index.js 402 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482
  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 SCOPE_OTHER = 0b00000000,
  285. SCOPE_PROGRAM = 0b00000001,
  286. SCOPE_FUNCTION = 0b00000010,
  287. SCOPE_ARROW = 0b00000100,
  288. SCOPE_SIMPLE_CATCH = 0b00001000,
  289. SCOPE_SUPER = 0b00010000,
  290. SCOPE_DIRECT_SUPER = 0b00100000,
  291. SCOPE_CLASS = 0b01000000,
  292. SCOPE_TS_MODULE = 0b10000000,
  293. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  294. const BIND_KIND_VALUE = 0b00000000001,
  295. BIND_KIND_TYPE = 0b00000000010,
  296. BIND_SCOPE_VAR = 0b00000000100,
  297. BIND_SCOPE_LEXICAL = 0b00000001000,
  298. BIND_SCOPE_FUNCTION = 0b00000010000,
  299. BIND_FLAGS_NONE = 0b00001000000,
  300. BIND_FLAGS_CLASS = 0b00010000000,
  301. BIND_FLAGS_TS_ENUM = 0b00100000000,
  302. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  303. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  304. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  305. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  306. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  307. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  308. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  309. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  310. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  311. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  312. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  313. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  314. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  315. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  316. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  317. CLASS_ELEMENT_KIND_GETTER = 0b010,
  318. CLASS_ELEMENT_KIND_SETTER = 0b001,
  319. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  320. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  321. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  322. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  323. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  324. CLASS_ELEMENT_OTHER = 0;
  325. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  326. const lineBreakG = new RegExp(lineBreak.source, "g");
  327. function isNewLine(code) {
  328. switch (code) {
  329. case 10:
  330. case 13:
  331. case 8232:
  332. case 8233:
  333. return true;
  334. default:
  335. return false;
  336. }
  337. }
  338. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  339. function isWhitespace(code) {
  340. switch (code) {
  341. case 0x0009:
  342. case 0x000b:
  343. case 0x000c:
  344. case 32:
  345. case 160:
  346. case 5760:
  347. case 0x2000:
  348. case 0x2001:
  349. case 0x2002:
  350. case 0x2003:
  351. case 0x2004:
  352. case 0x2005:
  353. case 0x2006:
  354. case 0x2007:
  355. case 0x2008:
  356. case 0x2009:
  357. case 0x200a:
  358. case 0x202f:
  359. case 0x205f:
  360. case 0x3000:
  361. case 0xfeff:
  362. return true;
  363. default:
  364. return false;
  365. }
  366. }
  367. class Position {
  368. constructor(line, col) {
  369. this.line = void 0;
  370. this.column = void 0;
  371. this.line = line;
  372. this.column = col;
  373. }
  374. }
  375. class SourceLocation {
  376. constructor(start, end) {
  377. this.start = void 0;
  378. this.end = void 0;
  379. this.filename = void 0;
  380. this.identifierName = void 0;
  381. this.start = start;
  382. this.end = end;
  383. }
  384. }
  385. function getLineInfo(input, offset) {
  386. let line = 1;
  387. let lineStart = 0;
  388. let match;
  389. lineBreakG.lastIndex = 0;
  390. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  391. line++;
  392. lineStart = lineBreakG.lastIndex;
  393. }
  394. return new Position(line, offset - lineStart);
  395. }
  396. class BaseParser {
  397. constructor() {
  398. this.sawUnambiguousESM = false;
  399. this.ambiguousScriptDifferentAst = false;
  400. }
  401. hasPlugin(name) {
  402. return this.plugins.has(name);
  403. }
  404. getPluginOption(plugin, name) {
  405. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  406. }
  407. }
  408. function last(stack) {
  409. return stack[stack.length - 1];
  410. }
  411. class CommentsParser extends BaseParser {
  412. addComment(comment) {
  413. if (this.filename) comment.loc.filename = this.filename;
  414. this.state.trailingComments.push(comment);
  415. this.state.leadingComments.push(comment);
  416. }
  417. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  418. if (this.state.leadingComments.length === 0) {
  419. return;
  420. }
  421. let lastElement = null;
  422. let i = elements.length;
  423. while (lastElement === null && i > 0) {
  424. lastElement = elements[--i];
  425. }
  426. if (lastElement === null) {
  427. return;
  428. }
  429. for (let j = 0; j < this.state.leadingComments.length; j++) {
  430. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  431. this.state.leadingComments.splice(j, 1);
  432. j--;
  433. }
  434. }
  435. const newTrailingComments = [];
  436. for (let i = 0; i < this.state.leadingComments.length; i++) {
  437. const leadingComment = this.state.leadingComments[i];
  438. if (leadingComment.end < node.end) {
  439. newTrailingComments.push(leadingComment);
  440. if (!takeAllComments) {
  441. this.state.leadingComments.splice(i, 1);
  442. i--;
  443. }
  444. } else {
  445. if (node.trailingComments === undefined) {
  446. node.trailingComments = [];
  447. }
  448. node.trailingComments.push(leadingComment);
  449. }
  450. }
  451. if (takeAllComments) this.state.leadingComments = [];
  452. if (newTrailingComments.length > 0) {
  453. lastElement.trailingComments = newTrailingComments;
  454. } else if (lastElement.trailingComments !== undefined) {
  455. lastElement.trailingComments = [];
  456. }
  457. }
  458. processComment(node) {
  459. if (node.type === "Program" && node.body.length > 0) return;
  460. const stack = this.state.commentStack;
  461. let firstChild, lastChild, trailingComments, i, j;
  462. if (this.state.trailingComments.length > 0) {
  463. if (this.state.trailingComments[0].start >= node.end) {
  464. trailingComments = this.state.trailingComments;
  465. this.state.trailingComments = [];
  466. } else {
  467. this.state.trailingComments.length = 0;
  468. }
  469. } else if (stack.length > 0) {
  470. const lastInStack = last(stack);
  471. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  472. trailingComments = lastInStack.trailingComments;
  473. delete lastInStack.trailingComments;
  474. }
  475. }
  476. if (stack.length > 0 && last(stack).start >= node.start) {
  477. firstChild = stack.pop();
  478. }
  479. while (stack.length > 0 && last(stack).start >= node.start) {
  480. lastChild = stack.pop();
  481. }
  482. if (!lastChild && firstChild) lastChild = firstChild;
  483. if (firstChild) {
  484. switch (node.type) {
  485. case "ObjectExpression":
  486. this.adjustCommentsAfterTrailingComma(node, node.properties);
  487. break;
  488. case "ObjectPattern":
  489. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  490. break;
  491. case "CallExpression":
  492. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  493. break;
  494. case "ArrayExpression":
  495. this.adjustCommentsAfterTrailingComma(node, node.elements);
  496. break;
  497. case "ArrayPattern":
  498. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  499. break;
  500. }
  501. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  502. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  503. }
  504. if (lastChild) {
  505. if (lastChild.leadingComments) {
  506. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  507. node.leadingComments = lastChild.leadingComments;
  508. delete lastChild.leadingComments;
  509. } else {
  510. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  511. if (lastChild.leadingComments[i].end <= node.start) {
  512. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  513. break;
  514. }
  515. }
  516. }
  517. }
  518. } else if (this.state.leadingComments.length > 0) {
  519. if (last(this.state.leadingComments).end <= node.start) {
  520. if (this.state.commentPreviousNode) {
  521. for (j = 0; j < this.state.leadingComments.length; j++) {
  522. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  523. this.state.leadingComments.splice(j, 1);
  524. j--;
  525. }
  526. }
  527. }
  528. if (this.state.leadingComments.length > 0) {
  529. node.leadingComments = this.state.leadingComments;
  530. this.state.leadingComments = [];
  531. }
  532. } else {
  533. for (i = 0; i < this.state.leadingComments.length; i++) {
  534. if (this.state.leadingComments[i].end > node.start) {
  535. break;
  536. }
  537. }
  538. const leadingComments = this.state.leadingComments.slice(0, i);
  539. if (leadingComments.length) {
  540. node.leadingComments = leadingComments;
  541. }
  542. trailingComments = this.state.leadingComments.slice(i);
  543. if (trailingComments.length === 0) {
  544. trailingComments = null;
  545. }
  546. }
  547. }
  548. this.state.commentPreviousNode = node;
  549. if (trailingComments) {
  550. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  551. node.innerComments = trailingComments;
  552. } else {
  553. const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end);
  554. if (firstTrailingCommentIndex > 0) {
  555. node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex);
  556. node.trailingComments = trailingComments.slice(firstTrailingCommentIndex);
  557. } else {
  558. node.trailingComments = trailingComments;
  559. }
  560. }
  561. }
  562. stack.push(node);
  563. }
  564. }
  565. const ErrorMessages = Object.freeze({
  566. AccessorIsGenerator: "A %0ter cannot be a generator",
  567. ArgumentsInClass: "'arguments' is only allowed in functions and class methods",
  568. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  569. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  570. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  571. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules",
  572. AwaitNotInAsyncFunction: "'await' is only allowed within async functions",
  573. BadGetterArity: "getter must not have any formal parameters",
  574. BadSetterArity: "setter must have exactly one formal parameter",
  575. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  576. ConstructorClassField: "Classes may not have a field named 'constructor'",
  577. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  578. ConstructorIsAccessor: "Class constructor may not be an accessor",
  579. ConstructorIsAsync: "Constructor can't be an async function",
  580. ConstructorIsGenerator: "Constructor can't be a generator",
  581. DeclarationMissingInitializer: "%0 require an initialization value",
  582. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  583. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  584. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  585. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  586. DecoratorStaticBlock: "Decorators can't be used with a static block",
  587. DeletePrivateField: "Deleting a private field is not allowed",
  588. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  589. DuplicateConstructor: "Duplicate constructor in the same class",
  590. DuplicateDefaultExport: "Only one default export allowed per module.",
  591. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  592. DuplicateProto: "Redefinition of __proto__ property",
  593. DuplicateRegExpFlags: "Duplicate regular expression flag",
  594. DuplicateStaticBlock: "Duplicate static block in the same class",
  595. ElementAfterRest: "Rest element must be last element",
  596. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  597. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { %0 as '%1' } from 'some-module'`?",
  598. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'",
  599. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  600. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  601. IllegalBreakContinue: "Unsyntactic %0",
  602. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  603. IllegalReturn: "'return' outside of function",
  604. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  605. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  606. ImportCallArity: "import() requires exactly %0",
  607. ImportCallNotNewExpression: "Cannot use new with import(...)",
  608. ImportCallSpreadArgument: "... is not allowed in import()",
  609. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  610. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  611. InvalidBigIntLiteral: "Invalid BigIntLiteral",
  612. InvalidCodePoint: "Code point out of bounds",
  613. InvalidDecimal: "Invalid decimal",
  614. InvalidDigit: "Expected number in radix %0",
  615. InvalidEscapeSequence: "Bad character escape sequence",
  616. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  617. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  618. InvalidIdentifier: "Invalid identifier %0",
  619. InvalidLhs: "Invalid left-hand side in %0",
  620. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  621. InvalidNumber: "Invalid number",
  622. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'",
  623. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  624. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  625. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  626. InvalidPropertyBindingPattern: "Binding member expression",
  627. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions",
  628. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  629. LabelRedeclaration: "Label '%0' is already declared",
  630. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  631. LineTerminatorBeforeArrow: "No line break is allowed before '=>'",
  632. MalformedRegExpFlags: "Invalid regular expression flag",
  633. MissingClassName: "A class name is required",
  634. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  635. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  636. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  637. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
  638. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
  639. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
  640. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
  641. ModuleExportUndefined: "Export '%0' is not defined",
  642. MultipleDefaultsInSwitch: "Multiple default clauses",
  643. NewlineAfterThrow: "Illegal newline after throw",
  644. NoCatchOrFinally: "Missing catch or finally clause",
  645. NumberIdentifier: "Identifier directly after number",
  646. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  647. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  648. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  649. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  650. ParamDupe: "Argument name clash",
  651. PatternHasAccessor: "Object pattern can't contain getter or setter",
  652. PatternHasMethod: "Object pattern can't contain methods",
  653. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  654. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  655. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  656. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  657. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  658. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  659. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
  660. PrivateNameRedeclaration: "Duplicate private name #%0",
  661. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  662. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  663. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  664. RecordNoProto: "'__proto__' is not allowed in Record expressions",
  665. RestTrailingComma: "Unexpected trailing comma after rest element",
  666. 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",
  667. StaticPrototype: "Classes may not have static property named prototype",
  668. StrictDelete: "Deleting local variable in strict mode",
  669. StrictEvalArguments: "Assigning to '%0' in strict mode",
  670. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  671. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  672. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
  673. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  674. StrictWith: "'with' in strict mode",
  675. 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?",
  676. SuperPrivateField: "Private fields can't be accessed on super",
  677. TrailingDecorator: "Decorators must be attached to a class element",
  678. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  679. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  680. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  681. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  682. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  683. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  684. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  685. UnexpectedKeyword: "Unexpected keyword '%0'",
  686. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  687. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  688. UnexpectedNewTarget: "new.target can only be used in functions",
  689. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  690. 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).",
  691. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  692. UnexpectedSuper: "super is only allowed in object methods and classes",
  693. UnexpectedToken: "Unexpected token '%0'",
  694. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  695. UnsupportedBind: "Binding should be performed on object property.",
  696. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  697. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  698. UnsupportedImport: "import can only be used in import() or import.meta",
  699. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  700. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  701. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  702. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  703. UnterminatedComment: "Unterminated comment",
  704. UnterminatedRegExp: "Unterminated regular expression",
  705. UnterminatedString: "Unterminated string constant",
  706. UnterminatedTemplate: "Unterminated template",
  707. VarRedeclaration: "Identifier '%0' has already been declared",
  708. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  709. YieldInParameter: "Yield expression is not allowed in formal parameters",
  710. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  711. });
  712. class ParserError extends CommentsParser {
  713. getLocationForPosition(pos) {
  714. let loc;
  715. 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);
  716. return loc;
  717. }
  718. raise(pos, errorTemplate, ...params) {
  719. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  720. }
  721. raiseWithData(pos, data, errorTemplate, ...params) {
  722. const loc = this.getLocationForPosition(pos);
  723. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  724. return this._raise(Object.assign({
  725. loc,
  726. pos
  727. }, data), message);
  728. }
  729. _raise(errorContext, message) {
  730. const err = new SyntaxError(message);
  731. Object.assign(err, errorContext);
  732. if (this.options.errorRecovery) {
  733. if (!this.isLookahead) this.state.errors.push(err);
  734. return err;
  735. } else {
  736. throw err;
  737. }
  738. }
  739. }
  740. function isSimpleProperty(node) {
  741. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  742. }
  743. var estree = (superClass => class extends superClass {
  744. estreeParseRegExpLiteral({
  745. pattern,
  746. flags
  747. }) {
  748. let regex = null;
  749. try {
  750. regex = new RegExp(pattern, flags);
  751. } catch (e) {}
  752. const node = this.estreeParseLiteral(regex);
  753. node.regex = {
  754. pattern,
  755. flags
  756. };
  757. return node;
  758. }
  759. estreeParseBigIntLiteral(value) {
  760. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  761. const node = this.estreeParseLiteral(bigInt);
  762. node.bigint = String(node.value || value);
  763. return node;
  764. }
  765. estreeParseDecimalLiteral(value) {
  766. const decimal = null;
  767. const node = this.estreeParseLiteral(decimal);
  768. node.decimal = String(node.value || value);
  769. return node;
  770. }
  771. estreeParseLiteral(value) {
  772. return this.parseLiteral(value, "Literal");
  773. }
  774. directiveToStmt(directive) {
  775. const directiveLiteral = directive.value;
  776. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  777. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  778. expression.value = directiveLiteral.value;
  779. expression.raw = directiveLiteral.extra.raw;
  780. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  781. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  782. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  783. }
  784. initFunction(node, isAsync) {
  785. super.initFunction(node, isAsync);
  786. node.expression = false;
  787. }
  788. checkDeclaration(node) {
  789. if (isSimpleProperty(node)) {
  790. this.checkDeclaration(node.value);
  791. } else {
  792. super.checkDeclaration(node);
  793. }
  794. }
  795. getObjectOrClassMethodParams(method) {
  796. return method.value.params;
  797. }
  798. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding) {
  799. switch (expr.type) {
  800. case "ObjectPattern":
  801. expr.properties.forEach(prop => {
  802. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  803. });
  804. break;
  805. default:
  806. super.checkLVal(expr, bindingType, checkClashes, contextDescription, disallowLetBinding);
  807. }
  808. }
  809. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  810. if (prop.method) {
  811. return;
  812. }
  813. super.checkProto(prop, isRecord, protoRef, refExpressionErrors);
  814. }
  815. isValidDirective(stmt) {
  816. var _stmt$expression$extr;
  817. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) == null ? void 0 : _stmt$expression$extr.parenthesized);
  818. }
  819. stmtToDirective(stmt) {
  820. const directive = super.stmtToDirective(stmt);
  821. const value = stmt.expression.value;
  822. directive.value.value = value;
  823. return directive;
  824. }
  825. parseBlockBody(node, allowDirectives, topLevel, end) {
  826. super.parseBlockBody(node, allowDirectives, topLevel, end);
  827. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  828. node.body = directiveStatements.concat(node.body);
  829. delete node.directives;
  830. }
  831. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  832. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  833. if (method.typeParameters) {
  834. method.value.typeParameters = method.typeParameters;
  835. delete method.typeParameters;
  836. }
  837. classBody.body.push(method);
  838. }
  839. parseExprAtom(refExpressionErrors) {
  840. switch (this.state.type) {
  841. case types.num:
  842. case types.string:
  843. return this.estreeParseLiteral(this.state.value);
  844. case types.regexp:
  845. return this.estreeParseRegExpLiteral(this.state.value);
  846. case types.bigint:
  847. return this.estreeParseBigIntLiteral(this.state.value);
  848. case types.decimal:
  849. return this.estreeParseDecimalLiteral(this.state.value);
  850. case types._null:
  851. return this.estreeParseLiteral(null);
  852. case types._true:
  853. return this.estreeParseLiteral(true);
  854. case types._false:
  855. return this.estreeParseLiteral(false);
  856. default:
  857. return super.parseExprAtom(refExpressionErrors);
  858. }
  859. }
  860. parseLiteral(value, type, startPos, startLoc) {
  861. const node = super.parseLiteral(value, type, startPos, startLoc);
  862. node.raw = node.extra.raw;
  863. delete node.extra;
  864. return node;
  865. }
  866. parseFunctionBody(node, allowExpression, isMethod = false) {
  867. super.parseFunctionBody(node, allowExpression, isMethod);
  868. node.expression = node.body.type !== "BlockStatement";
  869. }
  870. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  871. let funcNode = this.startNode();
  872. funcNode.kind = node.kind;
  873. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  874. funcNode.type = "FunctionExpression";
  875. delete funcNode.kind;
  876. node.value = funcNode;
  877. type = type === "ClassMethod" ? "MethodDefinition" : type;
  878. return this.finishNode(node, type);
  879. }
  880. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  881. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  882. if (node) {
  883. node.type = "Property";
  884. if (node.kind === "method") node.kind = "init";
  885. node.shorthand = false;
  886. }
  887. return node;
  888. }
  889. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  890. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  891. if (node) {
  892. node.kind = "init";
  893. node.type = "Property";
  894. }
  895. return node;
  896. }
  897. toAssignable(node) {
  898. if (isSimpleProperty(node)) {
  899. this.toAssignable(node.value);
  900. return node;
  901. }
  902. return super.toAssignable(node);
  903. }
  904. toAssignableObjectExpressionProp(prop, isLast) {
  905. if (prop.kind === "get" || prop.kind === "set") {
  906. throw this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  907. } else if (prop.method) {
  908. throw this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  909. } else {
  910. super.toAssignableObjectExpressionProp(prop, isLast);
  911. }
  912. }
  913. finishCallExpression(node, optional) {
  914. super.finishCallExpression(node, optional);
  915. if (node.callee.type === "Import") {
  916. node.type = "ImportExpression";
  917. node.source = node.arguments[0];
  918. delete node.arguments;
  919. delete node.callee;
  920. }
  921. return node;
  922. }
  923. toReferencedArguments(node) {
  924. if (node.type === "ImportExpression") {
  925. return;
  926. }
  927. super.toReferencedArguments(node);
  928. }
  929. parseExport(node) {
  930. super.parseExport(node);
  931. switch (node.type) {
  932. case "ExportAllDeclaration":
  933. node.exported = null;
  934. break;
  935. case "ExportNamedDeclaration":
  936. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  937. node.type = "ExportAllDeclaration";
  938. node.exported = node.specifiers[0].exported;
  939. delete node.specifiers;
  940. }
  941. break;
  942. }
  943. return node;
  944. }
  945. parseSubscript(base, startPos, startLoc, noCalls, state) {
  946. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  947. if (state.optionalChainMember) {
  948. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  949. node.type = node.type.substring(8);
  950. }
  951. if (state.stop) {
  952. const chain = this.startNodeAtNode(node);
  953. chain.expression = node;
  954. return this.finishNode(chain, "ChainExpression");
  955. }
  956. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  957. node.optional = false;
  958. }
  959. return node;
  960. }
  961. });
  962. class TokContext {
  963. constructor(token, isExpr, preserveSpace, override) {
  964. this.token = void 0;
  965. this.isExpr = void 0;
  966. this.preserveSpace = void 0;
  967. this.override = void 0;
  968. this.token = token;
  969. this.isExpr = !!isExpr;
  970. this.preserveSpace = !!preserveSpace;
  971. this.override = override;
  972. }
  973. }
  974. const types$1 = {
  975. braceStatement: new TokContext("{", false),
  976. braceExpression: new TokContext("{", true),
  977. recordExpression: new TokContext("#{", true),
  978. templateQuasi: new TokContext("${", false),
  979. parenStatement: new TokContext("(", false),
  980. parenExpression: new TokContext("(", true),
  981. template: new TokContext("`", true, true, p => p.readTmplToken()),
  982. functionExpression: new TokContext("function", true),
  983. functionStatement: new TokContext("function", false)
  984. };
  985. types.parenR.updateContext = types.braceR.updateContext = function () {
  986. if (this.state.context.length === 1) {
  987. this.state.exprAllowed = true;
  988. return;
  989. }
  990. let out = this.state.context.pop();
  991. if (out === types$1.braceStatement && this.curContext().token === "function") {
  992. out = this.state.context.pop();
  993. }
  994. this.state.exprAllowed = !out.isExpr;
  995. };
  996. types.name.updateContext = function (prevType) {
  997. let allowed = false;
  998. if (prevType !== types.dot) {
  999. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class) {
  1000. allowed = true;
  1001. }
  1002. }
  1003. this.state.exprAllowed = allowed;
  1004. if (this.state.isIterator) {
  1005. this.state.isIterator = false;
  1006. }
  1007. };
  1008. types.braceL.updateContext = function (prevType) {
  1009. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  1010. this.state.exprAllowed = true;
  1011. };
  1012. types.dollarBraceL.updateContext = function () {
  1013. this.state.context.push(types$1.templateQuasi);
  1014. this.state.exprAllowed = true;
  1015. };
  1016. types.parenL.updateContext = function (prevType) {
  1017. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  1018. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  1019. this.state.exprAllowed = true;
  1020. };
  1021. types.incDec.updateContext = function () {};
  1022. types._function.updateContext = types._class.updateContext = function (prevType) {
  1023. 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)) {
  1024. this.state.context.push(types$1.functionExpression);
  1025. } else {
  1026. this.state.context.push(types$1.functionStatement);
  1027. }
  1028. this.state.exprAllowed = false;
  1029. };
  1030. types.backQuote.updateContext = function () {
  1031. if (this.curContext() === types$1.template) {
  1032. this.state.context.pop();
  1033. } else {
  1034. this.state.context.push(types$1.template);
  1035. }
  1036. this.state.exprAllowed = false;
  1037. };
  1038. types.braceHashL.updateContext = function () {
  1039. this.state.context.push(types$1.recordExpression);
  1040. this.state.exprAllowed = true;
  1041. };
  1042. 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";
  1043. 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";
  1044. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1045. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1046. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1047. 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];
  1048. 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];
  1049. function isInAstralSet(code, set) {
  1050. let pos = 0x10000;
  1051. for (let i = 0, length = set.length; i < length; i += 2) {
  1052. pos += set[i];
  1053. if (pos > code) return false;
  1054. pos += set[i + 1];
  1055. if (pos >= code) return true;
  1056. }
  1057. return false;
  1058. }
  1059. function isIdentifierStart(code) {
  1060. if (code < 65) return code === 36;
  1061. if (code <= 90) return true;
  1062. if (code < 97) return code === 95;
  1063. if (code <= 122) return true;
  1064. if (code <= 0xffff) {
  1065. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1066. }
  1067. return isInAstralSet(code, astralIdentifierStartCodes);
  1068. }
  1069. function isIdentifierChar(code) {
  1070. if (code < 48) return code === 36;
  1071. if (code < 58) return true;
  1072. if (code < 65) return false;
  1073. if (code <= 90) return true;
  1074. if (code < 97) return code === 95;
  1075. if (code <= 122) return true;
  1076. if (code <= 0xffff) {
  1077. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1078. }
  1079. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1080. }
  1081. const reservedWords = {
  1082. 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"],
  1083. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1084. strictBind: ["eval", "arguments"]
  1085. };
  1086. const keywords$1 = new Set(reservedWords.keyword);
  1087. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1088. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1089. function isReservedWord(word, inModule) {
  1090. return inModule && word === "await" || word === "enum";
  1091. }
  1092. function isStrictReservedWord(word, inModule) {
  1093. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1094. }
  1095. function isStrictBindOnlyReservedWord(word) {
  1096. return reservedWordsStrictBindSet.has(word);
  1097. }
  1098. function isStrictBindReservedWord(word, inModule) {
  1099. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1100. }
  1101. function isKeyword(word) {
  1102. return keywords$1.has(word);
  1103. }
  1104. const keywordRelationalOperator = /^in(stanceof)?$/;
  1105. function isIteratorStart(current, next) {
  1106. return current === 64 && next === 64;
  1107. }
  1108. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1109. const FlowErrors = Object.freeze({
  1110. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1111. 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",
  1112. AssignReservedType: "Cannot overwrite reserved type %0",
  1113. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1114. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1115. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1116. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1117. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1118. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1119. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1120. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1121. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1122. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1123. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1124. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1125. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1126. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1127. 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",
  1128. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1129. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1130. InexactVariance: "Explicit inexact syntax cannot have variance",
  1131. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1132. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1133. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1134. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1135. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1136. SpreadVariance: "Spread properties cannot have variance",
  1137. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1138. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1139. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1140. UnexpectedReservedType: "Unexpected reserved type %0",
  1141. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1142. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1143. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1144. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1145. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1146. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  1147. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1148. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1149. UnterminatedFlowComment: "Unterminated flow-comment"
  1150. });
  1151. function isEsModuleType(bodyElement) {
  1152. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1153. }
  1154. function hasTypeImportKind(node) {
  1155. return node.importKind === "type" || node.importKind === "typeof";
  1156. }
  1157. function isMaybeDefaultImport(state) {
  1158. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1159. }
  1160. const exportSuggestions = {
  1161. const: "declare export var",
  1162. let: "declare export var",
  1163. type: "export type",
  1164. interface: "export interface"
  1165. };
  1166. function partition(list, test) {
  1167. const list1 = [];
  1168. const list2 = [];
  1169. for (let i = 0; i < list.length; i++) {
  1170. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1171. }
  1172. return [list1, list2];
  1173. }
  1174. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1175. var flow = (superClass => {
  1176. var _temp;
  1177. return _temp = class extends superClass {
  1178. constructor(options, input) {
  1179. super(options, input);
  1180. this.flowPragma = void 0;
  1181. this.flowPragma = undefined;
  1182. }
  1183. shouldParseTypes() {
  1184. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1185. }
  1186. shouldParseEnums() {
  1187. return !!this.getPluginOption("flow", "enums");
  1188. }
  1189. finishToken(type, val) {
  1190. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1191. if (this.flowPragma === undefined) {
  1192. this.flowPragma = null;
  1193. }
  1194. }
  1195. return super.finishToken(type, val);
  1196. }
  1197. addComment(comment) {
  1198. if (this.flowPragma === undefined) {
  1199. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1200. if (!matches) ; else if (matches[1] === "flow") {
  1201. this.flowPragma = "flow";
  1202. } else if (matches[1] === "noflow") {
  1203. this.flowPragma = "noflow";
  1204. } else {
  1205. throw new Error("Unexpected flow pragma");
  1206. }
  1207. }
  1208. return super.addComment(comment);
  1209. }
  1210. flowParseTypeInitialiser(tok) {
  1211. const oldInType = this.state.inType;
  1212. this.state.inType = true;
  1213. this.expect(tok || types.colon);
  1214. const type = this.flowParseType();
  1215. this.state.inType = oldInType;
  1216. return type;
  1217. }
  1218. flowParsePredicate() {
  1219. const node = this.startNode();
  1220. const moduloLoc = this.state.startLoc;
  1221. const moduloPos = this.state.start;
  1222. this.expect(types.modulo);
  1223. const checksLoc = this.state.startLoc;
  1224. this.expectContextual("checks");
  1225. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1226. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1227. }
  1228. if (this.eat(types.parenL)) {
  1229. node.value = this.parseExpression();
  1230. this.expect(types.parenR);
  1231. return this.finishNode(node, "DeclaredPredicate");
  1232. } else {
  1233. return this.finishNode(node, "InferredPredicate");
  1234. }
  1235. }
  1236. flowParseTypeAndPredicateInitialiser() {
  1237. const oldInType = this.state.inType;
  1238. this.state.inType = true;
  1239. this.expect(types.colon);
  1240. let type = null;
  1241. let predicate = null;
  1242. if (this.match(types.modulo)) {
  1243. this.state.inType = oldInType;
  1244. predicate = this.flowParsePredicate();
  1245. } else {
  1246. type = this.flowParseType();
  1247. this.state.inType = oldInType;
  1248. if (this.match(types.modulo)) {
  1249. predicate = this.flowParsePredicate();
  1250. }
  1251. }
  1252. return [type, predicate];
  1253. }
  1254. flowParseDeclareClass(node) {
  1255. this.next();
  1256. this.flowParseInterfaceish(node, true);
  1257. return this.finishNode(node, "DeclareClass");
  1258. }
  1259. flowParseDeclareFunction(node) {
  1260. this.next();
  1261. const id = node.id = this.parseIdentifier();
  1262. const typeNode = this.startNode();
  1263. const typeContainer = this.startNode();
  1264. if (this.isRelational("<")) {
  1265. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1266. } else {
  1267. typeNode.typeParameters = null;
  1268. }
  1269. this.expect(types.parenL);
  1270. const tmp = this.flowParseFunctionTypeParams();
  1271. typeNode.params = tmp.params;
  1272. typeNode.rest = tmp.rest;
  1273. this.expect(types.parenR);
  1274. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1275. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1276. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1277. this.resetEndLocation(id);
  1278. this.semicolon();
  1279. return this.finishNode(node, "DeclareFunction");
  1280. }
  1281. flowParseDeclare(node, insideModule) {
  1282. if (this.match(types._class)) {
  1283. return this.flowParseDeclareClass(node);
  1284. } else if (this.match(types._function)) {
  1285. return this.flowParseDeclareFunction(node);
  1286. } else if (this.match(types._var)) {
  1287. return this.flowParseDeclareVariable(node);
  1288. } else if (this.eatContextual("module")) {
  1289. if (this.match(types.dot)) {
  1290. return this.flowParseDeclareModuleExports(node);
  1291. } else {
  1292. if (insideModule) {
  1293. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1294. }
  1295. return this.flowParseDeclareModule(node);
  1296. }
  1297. } else if (this.isContextual("type")) {
  1298. return this.flowParseDeclareTypeAlias(node);
  1299. } else if (this.isContextual("opaque")) {
  1300. return this.flowParseDeclareOpaqueType(node);
  1301. } else if (this.isContextual("interface")) {
  1302. return this.flowParseDeclareInterface(node);
  1303. } else if (this.match(types._export)) {
  1304. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1305. } else {
  1306. throw this.unexpected();
  1307. }
  1308. }
  1309. flowParseDeclareVariable(node) {
  1310. this.next();
  1311. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1312. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1313. this.semicolon();
  1314. return this.finishNode(node, "DeclareVariable");
  1315. }
  1316. flowParseDeclareModule(node) {
  1317. this.scope.enter(SCOPE_OTHER);
  1318. if (this.match(types.string)) {
  1319. node.id = this.parseExprAtom();
  1320. } else {
  1321. node.id = this.parseIdentifier();
  1322. }
  1323. const bodyNode = node.body = this.startNode();
  1324. const body = bodyNode.body = [];
  1325. this.expect(types.braceL);
  1326. while (!this.match(types.braceR)) {
  1327. let bodyNode = this.startNode();
  1328. if (this.match(types._import)) {
  1329. this.next();
  1330. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1331. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1332. }
  1333. this.parseImport(bodyNode);
  1334. } else {
  1335. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1336. bodyNode = this.flowParseDeclare(bodyNode, true);
  1337. }
  1338. body.push(bodyNode);
  1339. }
  1340. this.scope.exit();
  1341. this.expect(types.braceR);
  1342. this.finishNode(bodyNode, "BlockStatement");
  1343. let kind = null;
  1344. let hasModuleExport = false;
  1345. body.forEach(bodyElement => {
  1346. if (isEsModuleType(bodyElement)) {
  1347. if (kind === "CommonJS") {
  1348. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1349. }
  1350. kind = "ES";
  1351. } else if (bodyElement.type === "DeclareModuleExports") {
  1352. if (hasModuleExport) {
  1353. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1354. }
  1355. if (kind === "ES") {
  1356. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1357. }
  1358. kind = "CommonJS";
  1359. hasModuleExport = true;
  1360. }
  1361. });
  1362. node.kind = kind || "CommonJS";
  1363. return this.finishNode(node, "DeclareModule");
  1364. }
  1365. flowParseDeclareExportDeclaration(node, insideModule) {
  1366. this.expect(types._export);
  1367. if (this.eat(types._default)) {
  1368. if (this.match(types._function) || this.match(types._class)) {
  1369. node.declaration = this.flowParseDeclare(this.startNode());
  1370. } else {
  1371. node.declaration = this.flowParseType();
  1372. this.semicolon();
  1373. }
  1374. node.default = true;
  1375. return this.finishNode(node, "DeclareExportDeclaration");
  1376. } else {
  1377. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1378. const label = this.state.value;
  1379. const suggestion = exportSuggestions[label];
  1380. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1381. }
  1382. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1383. node.declaration = this.flowParseDeclare(this.startNode());
  1384. node.default = false;
  1385. return this.finishNode(node, "DeclareExportDeclaration");
  1386. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1387. node = this.parseExport(node);
  1388. if (node.type === "ExportNamedDeclaration") {
  1389. node.type = "ExportDeclaration";
  1390. node.default = false;
  1391. delete node.exportKind;
  1392. }
  1393. node.type = "Declare" + node.type;
  1394. return node;
  1395. }
  1396. }
  1397. throw this.unexpected();
  1398. }
  1399. flowParseDeclareModuleExports(node) {
  1400. this.next();
  1401. this.expectContextual("exports");
  1402. node.typeAnnotation = this.flowParseTypeAnnotation();
  1403. this.semicolon();
  1404. return this.finishNode(node, "DeclareModuleExports");
  1405. }
  1406. flowParseDeclareTypeAlias(node) {
  1407. this.next();
  1408. this.flowParseTypeAlias(node);
  1409. node.type = "DeclareTypeAlias";
  1410. return node;
  1411. }
  1412. flowParseDeclareOpaqueType(node) {
  1413. this.next();
  1414. this.flowParseOpaqueType(node, true);
  1415. node.type = "DeclareOpaqueType";
  1416. return node;
  1417. }
  1418. flowParseDeclareInterface(node) {
  1419. this.next();
  1420. this.flowParseInterfaceish(node);
  1421. return this.finishNode(node, "DeclareInterface");
  1422. }
  1423. flowParseInterfaceish(node, isClass = false) {
  1424. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1425. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1426. if (this.isRelational("<")) {
  1427. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1428. } else {
  1429. node.typeParameters = null;
  1430. }
  1431. node.extends = [];
  1432. node.implements = [];
  1433. node.mixins = [];
  1434. if (this.eat(types._extends)) {
  1435. do {
  1436. node.extends.push(this.flowParseInterfaceExtends());
  1437. } while (!isClass && this.eat(types.comma));
  1438. }
  1439. if (this.isContextual("mixins")) {
  1440. this.next();
  1441. do {
  1442. node.mixins.push(this.flowParseInterfaceExtends());
  1443. } while (this.eat(types.comma));
  1444. }
  1445. if (this.isContextual("implements")) {
  1446. this.next();
  1447. do {
  1448. node.implements.push(this.flowParseInterfaceExtends());
  1449. } while (this.eat(types.comma));
  1450. }
  1451. node.body = this.flowParseObjectType({
  1452. allowStatic: isClass,
  1453. allowExact: false,
  1454. allowSpread: false,
  1455. allowProto: isClass,
  1456. allowInexact: false
  1457. });
  1458. }
  1459. flowParseInterfaceExtends() {
  1460. const node = this.startNode();
  1461. node.id = this.flowParseQualifiedTypeIdentifier();
  1462. if (this.isRelational("<")) {
  1463. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1464. } else {
  1465. node.typeParameters = null;
  1466. }
  1467. return this.finishNode(node, "InterfaceExtends");
  1468. }
  1469. flowParseInterface(node) {
  1470. this.flowParseInterfaceish(node);
  1471. return this.finishNode(node, "InterfaceDeclaration");
  1472. }
  1473. checkNotUnderscore(word) {
  1474. if (word === "_") {
  1475. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1476. }
  1477. }
  1478. checkReservedType(word, startLoc, declaration) {
  1479. if (!reservedTypes.has(word)) return;
  1480. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1481. }
  1482. flowParseRestrictedIdentifier(liberal, declaration) {
  1483. this.checkReservedType(this.state.value, this.state.start, declaration);
  1484. return this.parseIdentifier(liberal);
  1485. }
  1486. flowParseTypeAlias(node) {
  1487. node.id = this.flowParseRestrictedIdentifier(false, true);
  1488. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1489. if (this.isRelational("<")) {
  1490. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1491. } else {
  1492. node.typeParameters = null;
  1493. }
  1494. node.right = this.flowParseTypeInitialiser(types.eq);
  1495. this.semicolon();
  1496. return this.finishNode(node, "TypeAlias");
  1497. }
  1498. flowParseOpaqueType(node, declare) {
  1499. this.expectContextual("type");
  1500. node.id = this.flowParseRestrictedIdentifier(true, true);
  1501. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1502. if (this.isRelational("<")) {
  1503. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1504. } else {
  1505. node.typeParameters = null;
  1506. }
  1507. node.supertype = null;
  1508. if (this.match(types.colon)) {
  1509. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1510. }
  1511. node.impltype = null;
  1512. if (!declare) {
  1513. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1514. }
  1515. this.semicolon();
  1516. return this.finishNode(node, "OpaqueType");
  1517. }
  1518. flowParseTypeParameter(requireDefault = false) {
  1519. const nodeStart = this.state.start;
  1520. const node = this.startNode();
  1521. const variance = this.flowParseVariance();
  1522. const ident = this.flowParseTypeAnnotatableIdentifier();
  1523. node.name = ident.name;
  1524. node.variance = variance;
  1525. node.bound = ident.typeAnnotation;
  1526. if (this.match(types.eq)) {
  1527. this.eat(types.eq);
  1528. node.default = this.flowParseType();
  1529. } else {
  1530. if (requireDefault) {
  1531. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1532. }
  1533. }
  1534. return this.finishNode(node, "TypeParameter");
  1535. }
  1536. flowParseTypeParameterDeclaration() {
  1537. const oldInType = this.state.inType;
  1538. const node = this.startNode();
  1539. node.params = [];
  1540. this.state.inType = true;
  1541. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1542. this.next();
  1543. } else {
  1544. this.unexpected();
  1545. }
  1546. let defaultRequired = false;
  1547. do {
  1548. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1549. node.params.push(typeParameter);
  1550. if (typeParameter.default) {
  1551. defaultRequired = true;
  1552. }
  1553. if (!this.isRelational(">")) {
  1554. this.expect(types.comma);
  1555. }
  1556. } while (!this.isRelational(">"));
  1557. this.expectRelational(">");
  1558. this.state.inType = oldInType;
  1559. return this.finishNode(node, "TypeParameterDeclaration");
  1560. }
  1561. flowParseTypeParameterInstantiation() {
  1562. const node = this.startNode();
  1563. const oldInType = this.state.inType;
  1564. node.params = [];
  1565. this.state.inType = true;
  1566. this.expectRelational("<");
  1567. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1568. this.state.noAnonFunctionType = false;
  1569. while (!this.isRelational(">")) {
  1570. node.params.push(this.flowParseType());
  1571. if (!this.isRelational(">")) {
  1572. this.expect(types.comma);
  1573. }
  1574. }
  1575. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1576. this.expectRelational(">");
  1577. this.state.inType = oldInType;
  1578. return this.finishNode(node, "TypeParameterInstantiation");
  1579. }
  1580. flowParseTypeParameterInstantiationCallOrNew() {
  1581. const node = this.startNode();
  1582. const oldInType = this.state.inType;
  1583. node.params = [];
  1584. this.state.inType = true;
  1585. this.expectRelational("<");
  1586. while (!this.isRelational(">")) {
  1587. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1588. if (!this.isRelational(">")) {
  1589. this.expect(types.comma);
  1590. }
  1591. }
  1592. this.expectRelational(">");
  1593. this.state.inType = oldInType;
  1594. return this.finishNode(node, "TypeParameterInstantiation");
  1595. }
  1596. flowParseInterfaceType() {
  1597. const node = this.startNode();
  1598. this.expectContextual("interface");
  1599. node.extends = [];
  1600. if (this.eat(types._extends)) {
  1601. do {
  1602. node.extends.push(this.flowParseInterfaceExtends());
  1603. } while (this.eat(types.comma));
  1604. }
  1605. node.body = this.flowParseObjectType({
  1606. allowStatic: false,
  1607. allowExact: false,
  1608. allowSpread: false,
  1609. allowProto: false,
  1610. allowInexact: false
  1611. });
  1612. return this.finishNode(node, "InterfaceTypeAnnotation");
  1613. }
  1614. flowParseObjectPropertyKey() {
  1615. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1616. }
  1617. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1618. node.static = isStatic;
  1619. if (this.lookahead().type === types.colon) {
  1620. node.id = this.flowParseObjectPropertyKey();
  1621. node.key = this.flowParseTypeInitialiser();
  1622. } else {
  1623. node.id = null;
  1624. node.key = this.flowParseType();
  1625. }
  1626. this.expect(types.bracketR);
  1627. node.value = this.flowParseTypeInitialiser();
  1628. node.variance = variance;
  1629. return this.finishNode(node, "ObjectTypeIndexer");
  1630. }
  1631. flowParseObjectTypeInternalSlot(node, isStatic) {
  1632. node.static = isStatic;
  1633. node.id = this.flowParseObjectPropertyKey();
  1634. this.expect(types.bracketR);
  1635. this.expect(types.bracketR);
  1636. if (this.isRelational("<") || this.match(types.parenL)) {
  1637. node.method = true;
  1638. node.optional = false;
  1639. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1640. } else {
  1641. node.method = false;
  1642. if (this.eat(types.question)) {
  1643. node.optional = true;
  1644. }
  1645. node.value = this.flowParseTypeInitialiser();
  1646. }
  1647. return this.finishNode(node, "ObjectTypeInternalSlot");
  1648. }
  1649. flowParseObjectTypeMethodish(node) {
  1650. node.params = [];
  1651. node.rest = null;
  1652. node.typeParameters = null;
  1653. if (this.isRelational("<")) {
  1654. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1655. }
  1656. this.expect(types.parenL);
  1657. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1658. node.params.push(this.flowParseFunctionTypeParam());
  1659. if (!this.match(types.parenR)) {
  1660. this.expect(types.comma);
  1661. }
  1662. }
  1663. if (this.eat(types.ellipsis)) {
  1664. node.rest = this.flowParseFunctionTypeParam();
  1665. }
  1666. this.expect(types.parenR);
  1667. node.returnType = this.flowParseTypeInitialiser();
  1668. return this.finishNode(node, "FunctionTypeAnnotation");
  1669. }
  1670. flowParseObjectTypeCallProperty(node, isStatic) {
  1671. const valueNode = this.startNode();
  1672. node.static = isStatic;
  1673. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1674. return this.finishNode(node, "ObjectTypeCallProperty");
  1675. }
  1676. flowParseObjectType({
  1677. allowStatic,
  1678. allowExact,
  1679. allowSpread,
  1680. allowProto,
  1681. allowInexact
  1682. }) {
  1683. const oldInType = this.state.inType;
  1684. this.state.inType = true;
  1685. const nodeStart = this.startNode();
  1686. nodeStart.callProperties = [];
  1687. nodeStart.properties = [];
  1688. nodeStart.indexers = [];
  1689. nodeStart.internalSlots = [];
  1690. let endDelim;
  1691. let exact;
  1692. let inexact = false;
  1693. if (allowExact && this.match(types.braceBarL)) {
  1694. this.expect(types.braceBarL);
  1695. endDelim = types.braceBarR;
  1696. exact = true;
  1697. } else {
  1698. this.expect(types.braceL);
  1699. endDelim = types.braceR;
  1700. exact = false;
  1701. }
  1702. nodeStart.exact = exact;
  1703. while (!this.match(endDelim)) {
  1704. let isStatic = false;
  1705. let protoStart = null;
  1706. let inexactStart = null;
  1707. const node = this.startNode();
  1708. if (allowProto && this.isContextual("proto")) {
  1709. const lookahead = this.lookahead();
  1710. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1711. this.next();
  1712. protoStart = this.state.start;
  1713. allowStatic = false;
  1714. }
  1715. }
  1716. if (allowStatic && this.isContextual("static")) {
  1717. const lookahead = this.lookahead();
  1718. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1719. this.next();
  1720. isStatic = true;
  1721. }
  1722. }
  1723. const variance = this.flowParseVariance();
  1724. if (this.eat(types.bracketL)) {
  1725. if (protoStart != null) {
  1726. this.unexpected(protoStart);
  1727. }
  1728. if (this.eat(types.bracketL)) {
  1729. if (variance) {
  1730. this.unexpected(variance.start);
  1731. }
  1732. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1733. } else {
  1734. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1735. }
  1736. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1737. if (protoStart != null) {
  1738. this.unexpected(protoStart);
  1739. }
  1740. if (variance) {
  1741. this.unexpected(variance.start);
  1742. }
  1743. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1744. } else {
  1745. let kind = "init";
  1746. if (this.isContextual("get") || this.isContextual("set")) {
  1747. const lookahead = this.lookahead();
  1748. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1749. kind = this.state.value;
  1750. this.next();
  1751. }
  1752. }
  1753. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1754. if (propOrInexact === null) {
  1755. inexact = true;
  1756. inexactStart = this.state.lastTokStart;
  1757. } else {
  1758. nodeStart.properties.push(propOrInexact);
  1759. }
  1760. }
  1761. this.flowObjectTypeSemicolon();
  1762. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1763. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  1764. }
  1765. }
  1766. this.expect(endDelim);
  1767. if (allowSpread) {
  1768. nodeStart.inexact = inexact;
  1769. }
  1770. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1771. this.state.inType = oldInType;
  1772. return out;
  1773. }
  1774. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1775. if (this.eat(types.ellipsis)) {
  1776. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1777. if (isInexactToken) {
  1778. if (!allowSpread) {
  1779. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  1780. } else if (!allowInexact) {
  1781. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  1782. }
  1783. if (variance) {
  1784. this.raise(variance.start, FlowErrors.InexactVariance);
  1785. }
  1786. return null;
  1787. }
  1788. if (!allowSpread) {
  1789. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  1790. }
  1791. if (protoStart != null) {
  1792. this.unexpected(protoStart);
  1793. }
  1794. if (variance) {
  1795. this.raise(variance.start, FlowErrors.SpreadVariance);
  1796. }
  1797. node.argument = this.flowParseType();
  1798. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1799. } else {
  1800. node.key = this.flowParseObjectPropertyKey();
  1801. node.static = isStatic;
  1802. node.proto = protoStart != null;
  1803. node.kind = kind;
  1804. let optional = false;
  1805. if (this.isRelational("<") || this.match(types.parenL)) {
  1806. node.method = true;
  1807. if (protoStart != null) {
  1808. this.unexpected(protoStart);
  1809. }
  1810. if (variance) {
  1811. this.unexpected(variance.start);
  1812. }
  1813. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1814. if (kind === "get" || kind === "set") {
  1815. this.flowCheckGetterSetterParams(node);
  1816. }
  1817. } else {
  1818. if (kind !== "init") this.unexpected();
  1819. node.method = false;
  1820. if (this.eat(types.question)) {
  1821. optional = true;
  1822. }
  1823. node.value = this.flowParseTypeInitialiser();
  1824. node.variance = variance;
  1825. }
  1826. node.optional = optional;
  1827. return this.finishNode(node, "ObjectTypeProperty");
  1828. }
  1829. }
  1830. flowCheckGetterSetterParams(property) {
  1831. const paramCount = property.kind === "get" ? 0 : 1;
  1832. const start = property.start;
  1833. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1834. if (length !== paramCount) {
  1835. if (property.kind === "get") {
  1836. this.raise(start, ErrorMessages.BadGetterArity);
  1837. } else {
  1838. this.raise(start, ErrorMessages.BadSetterArity);
  1839. }
  1840. }
  1841. if (property.kind === "set" && property.value.rest) {
  1842. this.raise(start, ErrorMessages.BadSetterRestParameter);
  1843. }
  1844. }
  1845. flowObjectTypeSemicolon() {
  1846. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1847. this.unexpected();
  1848. }
  1849. }
  1850. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1851. startPos = startPos || this.state.start;
  1852. startLoc = startLoc || this.state.startLoc;
  1853. let node = id || this.flowParseRestrictedIdentifier(true);
  1854. while (this.eat(types.dot)) {
  1855. const node2 = this.startNodeAt(startPos, startLoc);
  1856. node2.qualification = node;
  1857. node2.id = this.flowParseRestrictedIdentifier(true);
  1858. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1859. }
  1860. return node;
  1861. }
  1862. flowParseGenericType(startPos, startLoc, id) {
  1863. const node = this.startNodeAt(startPos, startLoc);
  1864. node.typeParameters = null;
  1865. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1866. if (this.isRelational("<")) {
  1867. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1868. }
  1869. return this.finishNode(node, "GenericTypeAnnotation");
  1870. }
  1871. flowParseTypeofType() {
  1872. const node = this.startNode();
  1873. this.expect(types._typeof);
  1874. node.argument = this.flowParsePrimaryType();
  1875. return this.finishNode(node, "TypeofTypeAnnotation");
  1876. }
  1877. flowParseTupleType() {
  1878. const node = this.startNode();
  1879. node.types = [];
  1880. this.expect(types.bracketL);
  1881. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1882. node.types.push(this.flowParseType());
  1883. if (this.match(types.bracketR)) break;
  1884. this.expect(types.comma);
  1885. }
  1886. this.expect(types.bracketR);
  1887. return this.finishNode(node, "TupleTypeAnnotation");
  1888. }
  1889. flowParseFunctionTypeParam() {
  1890. let name = null;
  1891. let optional = false;
  1892. let typeAnnotation = null;
  1893. const node = this.startNode();
  1894. const lh = this.lookahead();
  1895. if (lh.type === types.colon || lh.type === types.question) {
  1896. name = this.parseIdentifier();
  1897. if (this.eat(types.question)) {
  1898. optional = true;
  1899. }
  1900. typeAnnotation = this.flowParseTypeInitialiser();
  1901. } else {
  1902. typeAnnotation = this.flowParseType();
  1903. }
  1904. node.name = name;
  1905. node.optional = optional;
  1906. node.typeAnnotation = typeAnnotation;
  1907. return this.finishNode(node, "FunctionTypeParam");
  1908. }
  1909. reinterpretTypeAsFunctionTypeParam(type) {
  1910. const node = this.startNodeAt(type.start, type.loc.start);
  1911. node.name = null;
  1912. node.optional = false;
  1913. node.typeAnnotation = type;
  1914. return this.finishNode(node, "FunctionTypeParam");
  1915. }
  1916. flowParseFunctionTypeParams(params = []) {
  1917. let rest = null;
  1918. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1919. params.push(this.flowParseFunctionTypeParam());
  1920. if (!this.match(types.parenR)) {
  1921. this.expect(types.comma);
  1922. }
  1923. }
  1924. if (this.eat(types.ellipsis)) {
  1925. rest = this.flowParseFunctionTypeParam();
  1926. }
  1927. return {
  1928. params,
  1929. rest
  1930. };
  1931. }
  1932. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1933. switch (id.name) {
  1934. case "any":
  1935. return this.finishNode(node, "AnyTypeAnnotation");
  1936. case "bool":
  1937. case "boolean":
  1938. return this.finishNode(node, "BooleanTypeAnnotation");
  1939. case "mixed":
  1940. return this.finishNode(node, "MixedTypeAnnotation");
  1941. case "empty":
  1942. return this.finishNode(node, "EmptyTypeAnnotation");
  1943. case "number":
  1944. return this.finishNode(node, "NumberTypeAnnotation");
  1945. case "string":
  1946. return this.finishNode(node, "StringTypeAnnotation");
  1947. case "symbol":
  1948. return this.finishNode(node, "SymbolTypeAnnotation");
  1949. default:
  1950. this.checkNotUnderscore(id.name);
  1951. return this.flowParseGenericType(startPos, startLoc, id);
  1952. }
  1953. }
  1954. flowParsePrimaryType() {
  1955. const startPos = this.state.start;
  1956. const startLoc = this.state.startLoc;
  1957. const node = this.startNode();
  1958. let tmp;
  1959. let type;
  1960. let isGroupedType = false;
  1961. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1962. switch (this.state.type) {
  1963. case types.name:
  1964. if (this.isContextual("interface")) {
  1965. return this.flowParseInterfaceType();
  1966. }
  1967. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1968. case types.braceL:
  1969. return this.flowParseObjectType({
  1970. allowStatic: false,
  1971. allowExact: false,
  1972. allowSpread: true,
  1973. allowProto: false,
  1974. allowInexact: true
  1975. });
  1976. case types.braceBarL:
  1977. return this.flowParseObjectType({
  1978. allowStatic: false,
  1979. allowExact: true,
  1980. allowSpread: true,
  1981. allowProto: false,
  1982. allowInexact: false
  1983. });
  1984. case types.bracketL:
  1985. this.state.noAnonFunctionType = false;
  1986. type = this.flowParseTupleType();
  1987. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1988. return type;
  1989. case types.relational:
  1990. if (this.state.value === "<") {
  1991. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1992. this.expect(types.parenL);
  1993. tmp = this.flowParseFunctionTypeParams();
  1994. node.params = tmp.params;
  1995. node.rest = tmp.rest;
  1996. this.expect(types.parenR);
  1997. this.expect(types.arrow);
  1998. node.returnType = this.flowParseType();
  1999. return this.finishNode(node, "FunctionTypeAnnotation");
  2000. }
  2001. break;
  2002. case types.parenL:
  2003. this.next();
  2004. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  2005. if (this.match(types.name)) {
  2006. const token = this.lookahead().type;
  2007. isGroupedType = token !== types.question && token !== types.colon;
  2008. } else {
  2009. isGroupedType = true;
  2010. }
  2011. }
  2012. if (isGroupedType) {
  2013. this.state.noAnonFunctionType = false;
  2014. type = this.flowParseType();
  2015. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2016. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  2017. this.expect(types.parenR);
  2018. return type;
  2019. } else {
  2020. this.eat(types.comma);
  2021. }
  2022. }
  2023. if (type) {
  2024. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  2025. } else {
  2026. tmp = this.flowParseFunctionTypeParams();
  2027. }
  2028. node.params = tmp.params;
  2029. node.rest = tmp.rest;
  2030. this.expect(types.parenR);
  2031. this.expect(types.arrow);
  2032. node.returnType = this.flowParseType();
  2033. node.typeParameters = null;
  2034. return this.finishNode(node, "FunctionTypeAnnotation");
  2035. case types.string:
  2036. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  2037. case types._true:
  2038. case types._false:
  2039. node.value = this.match(types._true);
  2040. this.next();
  2041. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  2042. case types.plusMin:
  2043. if (this.state.value === "-") {
  2044. this.next();
  2045. if (this.match(types.num)) {
  2046. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  2047. }
  2048. if (this.match(types.bigint)) {
  2049. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  2050. }
  2051. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  2052. }
  2053. throw this.unexpected();
  2054. case types.num:
  2055. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  2056. case types.bigint:
  2057. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  2058. case types._void:
  2059. this.next();
  2060. return this.finishNode(node, "VoidTypeAnnotation");
  2061. case types._null:
  2062. this.next();
  2063. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2064. case types._this:
  2065. this.next();
  2066. return this.finishNode(node, "ThisTypeAnnotation");
  2067. case types.star:
  2068. this.next();
  2069. return this.finishNode(node, "ExistsTypeAnnotation");
  2070. default:
  2071. if (this.state.type.keyword === "typeof") {
  2072. return this.flowParseTypeofType();
  2073. } else if (this.state.type.keyword) {
  2074. const label = this.state.type.label;
  2075. this.next();
  2076. return super.createIdentifier(node, label);
  2077. }
  2078. }
  2079. throw this.unexpected();
  2080. }
  2081. flowParsePostfixType() {
  2082. const startPos = this.state.start,
  2083. startLoc = this.state.startLoc;
  2084. let type = this.flowParsePrimaryType();
  2085. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2086. const node = this.startNodeAt(startPos, startLoc);
  2087. node.elementType = type;
  2088. this.expect(types.bracketL);
  2089. this.expect(types.bracketR);
  2090. type = this.finishNode(node, "ArrayTypeAnnotation");
  2091. }
  2092. return type;
  2093. }
  2094. flowParsePrefixType() {
  2095. const node = this.startNode();
  2096. if (this.eat(types.question)) {
  2097. node.typeAnnotation = this.flowParsePrefixType();
  2098. return this.finishNode(node, "NullableTypeAnnotation");
  2099. } else {
  2100. return this.flowParsePostfixType();
  2101. }
  2102. }
  2103. flowParseAnonFunctionWithoutParens() {
  2104. const param = this.flowParsePrefixType();
  2105. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2106. const node = this.startNodeAt(param.start, param.loc.start);
  2107. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2108. node.rest = null;
  2109. node.returnType = this.flowParseType();
  2110. node.typeParameters = null;
  2111. return this.finishNode(node, "FunctionTypeAnnotation");
  2112. }
  2113. return param;
  2114. }
  2115. flowParseIntersectionType() {
  2116. const node = this.startNode();
  2117. this.eat(types.bitwiseAND);
  2118. const type = this.flowParseAnonFunctionWithoutParens();
  2119. node.types = [type];
  2120. while (this.eat(types.bitwiseAND)) {
  2121. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2122. }
  2123. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2124. }
  2125. flowParseUnionType() {
  2126. const node = this.startNode();
  2127. this.eat(types.bitwiseOR);
  2128. const type = this.flowParseIntersectionType();
  2129. node.types = [type];
  2130. while (this.eat(types.bitwiseOR)) {
  2131. node.types.push(this.flowParseIntersectionType());
  2132. }
  2133. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2134. }
  2135. flowParseType() {
  2136. const oldInType = this.state.inType;
  2137. this.state.inType = true;
  2138. const type = this.flowParseUnionType();
  2139. this.state.inType = oldInType;
  2140. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2141. return type;
  2142. }
  2143. flowParseTypeOrImplicitInstantiation() {
  2144. if (this.state.type === types.name && this.state.value === "_") {
  2145. const startPos = this.state.start;
  2146. const startLoc = this.state.startLoc;
  2147. const node = this.parseIdentifier();
  2148. return this.flowParseGenericType(startPos, startLoc, node);
  2149. } else {
  2150. return this.flowParseType();
  2151. }
  2152. }
  2153. flowParseTypeAnnotation() {
  2154. const node = this.startNode();
  2155. node.typeAnnotation = this.flowParseTypeInitialiser();
  2156. return this.finishNode(node, "TypeAnnotation");
  2157. }
  2158. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2159. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2160. if (this.match(types.colon)) {
  2161. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2162. this.resetEndLocation(ident);
  2163. }
  2164. return ident;
  2165. }
  2166. typeCastToParameter(node) {
  2167. node.expression.typeAnnotation = node.typeAnnotation;
  2168. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2169. return node.expression;
  2170. }
  2171. flowParseVariance() {
  2172. let variance = null;
  2173. if (this.match(types.plusMin)) {
  2174. variance = this.startNode();
  2175. if (this.state.value === "+") {
  2176. variance.kind = "plus";
  2177. } else {
  2178. variance.kind = "minus";
  2179. }
  2180. this.next();
  2181. this.finishNode(variance, "Variance");
  2182. }
  2183. return variance;
  2184. }
  2185. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2186. if (allowExpressionBody) {
  2187. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2188. }
  2189. return super.parseFunctionBody(node, false, isMethod);
  2190. }
  2191. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2192. if (this.match(types.colon)) {
  2193. const typeNode = this.startNode();
  2194. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2195. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2196. }
  2197. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2198. }
  2199. parseStatement(context, topLevel) {
  2200. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2201. const lookahead = this.lookahead();
  2202. if (lookahead.type === types.name || isKeyword(lookahead.value)) {
  2203. const node = this.startNode();
  2204. this.next();
  2205. return this.flowParseInterface(node);
  2206. }
  2207. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2208. const node = this.startNode();
  2209. this.next();
  2210. return this.flowParseEnumDeclaration(node);
  2211. }
  2212. const stmt = super.parseStatement(context, topLevel);
  2213. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2214. this.flowPragma = null;
  2215. }
  2216. return stmt;
  2217. }
  2218. parseExpressionStatement(node, expr) {
  2219. if (expr.type === "Identifier") {
  2220. if (expr.name === "declare") {
  2221. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2222. return this.flowParseDeclare(node);
  2223. }
  2224. } else if (this.match(types.name)) {
  2225. if (expr.name === "interface") {
  2226. return this.flowParseInterface(node);
  2227. } else if (expr.name === "type") {
  2228. return this.flowParseTypeAlias(node);
  2229. } else if (expr.name === "opaque") {
  2230. return this.flowParseOpaqueType(node, false);
  2231. }
  2232. }
  2233. }
  2234. return super.parseExpressionStatement(node, expr);
  2235. }
  2236. shouldParseExportDeclaration() {
  2237. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2238. }
  2239. isExportDefaultSpecifier() {
  2240. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2241. return false;
  2242. }
  2243. return super.isExportDefaultSpecifier();
  2244. }
  2245. parseExportDefaultExpression() {
  2246. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2247. const node = this.startNode();
  2248. this.next();
  2249. return this.flowParseEnumDeclaration(node);
  2250. }
  2251. return super.parseExportDefaultExpression();
  2252. }
  2253. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  2254. if (!this.match(types.question)) return expr;
  2255. if (refNeedsArrowPos) {
  2256. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  2257. if (!result.node) {
  2258. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2259. return expr;
  2260. }
  2261. if (result.error) this.state = result.failState;
  2262. return result.node;
  2263. }
  2264. this.expect(types.question);
  2265. const state = this.state.clone();
  2266. const originalNoArrowAt = this.state.noArrowAt;
  2267. const node = this.startNodeAt(startPos, startLoc);
  2268. let {
  2269. consequent,
  2270. failed
  2271. } = this.tryParseConditionalConsequent();
  2272. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2273. if (failed || invalid.length > 0) {
  2274. const noArrowAt = [...originalNoArrowAt];
  2275. if (invalid.length > 0) {
  2276. this.state = state;
  2277. this.state.noArrowAt = noArrowAt;
  2278. for (let i = 0; i < invalid.length; i++) {
  2279. noArrowAt.push(invalid[i].start);
  2280. }
  2281. ({
  2282. consequent,
  2283. failed
  2284. } = this.tryParseConditionalConsequent());
  2285. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2286. }
  2287. if (failed && valid.length > 1) {
  2288. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2289. }
  2290. if (failed && valid.length === 1) {
  2291. this.state = state;
  2292. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2293. ({
  2294. consequent,
  2295. failed
  2296. } = this.tryParseConditionalConsequent());
  2297. }
  2298. }
  2299. this.getArrowLikeExpressions(consequent, true);
  2300. this.state.noArrowAt = originalNoArrowAt;
  2301. this.expect(types.colon);
  2302. node.test = expr;
  2303. node.consequent = consequent;
  2304. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  2305. return this.finishNode(node, "ConditionalExpression");
  2306. }
  2307. tryParseConditionalConsequent() {
  2308. this.state.noArrowParamsConversionAt.push(this.state.start);
  2309. const consequent = this.parseMaybeAssignAllowIn();
  2310. const failed = !this.match(types.colon);
  2311. this.state.noArrowParamsConversionAt.pop();
  2312. return {
  2313. consequent,
  2314. failed
  2315. };
  2316. }
  2317. getArrowLikeExpressions(node, disallowInvalid) {
  2318. const stack = [node];
  2319. const arrows = [];
  2320. while (stack.length !== 0) {
  2321. const node = stack.pop();
  2322. if (node.type === "ArrowFunctionExpression") {
  2323. if (node.typeParameters || !node.returnType) {
  2324. this.finishArrowValidation(node);
  2325. } else {
  2326. arrows.push(node);
  2327. }
  2328. stack.push(node.body);
  2329. } else if (node.type === "ConditionalExpression") {
  2330. stack.push(node.consequent);
  2331. stack.push(node.alternate);
  2332. }
  2333. }
  2334. if (disallowInvalid) {
  2335. arrows.forEach(node => this.finishArrowValidation(node));
  2336. return [arrows, []];
  2337. }
  2338. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2339. }
  2340. finishArrowValidation(node) {
  2341. var _node$extra;
  2342. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma);
  2343. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2344. super.checkParams(node, false, true);
  2345. this.scope.exit();
  2346. }
  2347. forwardNoArrowParamsConversionAt(node, parse) {
  2348. let result;
  2349. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2350. this.state.noArrowParamsConversionAt.push(this.state.start);
  2351. result = parse();
  2352. this.state.noArrowParamsConversionAt.pop();
  2353. } else {
  2354. result = parse();
  2355. }
  2356. return result;
  2357. }
  2358. parseParenItem(node, startPos, startLoc) {
  2359. node = super.parseParenItem(node, startPos, startLoc);
  2360. if (this.eat(types.question)) {
  2361. node.optional = true;
  2362. this.resetEndLocation(node);
  2363. }
  2364. if (this.match(types.colon)) {
  2365. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2366. typeCastNode.expression = node;
  2367. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2368. return this.finishNode(typeCastNode, "TypeCastExpression");
  2369. }
  2370. return node;
  2371. }
  2372. assertModuleNodeAllowed(node) {
  2373. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2374. return;
  2375. }
  2376. super.assertModuleNodeAllowed(node);
  2377. }
  2378. parseExport(node) {
  2379. const decl = super.parseExport(node);
  2380. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2381. decl.exportKind = decl.exportKind || "value";
  2382. }
  2383. return decl;
  2384. }
  2385. parseExportDeclaration(node) {
  2386. if (this.isContextual("type")) {
  2387. node.exportKind = "type";
  2388. const declarationNode = this.startNode();
  2389. this.next();
  2390. if (this.match(types.braceL)) {
  2391. node.specifiers = this.parseExportSpecifiers();
  2392. this.parseExportFrom(node);
  2393. return null;
  2394. } else {
  2395. return this.flowParseTypeAlias(declarationNode);
  2396. }
  2397. } else if (this.isContextual("opaque")) {
  2398. node.exportKind = "type";
  2399. const declarationNode = this.startNode();
  2400. this.next();
  2401. return this.flowParseOpaqueType(declarationNode, false);
  2402. } else if (this.isContextual("interface")) {
  2403. node.exportKind = "type";
  2404. const declarationNode = this.startNode();
  2405. this.next();
  2406. return this.flowParseInterface(declarationNode);
  2407. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2408. node.exportKind = "value";
  2409. const declarationNode = this.startNode();
  2410. this.next();
  2411. return this.flowParseEnumDeclaration(declarationNode);
  2412. } else {
  2413. return super.parseExportDeclaration(node);
  2414. }
  2415. }
  2416. eatExportStar(node) {
  2417. if (super.eatExportStar(...arguments)) return true;
  2418. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2419. node.exportKind = "type";
  2420. this.next();
  2421. this.next();
  2422. return true;
  2423. }
  2424. return false;
  2425. }
  2426. maybeParseExportNamespaceSpecifier(node) {
  2427. const pos = this.state.start;
  2428. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2429. if (hasNamespace && node.exportKind === "type") {
  2430. this.unexpected(pos);
  2431. }
  2432. return hasNamespace;
  2433. }
  2434. parseClassId(node, isStatement, optionalId) {
  2435. super.parseClassId(node, isStatement, optionalId);
  2436. if (this.isRelational("<")) {
  2437. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2438. }
  2439. }
  2440. parseClassMember(classBody, member, state) {
  2441. const pos = this.state.start;
  2442. if (this.isContextual("declare")) {
  2443. if (this.parseClassMemberFromModifier(classBody, member)) {
  2444. return;
  2445. }
  2446. member.declare = true;
  2447. }
  2448. super.parseClassMember(classBody, member, state);
  2449. if (member.declare) {
  2450. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  2451. this.raise(pos, FlowErrors.DeclareClassElement);
  2452. } else if (member.value) {
  2453. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2454. }
  2455. }
  2456. }
  2457. getTokenFromCode(code) {
  2458. const next = this.input.charCodeAt(this.state.pos + 1);
  2459. if (code === 123 && next === 124) {
  2460. return this.finishOp(types.braceBarL, 2);
  2461. } else if (this.state.inType && (code === 62 || code === 60)) {
  2462. return this.finishOp(types.relational, 1);
  2463. } else if (this.state.inType && code === 63) {
  2464. return this.finishOp(types.question, 1);
  2465. } else if (isIteratorStart(code, next)) {
  2466. this.state.isIterator = true;
  2467. return super.readWord();
  2468. } else {
  2469. return super.getTokenFromCode(code);
  2470. }
  2471. }
  2472. isAssignable(node, isBinding) {
  2473. switch (node.type) {
  2474. case "Identifier":
  2475. case "ObjectPattern":
  2476. case "ArrayPattern":
  2477. case "AssignmentPattern":
  2478. return true;
  2479. case "ObjectExpression":
  2480. {
  2481. const last = node.properties.length - 1;
  2482. return node.properties.every((prop, i) => {
  2483. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2484. });
  2485. }
  2486. case "ObjectProperty":
  2487. return this.isAssignable(node.value);
  2488. case "SpreadElement":
  2489. return this.isAssignable(node.argument);
  2490. case "ArrayExpression":
  2491. return node.elements.every(element => this.isAssignable(element));
  2492. case "AssignmentExpression":
  2493. return node.operator === "=";
  2494. case "ParenthesizedExpression":
  2495. case "TypeCastExpression":
  2496. return this.isAssignable(node.expression);
  2497. case "MemberExpression":
  2498. case "OptionalMemberExpression":
  2499. return !isBinding;
  2500. default:
  2501. return false;
  2502. }
  2503. }
  2504. toAssignable(node) {
  2505. if (node.type === "TypeCastExpression") {
  2506. return super.toAssignable(this.typeCastToParameter(node));
  2507. } else {
  2508. return super.toAssignable(node);
  2509. }
  2510. }
  2511. toAssignableList(exprList, trailingCommaPos) {
  2512. for (let i = 0; i < exprList.length; i++) {
  2513. const expr = exprList[i];
  2514. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  2515. exprList[i] = this.typeCastToParameter(expr);
  2516. }
  2517. }
  2518. return super.toAssignableList(exprList, trailingCommaPos);
  2519. }
  2520. toReferencedList(exprList, isParenthesizedExpr) {
  2521. for (let i = 0; i < exprList.length; i++) {
  2522. var _expr$extra;
  2523. const expr = exprList[i];
  2524. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) == null ? void 0 : _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2525. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2526. }
  2527. }
  2528. return exprList;
  2529. }
  2530. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  2531. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  2532. if (canBePattern && !this.state.maybeInArrowParameters) {
  2533. this.toReferencedList(node.elements);
  2534. }
  2535. return node;
  2536. }
  2537. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  2538. if (expr.type !== "TypeCastExpression") {
  2539. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  2540. }
  2541. }
  2542. parseClassProperty(node) {
  2543. if (this.match(types.colon)) {
  2544. node.typeAnnotation = this.flowParseTypeAnnotation();
  2545. }
  2546. return super.parseClassProperty(node);
  2547. }
  2548. parseClassPrivateProperty(node) {
  2549. if (this.match(types.colon)) {
  2550. node.typeAnnotation = this.flowParseTypeAnnotation();
  2551. }
  2552. return super.parseClassPrivateProperty(node);
  2553. }
  2554. isClassMethod() {
  2555. return this.isRelational("<") || super.isClassMethod();
  2556. }
  2557. isClassProperty() {
  2558. return this.match(types.colon) || super.isClassProperty();
  2559. }
  2560. isNonstaticConstructor(method) {
  2561. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2562. }
  2563. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2564. if (method.variance) {
  2565. this.unexpected(method.variance.start);
  2566. }
  2567. delete method.variance;
  2568. if (this.isRelational("<")) {
  2569. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2570. }
  2571. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2572. }
  2573. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2574. if (method.variance) {
  2575. this.unexpected(method.variance.start);
  2576. }
  2577. delete method.variance;
  2578. if (this.isRelational("<")) {
  2579. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2580. }
  2581. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2582. }
  2583. parseClassSuper(node) {
  2584. super.parseClassSuper(node);
  2585. if (node.superClass && this.isRelational("<")) {
  2586. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2587. }
  2588. if (this.isContextual("implements")) {
  2589. this.next();
  2590. const implemented = node.implements = [];
  2591. do {
  2592. const node = this.startNode();
  2593. node.id = this.flowParseRestrictedIdentifier(true);
  2594. if (this.isRelational("<")) {
  2595. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2596. } else {
  2597. node.typeParameters = null;
  2598. }
  2599. implemented.push(this.finishNode(node, "ClassImplements"));
  2600. } while (this.eat(types.comma));
  2601. }
  2602. }
  2603. parsePropertyName(node, isPrivateNameAllowed) {
  2604. const variance = this.flowParseVariance();
  2605. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2606. node.variance = variance;
  2607. return key;
  2608. }
  2609. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  2610. if (prop.variance) {
  2611. this.unexpected(prop.variance.start);
  2612. }
  2613. delete prop.variance;
  2614. let typeParameters;
  2615. if (this.isRelational("<") && !isAccessor) {
  2616. typeParameters = this.flowParseTypeParameterDeclaration();
  2617. if (!this.match(types.parenL)) this.unexpected();
  2618. }
  2619. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  2620. if (typeParameters) {
  2621. (prop.value || prop).typeParameters = typeParameters;
  2622. }
  2623. }
  2624. parseAssignableListItemTypes(param) {
  2625. if (this.eat(types.question)) {
  2626. if (param.type !== "Identifier") {
  2627. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  2628. }
  2629. param.optional = true;
  2630. }
  2631. if (this.match(types.colon)) {
  2632. param.typeAnnotation = this.flowParseTypeAnnotation();
  2633. }
  2634. this.resetEndLocation(param);
  2635. return param;
  2636. }
  2637. parseMaybeDefault(startPos, startLoc, left) {
  2638. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2639. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2640. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  2641. }
  2642. return node;
  2643. }
  2644. shouldParseDefaultImport(node) {
  2645. if (!hasTypeImportKind(node)) {
  2646. return super.shouldParseDefaultImport(node);
  2647. }
  2648. return isMaybeDefaultImport(this.state);
  2649. }
  2650. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2651. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2652. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  2653. node.specifiers.push(this.finishNode(specifier, type));
  2654. }
  2655. maybeParseDefaultImportSpecifier(node) {
  2656. node.importKind = "value";
  2657. let kind = null;
  2658. if (this.match(types._typeof)) {
  2659. kind = "typeof";
  2660. } else if (this.isContextual("type")) {
  2661. kind = "type";
  2662. }
  2663. if (kind) {
  2664. const lh = this.lookahead();
  2665. if (kind === "type" && lh.type === types.star) {
  2666. this.unexpected(lh.start);
  2667. }
  2668. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2669. this.next();
  2670. node.importKind = kind;
  2671. }
  2672. }
  2673. return super.maybeParseDefaultImportSpecifier(node);
  2674. }
  2675. parseImportSpecifier(node) {
  2676. const specifier = this.startNode();
  2677. const firstIdentLoc = this.state.start;
  2678. const firstIdent = this.parseModuleExportName();
  2679. let specifierTypeKind = null;
  2680. if (firstIdent.type === "Identifier") {
  2681. if (firstIdent.name === "type") {
  2682. specifierTypeKind = "type";
  2683. } else if (firstIdent.name === "typeof") {
  2684. specifierTypeKind = "typeof";
  2685. }
  2686. }
  2687. let isBinding = false;
  2688. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2689. const as_ident = this.parseIdentifier(true);
  2690. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2691. specifier.imported = as_ident;
  2692. specifier.importKind = specifierTypeKind;
  2693. specifier.local = as_ident.__clone();
  2694. } else {
  2695. specifier.imported = firstIdent;
  2696. specifier.importKind = null;
  2697. specifier.local = this.parseIdentifier();
  2698. }
  2699. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2700. specifier.imported = this.parseIdentifier(true);
  2701. specifier.importKind = specifierTypeKind;
  2702. if (this.eatContextual("as")) {
  2703. specifier.local = this.parseIdentifier();
  2704. } else {
  2705. isBinding = true;
  2706. specifier.local = specifier.imported.__clone();
  2707. }
  2708. } else {
  2709. if (firstIdent.type === "StringLiteral") {
  2710. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  2711. }
  2712. isBinding = true;
  2713. specifier.imported = firstIdent;
  2714. specifier.importKind = null;
  2715. specifier.local = specifier.imported.__clone();
  2716. }
  2717. const nodeIsTypeImport = hasTypeImportKind(node);
  2718. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2719. if (nodeIsTypeImport && specifierIsTypeImport) {
  2720. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  2721. }
  2722. if (nodeIsTypeImport || specifierIsTypeImport) {
  2723. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2724. }
  2725. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2726. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2727. }
  2728. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2729. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2730. }
  2731. parseFunctionParams(node, allowModifiers) {
  2732. const kind = node.kind;
  2733. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2734. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2735. }
  2736. super.parseFunctionParams(node, allowModifiers);
  2737. }
  2738. parseVarId(decl, kind) {
  2739. super.parseVarId(decl, kind);
  2740. if (this.match(types.colon)) {
  2741. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2742. this.resetEndLocation(decl.id);
  2743. }
  2744. }
  2745. parseAsyncArrowFromCallExpression(node, call) {
  2746. if (this.match(types.colon)) {
  2747. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2748. this.state.noAnonFunctionType = true;
  2749. node.returnType = this.flowParseTypeAnnotation();
  2750. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2751. }
  2752. return super.parseAsyncArrowFromCallExpression(node, call);
  2753. }
  2754. shouldParseAsyncArrow() {
  2755. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2756. }
  2757. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  2758. var _jsx;
  2759. let state = null;
  2760. let jsx;
  2761. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2762. state = this.state.clone();
  2763. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  2764. if (!jsx.error) return jsx.node;
  2765. const {
  2766. context
  2767. } = this.state;
  2768. if (context[context.length - 1] === types$1.j_oTag) {
  2769. context.length -= 2;
  2770. } else if (context[context.length - 1] === types$1.j_expr) {
  2771. context.length -= 1;
  2772. }
  2773. }
  2774. if (((_jsx = jsx) == null ? void 0 : _jsx.error) || this.isRelational("<")) {
  2775. var _jsx2, _jsx3;
  2776. state = state || this.state.clone();
  2777. let typeParameters;
  2778. const arrow = this.tryParse(abort => {
  2779. var _arrowExpression$extr;
  2780. typeParameters = this.flowParseTypeParameterDeclaration();
  2781. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  2782. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2783. this.resetStartLocationFromNode(result, typeParameters);
  2784. return result;
  2785. });
  2786. if (arrowExpression.type !== "ArrowFunctionExpression" && ((_arrowExpression$extr = arrowExpression.extra) == null ? void 0 : _arrowExpression$extr.parenthesized)) {
  2787. abort();
  2788. }
  2789. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  2790. expr.typeParameters = typeParameters;
  2791. this.resetStartLocationFromNode(expr, typeParameters);
  2792. return arrowExpression;
  2793. }, state);
  2794. let arrowExpression = null;
  2795. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  2796. if (!arrow.error && !arrow.aborted) {
  2797. if (arrow.node.async) {
  2798. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  2799. }
  2800. return arrow.node;
  2801. }
  2802. arrowExpression = arrow.node;
  2803. }
  2804. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  2805. this.state = jsx.failState;
  2806. return jsx.node;
  2807. }
  2808. if (arrowExpression) {
  2809. this.state = arrow.failState;
  2810. return arrowExpression;
  2811. }
  2812. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  2813. if (arrow.thrown) throw arrow.error;
  2814. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  2815. }
  2816. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2817. }
  2818. parseArrow(node) {
  2819. if (this.match(types.colon)) {
  2820. const result = this.tryParse(() => {
  2821. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2822. this.state.noAnonFunctionType = true;
  2823. const typeNode = this.startNode();
  2824. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2825. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2826. if (this.canInsertSemicolon()) this.unexpected();
  2827. if (!this.match(types.arrow)) this.unexpected();
  2828. return typeNode;
  2829. });
  2830. if (result.thrown) return null;
  2831. if (result.error) this.state = result.failState;
  2832. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2833. }
  2834. return super.parseArrow(node);
  2835. }
  2836. shouldParseArrow() {
  2837. return this.match(types.colon) || super.shouldParseArrow();
  2838. }
  2839. setArrowFunctionParameters(node, params) {
  2840. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2841. node.params = params;
  2842. } else {
  2843. super.setArrowFunctionParameters(node, params);
  2844. }
  2845. }
  2846. checkParams(node, allowDuplicates, isArrowFunction) {
  2847. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2848. return;
  2849. }
  2850. return super.checkParams(...arguments);
  2851. }
  2852. parseParenAndDistinguishExpression(canBeArrow) {
  2853. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2854. }
  2855. parseSubscripts(base, startPos, startLoc, noCalls) {
  2856. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2857. this.next();
  2858. const node = this.startNodeAt(startPos, startLoc);
  2859. node.callee = base;
  2860. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2861. base = this.finishNode(node, "CallExpression");
  2862. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2863. const state = this.state.clone();
  2864. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2865. if (!arrow.error && !arrow.aborted) return arrow.node;
  2866. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2867. if (result.node && !result.error) return result.node;
  2868. if (arrow.node) {
  2869. this.state = arrow.failState;
  2870. return arrow.node;
  2871. }
  2872. if (result.node) {
  2873. this.state = result.failState;
  2874. return result.node;
  2875. }
  2876. throw arrow.error || result.error;
  2877. }
  2878. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2879. }
  2880. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2881. if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
  2882. subscriptState.optionalChainMember = true;
  2883. if (noCalls) {
  2884. subscriptState.stop = true;
  2885. return base;
  2886. }
  2887. this.next();
  2888. const node = this.startNodeAt(startPos, startLoc);
  2889. node.callee = base;
  2890. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2891. this.expect(types.parenL);
  2892. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2893. node.optional = true;
  2894. return this.finishCallExpression(node, true);
  2895. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2896. const node = this.startNodeAt(startPos, startLoc);
  2897. node.callee = base;
  2898. const result = this.tryParse(() => {
  2899. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2900. this.expect(types.parenL);
  2901. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2902. if (subscriptState.optionalChainMember) node.optional = false;
  2903. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2904. });
  2905. if (result.node) {
  2906. if (result.error) this.state = result.failState;
  2907. return result.node;
  2908. }
  2909. }
  2910. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2911. }
  2912. parseNewArguments(node) {
  2913. let targs = null;
  2914. if (this.shouldParseTypes() && this.isRelational("<")) {
  2915. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2916. }
  2917. node.typeArguments = targs;
  2918. super.parseNewArguments(node);
  2919. }
  2920. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2921. const node = this.startNodeAt(startPos, startLoc);
  2922. this.parseFunctionParams(node);
  2923. if (!this.parseArrow(node)) return;
  2924. return this.parseArrowExpression(node, undefined, true);
  2925. }
  2926. readToken_mult_modulo(code) {
  2927. const next = this.input.charCodeAt(this.state.pos + 1);
  2928. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2929. this.state.hasFlowComment = false;
  2930. this.state.pos += 2;
  2931. this.nextToken();
  2932. return;
  2933. }
  2934. super.readToken_mult_modulo(code);
  2935. }
  2936. readToken_pipe_amp(code) {
  2937. const next = this.input.charCodeAt(this.state.pos + 1);
  2938. if (code === 124 && next === 125) {
  2939. this.finishOp(types.braceBarR, 2);
  2940. return;
  2941. }
  2942. super.readToken_pipe_amp(code);
  2943. }
  2944. parseTopLevel(file, program) {
  2945. const fileNode = super.parseTopLevel(file, program);
  2946. if (this.state.hasFlowComment) {
  2947. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  2948. }
  2949. return fileNode;
  2950. }
  2951. skipBlockComment() {
  2952. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2953. if (this.state.hasFlowComment) {
  2954. this.unexpected(null, FlowErrors.NestedFlowComment);
  2955. }
  2956. this.hasFlowCommentCompletion();
  2957. this.state.pos += this.skipFlowComment();
  2958. this.state.hasFlowComment = true;
  2959. return;
  2960. }
  2961. if (this.state.hasFlowComment) {
  2962. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2963. if (end === -1) {
  2964. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  2965. }
  2966. this.state.pos = end + 3;
  2967. return;
  2968. }
  2969. super.skipBlockComment();
  2970. }
  2971. skipFlowComment() {
  2972. const {
  2973. pos
  2974. } = this.state;
  2975. let shiftToFirstNonWhiteSpace = 2;
  2976. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2977. shiftToFirstNonWhiteSpace++;
  2978. }
  2979. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2980. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2981. if (ch2 === 58 && ch3 === 58) {
  2982. return shiftToFirstNonWhiteSpace + 2;
  2983. }
  2984. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2985. return shiftToFirstNonWhiteSpace + 12;
  2986. }
  2987. if (ch2 === 58 && ch3 !== 58) {
  2988. return shiftToFirstNonWhiteSpace;
  2989. }
  2990. return false;
  2991. }
  2992. hasFlowCommentCompletion() {
  2993. const end = this.input.indexOf("*/", this.state.pos);
  2994. if (end === -1) {
  2995. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  2996. }
  2997. }
  2998. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2999. enumName,
  3000. memberName
  3001. }) {
  3002. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  3003. }
  3004. flowEnumErrorInvalidMemberName(pos, {
  3005. enumName,
  3006. memberName
  3007. }) {
  3008. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  3009. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  3010. }
  3011. flowEnumErrorDuplicateMemberName(pos, {
  3012. enumName,
  3013. memberName
  3014. }) {
  3015. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  3016. }
  3017. flowEnumErrorInconsistentMemberValues(pos, {
  3018. enumName
  3019. }) {
  3020. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  3021. }
  3022. flowEnumErrorInvalidExplicitType(pos, {
  3023. enumName,
  3024. suppliedType
  3025. }) {
  3026. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  3027. }
  3028. flowEnumErrorInvalidMemberInitializer(pos, {
  3029. enumName,
  3030. explicitType,
  3031. memberName
  3032. }) {
  3033. let message = null;
  3034. switch (explicitType) {
  3035. case "boolean":
  3036. case "number":
  3037. case "string":
  3038. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  3039. break;
  3040. case "symbol":
  3041. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  3042. break;
  3043. default:
  3044. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  3045. }
  3046. return this.raise(pos, message, enumName, memberName, explicitType);
  3047. }
  3048. flowEnumErrorNumberMemberNotInitialized(pos, {
  3049. enumName,
  3050. memberName
  3051. }) {
  3052. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  3053. }
  3054. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  3055. enumName
  3056. }) {
  3057. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  3058. }
  3059. flowEnumMemberInit() {
  3060. const startPos = this.state.start;
  3061. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  3062. switch (this.state.type) {
  3063. case types.num:
  3064. {
  3065. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  3066. if (endOfInit()) {
  3067. return {
  3068. type: "number",
  3069. pos: literal.start,
  3070. value: literal
  3071. };
  3072. }
  3073. return {
  3074. type: "invalid",
  3075. pos: startPos
  3076. };
  3077. }
  3078. case types.string:
  3079. {
  3080. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  3081. if (endOfInit()) {
  3082. return {
  3083. type: "string",
  3084. pos: literal.start,
  3085. value: literal
  3086. };
  3087. }
  3088. return {
  3089. type: "invalid",
  3090. pos: startPos
  3091. };
  3092. }
  3093. case types._true:
  3094. case types._false:
  3095. {
  3096. const literal = this.parseBooleanLiteral();
  3097. if (endOfInit()) {
  3098. return {
  3099. type: "boolean",
  3100. pos: literal.start,
  3101. value: literal
  3102. };
  3103. }
  3104. return {
  3105. type: "invalid",
  3106. pos: startPos
  3107. };
  3108. }
  3109. default:
  3110. return {
  3111. type: "invalid",
  3112. pos: startPos
  3113. };
  3114. }
  3115. }
  3116. flowEnumMemberRaw() {
  3117. const pos = this.state.start;
  3118. const id = this.parseIdentifier(true);
  3119. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3120. type: "none",
  3121. pos
  3122. };
  3123. return {
  3124. id,
  3125. init
  3126. };
  3127. }
  3128. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3129. const {
  3130. explicitType
  3131. } = context;
  3132. if (explicitType === null) {
  3133. return;
  3134. }
  3135. if (explicitType !== expectedType) {
  3136. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3137. }
  3138. }
  3139. flowEnumMembers({
  3140. enumName,
  3141. explicitType
  3142. }) {
  3143. const seenNames = new Set();
  3144. const members = {
  3145. booleanMembers: [],
  3146. numberMembers: [],
  3147. stringMembers: [],
  3148. defaultedMembers: []
  3149. };
  3150. while (!this.match(types.braceR)) {
  3151. const memberNode = this.startNode();
  3152. const {
  3153. id,
  3154. init
  3155. } = this.flowEnumMemberRaw();
  3156. const memberName = id.name;
  3157. if (memberName === "") {
  3158. continue;
  3159. }
  3160. if (/^[a-z]/.test(memberName)) {
  3161. this.flowEnumErrorInvalidMemberName(id.start, {
  3162. enumName,
  3163. memberName
  3164. });
  3165. }
  3166. if (seenNames.has(memberName)) {
  3167. this.flowEnumErrorDuplicateMemberName(id.start, {
  3168. enumName,
  3169. memberName
  3170. });
  3171. }
  3172. seenNames.add(memberName);
  3173. const context = {
  3174. enumName,
  3175. explicitType,
  3176. memberName
  3177. };
  3178. memberNode.id = id;
  3179. switch (init.type) {
  3180. case "boolean":
  3181. {
  3182. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3183. memberNode.init = init.value;
  3184. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3185. break;
  3186. }
  3187. case "number":
  3188. {
  3189. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3190. memberNode.init = init.value;
  3191. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3192. break;
  3193. }
  3194. case "string":
  3195. {
  3196. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3197. memberNode.init = init.value;
  3198. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3199. break;
  3200. }
  3201. case "invalid":
  3202. {
  3203. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3204. }
  3205. case "none":
  3206. {
  3207. switch (explicitType) {
  3208. case "boolean":
  3209. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3210. break;
  3211. case "number":
  3212. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3213. break;
  3214. default:
  3215. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3216. }
  3217. }
  3218. }
  3219. if (!this.match(types.braceR)) {
  3220. this.expect(types.comma);
  3221. }
  3222. }
  3223. return members;
  3224. }
  3225. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3226. enumName
  3227. }) {
  3228. if (initializedMembers.length === 0) {
  3229. return defaultedMembers;
  3230. } else if (defaultedMembers.length === 0) {
  3231. return initializedMembers;
  3232. } else if (defaultedMembers.length > initializedMembers.length) {
  3233. for (let _i = 0; _i < initializedMembers.length; _i++) {
  3234. const member = initializedMembers[_i];
  3235. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3236. enumName
  3237. });
  3238. }
  3239. return defaultedMembers;
  3240. } else {
  3241. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  3242. const member = defaultedMembers[_i2];
  3243. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3244. enumName
  3245. });
  3246. }
  3247. return initializedMembers;
  3248. }
  3249. }
  3250. flowEnumParseExplicitType({
  3251. enumName
  3252. }) {
  3253. if (this.eatContextual("of")) {
  3254. if (!this.match(types.name)) {
  3255. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3256. enumName,
  3257. suppliedType: null
  3258. });
  3259. }
  3260. const {
  3261. value
  3262. } = this.state;
  3263. this.next();
  3264. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3265. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3266. enumName,
  3267. suppliedType: value
  3268. });
  3269. }
  3270. return value;
  3271. }
  3272. return null;
  3273. }
  3274. flowEnumBody(node, {
  3275. enumName,
  3276. nameLoc
  3277. }) {
  3278. const explicitType = this.flowEnumParseExplicitType({
  3279. enumName
  3280. });
  3281. this.expect(types.braceL);
  3282. const members = this.flowEnumMembers({
  3283. enumName,
  3284. explicitType
  3285. });
  3286. switch (explicitType) {
  3287. case "boolean":
  3288. node.explicitType = true;
  3289. node.members = members.booleanMembers;
  3290. this.expect(types.braceR);
  3291. return this.finishNode(node, "EnumBooleanBody");
  3292. case "number":
  3293. node.explicitType = true;
  3294. node.members = members.numberMembers;
  3295. this.expect(types.braceR);
  3296. return this.finishNode(node, "EnumNumberBody");
  3297. case "string":
  3298. node.explicitType = true;
  3299. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3300. enumName
  3301. });
  3302. this.expect(types.braceR);
  3303. return this.finishNode(node, "EnumStringBody");
  3304. case "symbol":
  3305. node.members = members.defaultedMembers;
  3306. this.expect(types.braceR);
  3307. return this.finishNode(node, "EnumSymbolBody");
  3308. default:
  3309. {
  3310. const empty = () => {
  3311. node.members = [];
  3312. this.expect(types.braceR);
  3313. return this.finishNode(node, "EnumStringBody");
  3314. };
  3315. node.explicitType = false;
  3316. const boolsLen = members.booleanMembers.length;
  3317. const numsLen = members.numberMembers.length;
  3318. const strsLen = members.stringMembers.length;
  3319. const defaultedLen = members.defaultedMembers.length;
  3320. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3321. return empty();
  3322. } else if (!boolsLen && !numsLen) {
  3323. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3324. enumName
  3325. });
  3326. this.expect(types.braceR);
  3327. return this.finishNode(node, "EnumStringBody");
  3328. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3329. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  3330. const member = _members$defaultedMem[_i3];
  3331. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3332. enumName,
  3333. memberName: member.id.name
  3334. });
  3335. }
  3336. node.members = members.booleanMembers;
  3337. this.expect(types.braceR);
  3338. return this.finishNode(node, "EnumBooleanBody");
  3339. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3340. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  3341. const member = _members$defaultedMem2[_i4];
  3342. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3343. enumName,
  3344. memberName: member.id.name
  3345. });
  3346. }
  3347. node.members = members.numberMembers;
  3348. this.expect(types.braceR);
  3349. return this.finishNode(node, "EnumNumberBody");
  3350. } else {
  3351. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3352. enumName
  3353. });
  3354. return empty();
  3355. }
  3356. }
  3357. }
  3358. }
  3359. flowParseEnumDeclaration(node) {
  3360. const id = this.parseIdentifier();
  3361. node.id = id;
  3362. node.body = this.flowEnumBody(this.startNode(), {
  3363. enumName: id.name,
  3364. nameLoc: id.start
  3365. });
  3366. return this.finishNode(node, "EnumDeclaration");
  3367. }
  3368. updateContext(prevType) {
  3369. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  3370. this.state.exprAllowed = false;
  3371. } else {
  3372. super.updateContext(prevType);
  3373. }
  3374. }
  3375. isLookaheadToken_lt() {
  3376. const next = this.nextTokenStart();
  3377. if (this.input.charCodeAt(next) === 60) {
  3378. const afterNext = this.input.charCodeAt(next + 1);
  3379. return afterNext !== 60 && afterNext !== 61;
  3380. }
  3381. return false;
  3382. }
  3383. maybeUnwrapTypeCastExpression(node) {
  3384. return node.type === "TypeCastExpression" ? node.expression : node;
  3385. }
  3386. }, _temp;
  3387. });
  3388. const entities = {
  3389. quot: "\u0022",
  3390. amp: "&",
  3391. apos: "\u0027",
  3392. lt: "<",
  3393. gt: ">",
  3394. nbsp: "\u00A0",
  3395. iexcl: "\u00A1",
  3396. cent: "\u00A2",
  3397. pound: "\u00A3",
  3398. curren: "\u00A4",
  3399. yen: "\u00A5",
  3400. brvbar: "\u00A6",
  3401. sect: "\u00A7",
  3402. uml: "\u00A8",
  3403. copy: "\u00A9",
  3404. ordf: "\u00AA",
  3405. laquo: "\u00AB",
  3406. not: "\u00AC",
  3407. shy: "\u00AD",
  3408. reg: "\u00AE",
  3409. macr: "\u00AF",
  3410. deg: "\u00B0",
  3411. plusmn: "\u00B1",
  3412. sup2: "\u00B2",
  3413. sup3: "\u00B3",
  3414. acute: "\u00B4",
  3415. micro: "\u00B5",
  3416. para: "\u00B6",
  3417. middot: "\u00B7",
  3418. cedil: "\u00B8",
  3419. sup1: "\u00B9",
  3420. ordm: "\u00BA",
  3421. raquo: "\u00BB",
  3422. frac14: "\u00BC",
  3423. frac12: "\u00BD",
  3424. frac34: "\u00BE",
  3425. iquest: "\u00BF",
  3426. Agrave: "\u00C0",
  3427. Aacute: "\u00C1",
  3428. Acirc: "\u00C2",
  3429. Atilde: "\u00C3",
  3430. Auml: "\u00C4",
  3431. Aring: "\u00C5",
  3432. AElig: "\u00C6",
  3433. Ccedil: "\u00C7",
  3434. Egrave: "\u00C8",
  3435. Eacute: "\u00C9",
  3436. Ecirc: "\u00CA",
  3437. Euml: "\u00CB",
  3438. Igrave: "\u00CC",
  3439. Iacute: "\u00CD",
  3440. Icirc: "\u00CE",
  3441. Iuml: "\u00CF",
  3442. ETH: "\u00D0",
  3443. Ntilde: "\u00D1",
  3444. Ograve: "\u00D2",
  3445. Oacute: "\u00D3",
  3446. Ocirc: "\u00D4",
  3447. Otilde: "\u00D5",
  3448. Ouml: "\u00D6",
  3449. times: "\u00D7",
  3450. Oslash: "\u00D8",
  3451. Ugrave: "\u00D9",
  3452. Uacute: "\u00DA",
  3453. Ucirc: "\u00DB",
  3454. Uuml: "\u00DC",
  3455. Yacute: "\u00DD",
  3456. THORN: "\u00DE",
  3457. szlig: "\u00DF",
  3458. agrave: "\u00E0",
  3459. aacute: "\u00E1",
  3460. acirc: "\u00E2",
  3461. atilde: "\u00E3",
  3462. auml: "\u00E4",
  3463. aring: "\u00E5",
  3464. aelig: "\u00E6",
  3465. ccedil: "\u00E7",
  3466. egrave: "\u00E8",
  3467. eacute: "\u00E9",
  3468. ecirc: "\u00EA",
  3469. euml: "\u00EB",
  3470. igrave: "\u00EC",
  3471. iacute: "\u00ED",
  3472. icirc: "\u00EE",
  3473. iuml: "\u00EF",
  3474. eth: "\u00F0",
  3475. ntilde: "\u00F1",
  3476. ograve: "\u00F2",
  3477. oacute: "\u00F3",
  3478. ocirc: "\u00F4",
  3479. otilde: "\u00F5",
  3480. ouml: "\u00F6",
  3481. divide: "\u00F7",
  3482. oslash: "\u00F8",
  3483. ugrave: "\u00F9",
  3484. uacute: "\u00FA",
  3485. ucirc: "\u00FB",
  3486. uuml: "\u00FC",
  3487. yacute: "\u00FD",
  3488. thorn: "\u00FE",
  3489. yuml: "\u00FF",
  3490. OElig: "\u0152",
  3491. oelig: "\u0153",
  3492. Scaron: "\u0160",
  3493. scaron: "\u0161",
  3494. Yuml: "\u0178",
  3495. fnof: "\u0192",
  3496. circ: "\u02C6",
  3497. tilde: "\u02DC",
  3498. Alpha: "\u0391",
  3499. Beta: "\u0392",
  3500. Gamma: "\u0393",
  3501. Delta: "\u0394",
  3502. Epsilon: "\u0395",
  3503. Zeta: "\u0396",
  3504. Eta: "\u0397",
  3505. Theta: "\u0398",
  3506. Iota: "\u0399",
  3507. Kappa: "\u039A",
  3508. Lambda: "\u039B",
  3509. Mu: "\u039C",
  3510. Nu: "\u039D",
  3511. Xi: "\u039E",
  3512. Omicron: "\u039F",
  3513. Pi: "\u03A0",
  3514. Rho: "\u03A1",
  3515. Sigma: "\u03A3",
  3516. Tau: "\u03A4",
  3517. Upsilon: "\u03A5",
  3518. Phi: "\u03A6",
  3519. Chi: "\u03A7",
  3520. Psi: "\u03A8",
  3521. Omega: "\u03A9",
  3522. alpha: "\u03B1",
  3523. beta: "\u03B2",
  3524. gamma: "\u03B3",
  3525. delta: "\u03B4",
  3526. epsilon: "\u03B5",
  3527. zeta: "\u03B6",
  3528. eta: "\u03B7",
  3529. theta: "\u03B8",
  3530. iota: "\u03B9",
  3531. kappa: "\u03BA",
  3532. lambda: "\u03BB",
  3533. mu: "\u03BC",
  3534. nu: "\u03BD",
  3535. xi: "\u03BE",
  3536. omicron: "\u03BF",
  3537. pi: "\u03C0",
  3538. rho: "\u03C1",
  3539. sigmaf: "\u03C2",
  3540. sigma: "\u03C3",
  3541. tau: "\u03C4",
  3542. upsilon: "\u03C5",
  3543. phi: "\u03C6",
  3544. chi: "\u03C7",
  3545. psi: "\u03C8",
  3546. omega: "\u03C9",
  3547. thetasym: "\u03D1",
  3548. upsih: "\u03D2",
  3549. piv: "\u03D6",
  3550. ensp: "\u2002",
  3551. emsp: "\u2003",
  3552. thinsp: "\u2009",
  3553. zwnj: "\u200C",
  3554. zwj: "\u200D",
  3555. lrm: "\u200E",
  3556. rlm: "\u200F",
  3557. ndash: "\u2013",
  3558. mdash: "\u2014",
  3559. lsquo: "\u2018",
  3560. rsquo: "\u2019",
  3561. sbquo: "\u201A",
  3562. ldquo: "\u201C",
  3563. rdquo: "\u201D",
  3564. bdquo: "\u201E",
  3565. dagger: "\u2020",
  3566. Dagger: "\u2021",
  3567. bull: "\u2022",
  3568. hellip: "\u2026",
  3569. permil: "\u2030",
  3570. prime: "\u2032",
  3571. Prime: "\u2033",
  3572. lsaquo: "\u2039",
  3573. rsaquo: "\u203A",
  3574. oline: "\u203E",
  3575. frasl: "\u2044",
  3576. euro: "\u20AC",
  3577. image: "\u2111",
  3578. weierp: "\u2118",
  3579. real: "\u211C",
  3580. trade: "\u2122",
  3581. alefsym: "\u2135",
  3582. larr: "\u2190",
  3583. uarr: "\u2191",
  3584. rarr: "\u2192",
  3585. darr: "\u2193",
  3586. harr: "\u2194",
  3587. crarr: "\u21B5",
  3588. lArr: "\u21D0",
  3589. uArr: "\u21D1",
  3590. rArr: "\u21D2",
  3591. dArr: "\u21D3",
  3592. hArr: "\u21D4",
  3593. forall: "\u2200",
  3594. part: "\u2202",
  3595. exist: "\u2203",
  3596. empty: "\u2205",
  3597. nabla: "\u2207",
  3598. isin: "\u2208",
  3599. notin: "\u2209",
  3600. ni: "\u220B",
  3601. prod: "\u220F",
  3602. sum: "\u2211",
  3603. minus: "\u2212",
  3604. lowast: "\u2217",
  3605. radic: "\u221A",
  3606. prop: "\u221D",
  3607. infin: "\u221E",
  3608. ang: "\u2220",
  3609. and: "\u2227",
  3610. or: "\u2228",
  3611. cap: "\u2229",
  3612. cup: "\u222A",
  3613. int: "\u222B",
  3614. there4: "\u2234",
  3615. sim: "\u223C",
  3616. cong: "\u2245",
  3617. asymp: "\u2248",
  3618. ne: "\u2260",
  3619. equiv: "\u2261",
  3620. le: "\u2264",
  3621. ge: "\u2265",
  3622. sub: "\u2282",
  3623. sup: "\u2283",
  3624. nsub: "\u2284",
  3625. sube: "\u2286",
  3626. supe: "\u2287",
  3627. oplus: "\u2295",
  3628. otimes: "\u2297",
  3629. perp: "\u22A5",
  3630. sdot: "\u22C5",
  3631. lceil: "\u2308",
  3632. rceil: "\u2309",
  3633. lfloor: "\u230A",
  3634. rfloor: "\u230B",
  3635. lang: "\u2329",
  3636. rang: "\u232A",
  3637. loz: "\u25CA",
  3638. spades: "\u2660",
  3639. clubs: "\u2663",
  3640. hearts: "\u2665",
  3641. diams: "\u2666"
  3642. };
  3643. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3644. const DECIMAL_NUMBER = /^\d+$/;
  3645. const JsxErrors = Object.freeze({
  3646. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3647. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3648. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3649. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3650. UnterminatedJsxContent: "Unterminated JSX contents",
  3651. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3652. });
  3653. types$1.j_oTag = new TokContext("<tag", false);
  3654. types$1.j_cTag = new TokContext("</tag", false);
  3655. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3656. types.jsxName = new TokenType("jsxName");
  3657. types.jsxText = new TokenType("jsxText", {
  3658. beforeExpr: true
  3659. });
  3660. types.jsxTagStart = new TokenType("jsxTagStart", {
  3661. startsExpr: true
  3662. });
  3663. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3664. types.jsxTagStart.updateContext = function () {
  3665. this.state.context.push(types$1.j_expr);
  3666. this.state.context.push(types$1.j_oTag);
  3667. this.state.exprAllowed = false;
  3668. };
  3669. types.jsxTagEnd.updateContext = function (prevType) {
  3670. const out = this.state.context.pop();
  3671. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3672. this.state.context.pop();
  3673. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3674. } else {
  3675. this.state.exprAllowed = true;
  3676. }
  3677. };
  3678. function isFragment(object) {
  3679. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3680. }
  3681. function getQualifiedJSXName(object) {
  3682. if (object.type === "JSXIdentifier") {
  3683. return object.name;
  3684. }
  3685. if (object.type === "JSXNamespacedName") {
  3686. return object.namespace.name + ":" + object.name.name;
  3687. }
  3688. if (object.type === "JSXMemberExpression") {
  3689. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3690. }
  3691. throw new Error("Node had unexpected type: " + object.type);
  3692. }
  3693. var jsx = (superClass => class extends superClass {
  3694. jsxReadToken() {
  3695. let out = "";
  3696. let chunkStart = this.state.pos;
  3697. for (;;) {
  3698. if (this.state.pos >= this.length) {
  3699. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  3700. }
  3701. const ch = this.input.charCodeAt(this.state.pos);
  3702. switch (ch) {
  3703. case 60:
  3704. case 123:
  3705. if (this.state.pos === this.state.start) {
  3706. if (ch === 60 && this.state.exprAllowed) {
  3707. ++this.state.pos;
  3708. return this.finishToken(types.jsxTagStart);
  3709. }
  3710. return super.getTokenFromCode(ch);
  3711. }
  3712. out += this.input.slice(chunkStart, this.state.pos);
  3713. return this.finishToken(types.jsxText, out);
  3714. case 38:
  3715. out += this.input.slice(chunkStart, this.state.pos);
  3716. out += this.jsxReadEntity();
  3717. chunkStart = this.state.pos;
  3718. break;
  3719. default:
  3720. if (isNewLine(ch)) {
  3721. out += this.input.slice(chunkStart, this.state.pos);
  3722. out += this.jsxReadNewLine(true);
  3723. chunkStart = this.state.pos;
  3724. } else {
  3725. ++this.state.pos;
  3726. }
  3727. }
  3728. }
  3729. }
  3730. jsxReadNewLine(normalizeCRLF) {
  3731. const ch = this.input.charCodeAt(this.state.pos);
  3732. let out;
  3733. ++this.state.pos;
  3734. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3735. ++this.state.pos;
  3736. out = normalizeCRLF ? "\n" : "\r\n";
  3737. } else {
  3738. out = String.fromCharCode(ch);
  3739. }
  3740. ++this.state.curLine;
  3741. this.state.lineStart = this.state.pos;
  3742. return out;
  3743. }
  3744. jsxReadString(quote) {
  3745. let out = "";
  3746. let chunkStart = ++this.state.pos;
  3747. for (;;) {
  3748. if (this.state.pos >= this.length) {
  3749. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3750. }
  3751. const ch = this.input.charCodeAt(this.state.pos);
  3752. if (ch === quote) break;
  3753. if (ch === 38) {
  3754. out += this.input.slice(chunkStart, this.state.pos);
  3755. out += this.jsxReadEntity();
  3756. chunkStart = this.state.pos;
  3757. } else if (isNewLine(ch)) {
  3758. out += this.input.slice(chunkStart, this.state.pos);
  3759. out += this.jsxReadNewLine(false);
  3760. chunkStart = this.state.pos;
  3761. } else {
  3762. ++this.state.pos;
  3763. }
  3764. }
  3765. out += this.input.slice(chunkStart, this.state.pos++);
  3766. return this.finishToken(types.string, out);
  3767. }
  3768. jsxReadEntity() {
  3769. let str = "";
  3770. let count = 0;
  3771. let entity;
  3772. let ch = this.input[this.state.pos];
  3773. const startPos = ++this.state.pos;
  3774. while (this.state.pos < this.length && count++ < 10) {
  3775. ch = this.input[this.state.pos++];
  3776. if (ch === ";") {
  3777. if (str[0] === "#") {
  3778. if (str[1] === "x") {
  3779. str = str.substr(2);
  3780. if (HEX_NUMBER.test(str)) {
  3781. entity = String.fromCodePoint(parseInt(str, 16));
  3782. }
  3783. } else {
  3784. str = str.substr(1);
  3785. if (DECIMAL_NUMBER.test(str)) {
  3786. entity = String.fromCodePoint(parseInt(str, 10));
  3787. }
  3788. }
  3789. } else {
  3790. entity = entities[str];
  3791. }
  3792. break;
  3793. }
  3794. str += ch;
  3795. }
  3796. if (!entity) {
  3797. this.state.pos = startPos;
  3798. return "&";
  3799. }
  3800. return entity;
  3801. }
  3802. jsxReadWord() {
  3803. let ch;
  3804. const start = this.state.pos;
  3805. do {
  3806. ch = this.input.charCodeAt(++this.state.pos);
  3807. } while (isIdentifierChar(ch) || ch === 45);
  3808. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3809. }
  3810. jsxParseIdentifier() {
  3811. const node = this.startNode();
  3812. if (this.match(types.jsxName)) {
  3813. node.name = this.state.value;
  3814. } else if (this.state.type.keyword) {
  3815. node.name = this.state.type.keyword;
  3816. } else {
  3817. this.unexpected();
  3818. }
  3819. this.next();
  3820. return this.finishNode(node, "JSXIdentifier");
  3821. }
  3822. jsxParseNamespacedName() {
  3823. const startPos = this.state.start;
  3824. const startLoc = this.state.startLoc;
  3825. const name = this.jsxParseIdentifier();
  3826. if (!this.eat(types.colon)) return name;
  3827. const node = this.startNodeAt(startPos, startLoc);
  3828. node.namespace = name;
  3829. node.name = this.jsxParseIdentifier();
  3830. return this.finishNode(node, "JSXNamespacedName");
  3831. }
  3832. jsxParseElementName() {
  3833. const startPos = this.state.start;
  3834. const startLoc = this.state.startLoc;
  3835. let node = this.jsxParseNamespacedName();
  3836. if (node.type === "JSXNamespacedName") {
  3837. return node;
  3838. }
  3839. while (this.eat(types.dot)) {
  3840. const newNode = this.startNodeAt(startPos, startLoc);
  3841. newNode.object = node;
  3842. newNode.property = this.jsxParseIdentifier();
  3843. node = this.finishNode(newNode, "JSXMemberExpression");
  3844. }
  3845. return node;
  3846. }
  3847. jsxParseAttributeValue() {
  3848. let node;
  3849. switch (this.state.type) {
  3850. case types.braceL:
  3851. node = this.startNode();
  3852. this.next();
  3853. node = this.jsxParseExpressionContainer(node);
  3854. if (node.expression.type === "JSXEmptyExpression") {
  3855. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  3856. }
  3857. return node;
  3858. case types.jsxTagStart:
  3859. case types.string:
  3860. return this.parseExprAtom();
  3861. default:
  3862. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  3863. }
  3864. }
  3865. jsxParseEmptyExpression() {
  3866. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3867. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3868. }
  3869. jsxParseSpreadChild(node) {
  3870. this.next();
  3871. node.expression = this.parseExpression();
  3872. this.expect(types.braceR);
  3873. return this.finishNode(node, "JSXSpreadChild");
  3874. }
  3875. jsxParseExpressionContainer(node) {
  3876. if (this.match(types.braceR)) {
  3877. node.expression = this.jsxParseEmptyExpression();
  3878. } else {
  3879. node.expression = this.parseExpression();
  3880. }
  3881. this.expect(types.braceR);
  3882. return this.finishNode(node, "JSXExpressionContainer");
  3883. }
  3884. jsxParseAttribute() {
  3885. const node = this.startNode();
  3886. if (this.eat(types.braceL)) {
  3887. this.expect(types.ellipsis);
  3888. node.argument = this.parseMaybeAssignAllowIn();
  3889. this.expect(types.braceR);
  3890. return this.finishNode(node, "JSXSpreadAttribute");
  3891. }
  3892. node.name = this.jsxParseNamespacedName();
  3893. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3894. return this.finishNode(node, "JSXAttribute");
  3895. }
  3896. jsxParseOpeningElementAt(startPos, startLoc) {
  3897. const node = this.startNodeAt(startPos, startLoc);
  3898. if (this.match(types.jsxTagEnd)) {
  3899. this.expect(types.jsxTagEnd);
  3900. return this.finishNode(node, "JSXOpeningFragment");
  3901. }
  3902. node.name = this.jsxParseElementName();
  3903. return this.jsxParseOpeningElementAfterName(node);
  3904. }
  3905. jsxParseOpeningElementAfterName(node) {
  3906. const attributes = [];
  3907. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3908. attributes.push(this.jsxParseAttribute());
  3909. }
  3910. node.attributes = attributes;
  3911. node.selfClosing = this.eat(types.slash);
  3912. this.expect(types.jsxTagEnd);
  3913. return this.finishNode(node, "JSXOpeningElement");
  3914. }
  3915. jsxParseClosingElementAt(startPos, startLoc) {
  3916. const node = this.startNodeAt(startPos, startLoc);
  3917. if (this.match(types.jsxTagEnd)) {
  3918. this.expect(types.jsxTagEnd);
  3919. return this.finishNode(node, "JSXClosingFragment");
  3920. }
  3921. node.name = this.jsxParseElementName();
  3922. this.expect(types.jsxTagEnd);
  3923. return this.finishNode(node, "JSXClosingElement");
  3924. }
  3925. jsxParseElementAt(startPos, startLoc) {
  3926. const node = this.startNodeAt(startPos, startLoc);
  3927. const children = [];
  3928. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3929. let closingElement = null;
  3930. if (!openingElement.selfClosing) {
  3931. contents: for (;;) {
  3932. switch (this.state.type) {
  3933. case types.jsxTagStart:
  3934. startPos = this.state.start;
  3935. startLoc = this.state.startLoc;
  3936. this.next();
  3937. if (this.eat(types.slash)) {
  3938. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3939. break contents;
  3940. }
  3941. children.push(this.jsxParseElementAt(startPos, startLoc));
  3942. break;
  3943. case types.jsxText:
  3944. children.push(this.parseExprAtom());
  3945. break;
  3946. case types.braceL:
  3947. {
  3948. const node = this.startNode();
  3949. this.next();
  3950. if (this.match(types.ellipsis)) {
  3951. children.push(this.jsxParseSpreadChild(node));
  3952. } else {
  3953. children.push(this.jsxParseExpressionContainer(node));
  3954. }
  3955. break;
  3956. }
  3957. default:
  3958. throw this.unexpected();
  3959. }
  3960. }
  3961. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3962. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  3963. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3964. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3965. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3966. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3967. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3968. }
  3969. }
  3970. }
  3971. if (isFragment(openingElement)) {
  3972. node.openingFragment = openingElement;
  3973. node.closingFragment = closingElement;
  3974. } else {
  3975. node.openingElement = openingElement;
  3976. node.closingElement = closingElement;
  3977. }
  3978. node.children = children;
  3979. if (this.isRelational("<")) {
  3980. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  3981. }
  3982. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3983. }
  3984. jsxParseElement() {
  3985. const startPos = this.state.start;
  3986. const startLoc = this.state.startLoc;
  3987. this.next();
  3988. return this.jsxParseElementAt(startPos, startLoc);
  3989. }
  3990. parseExprAtom(refExpressionErrors) {
  3991. if (this.match(types.jsxText)) {
  3992. return this.parseLiteral(this.state.value, "JSXText");
  3993. } else if (this.match(types.jsxTagStart)) {
  3994. return this.jsxParseElement();
  3995. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3996. this.finishToken(types.jsxTagStart);
  3997. return this.jsxParseElement();
  3998. } else {
  3999. return super.parseExprAtom(refExpressionErrors);
  4000. }
  4001. }
  4002. getTokenFromCode(code) {
  4003. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  4004. const context = this.curContext();
  4005. if (context === types$1.j_expr) {
  4006. return this.jsxReadToken();
  4007. }
  4008. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  4009. if (isIdentifierStart(code)) {
  4010. return this.jsxReadWord();
  4011. }
  4012. if (code === 62) {
  4013. ++this.state.pos;
  4014. return this.finishToken(types.jsxTagEnd);
  4015. }
  4016. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  4017. return this.jsxReadString(code);
  4018. }
  4019. }
  4020. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  4021. ++this.state.pos;
  4022. return this.finishToken(types.jsxTagStart);
  4023. }
  4024. return super.getTokenFromCode(code);
  4025. }
  4026. updateContext(prevType) {
  4027. if (this.match(types.braceL)) {
  4028. const curContext = this.curContext();
  4029. if (curContext === types$1.j_oTag) {
  4030. this.state.context.push(types$1.braceExpression);
  4031. } else if (curContext === types$1.j_expr) {
  4032. this.state.context.push(types$1.templateQuasi);
  4033. } else {
  4034. super.updateContext(prevType);
  4035. }
  4036. this.state.exprAllowed = true;
  4037. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  4038. this.state.context.length -= 2;
  4039. this.state.context.push(types$1.j_cTag);
  4040. this.state.exprAllowed = false;
  4041. } else {
  4042. return super.updateContext(prevType);
  4043. }
  4044. }
  4045. });
  4046. class Scope {
  4047. constructor(flags) {
  4048. this.flags = void 0;
  4049. this.var = [];
  4050. this.lexical = [];
  4051. this.functions = [];
  4052. this.flags = flags;
  4053. }
  4054. }
  4055. class ScopeHandler {
  4056. constructor(raise, inModule) {
  4057. this.scopeStack = [];
  4058. this.undefinedExports = new Map();
  4059. this.undefinedPrivateNames = new Map();
  4060. this.raise = raise;
  4061. this.inModule = inModule;
  4062. }
  4063. get inFunction() {
  4064. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  4065. }
  4066. get allowSuper() {
  4067. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  4068. }
  4069. get allowDirectSuper() {
  4070. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  4071. }
  4072. get inClass() {
  4073. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  4074. }
  4075. get inNonArrowFunction() {
  4076. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  4077. }
  4078. get treatFunctionsAsVar() {
  4079. return this.treatFunctionsAsVarInScope(this.currentScope());
  4080. }
  4081. createScope(flags) {
  4082. return new Scope(flags);
  4083. }
  4084. enter(flags) {
  4085. this.scopeStack.push(this.createScope(flags));
  4086. }
  4087. exit() {
  4088. this.scopeStack.pop();
  4089. }
  4090. treatFunctionsAsVarInScope(scope) {
  4091. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  4092. }
  4093. declareName(name, bindingType, pos) {
  4094. let scope = this.currentScope();
  4095. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  4096. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4097. if (bindingType & BIND_SCOPE_FUNCTION) {
  4098. scope.functions.push(name);
  4099. } else {
  4100. scope.lexical.push(name);
  4101. }
  4102. if (bindingType & BIND_SCOPE_LEXICAL) {
  4103. this.maybeExportDefined(scope, name);
  4104. }
  4105. } else if (bindingType & BIND_SCOPE_VAR) {
  4106. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  4107. scope = this.scopeStack[i];
  4108. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4109. scope.var.push(name);
  4110. this.maybeExportDefined(scope, name);
  4111. if (scope.flags & SCOPE_VAR) break;
  4112. }
  4113. }
  4114. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4115. this.undefinedExports.delete(name);
  4116. }
  4117. }
  4118. maybeExportDefined(scope, name) {
  4119. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4120. this.undefinedExports.delete(name);
  4121. }
  4122. }
  4123. checkRedeclarationInScope(scope, name, bindingType, pos) {
  4124. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  4125. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  4126. }
  4127. }
  4128. isRedeclaredInScope(scope, name, bindingType) {
  4129. if (!(bindingType & BIND_KIND_VALUE)) return false;
  4130. if (bindingType & BIND_SCOPE_LEXICAL) {
  4131. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  4132. }
  4133. if (bindingType & BIND_SCOPE_FUNCTION) {
  4134. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  4135. }
  4136. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  4137. }
  4138. checkLocalExport(id) {
  4139. 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) {
  4140. this.undefinedExports.set(id.name, id.start);
  4141. }
  4142. }
  4143. currentScope() {
  4144. return this.scopeStack[this.scopeStack.length - 1];
  4145. }
  4146. currentVarScope() {
  4147. for (let i = this.scopeStack.length - 1;; i--) {
  4148. const scope = this.scopeStack[i];
  4149. if (scope.flags & SCOPE_VAR) {
  4150. return scope;
  4151. }
  4152. }
  4153. }
  4154. currentThisScope() {
  4155. for (let i = this.scopeStack.length - 1;; i--) {
  4156. const scope = this.scopeStack[i];
  4157. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  4158. return scope;
  4159. }
  4160. }
  4161. }
  4162. }
  4163. class TypeScriptScope extends Scope {
  4164. constructor(...args) {
  4165. super(...args);
  4166. this.types = [];
  4167. this.enums = [];
  4168. this.constEnums = [];
  4169. this.classes = [];
  4170. this.exportOnlyBindings = [];
  4171. }
  4172. }
  4173. class TypeScriptScopeHandler extends ScopeHandler {
  4174. createScope(flags) {
  4175. return new TypeScriptScope(flags);
  4176. }
  4177. declareName(name, bindingType, pos) {
  4178. const scope = this.currentScope();
  4179. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4180. this.maybeExportDefined(scope, name);
  4181. scope.exportOnlyBindings.push(name);
  4182. return;
  4183. }
  4184. super.declareName(...arguments);
  4185. if (bindingType & BIND_KIND_TYPE) {
  4186. if (!(bindingType & BIND_KIND_VALUE)) {
  4187. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4188. this.maybeExportDefined(scope, name);
  4189. }
  4190. scope.types.push(name);
  4191. }
  4192. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4193. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4194. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4195. }
  4196. isRedeclaredInScope(scope, name, bindingType) {
  4197. if (scope.enums.indexOf(name) > -1) {
  4198. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4199. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4200. const wasConst = scope.constEnums.indexOf(name) > -1;
  4201. return isConst !== wasConst;
  4202. }
  4203. return true;
  4204. }
  4205. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4206. if (scope.lexical.indexOf(name) > -1) {
  4207. return !!(bindingType & BIND_KIND_VALUE);
  4208. } else {
  4209. return false;
  4210. }
  4211. }
  4212. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4213. return true;
  4214. }
  4215. return super.isRedeclaredInScope(...arguments);
  4216. }
  4217. checkLocalExport(id) {
  4218. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4219. super.checkLocalExport(id);
  4220. }
  4221. }
  4222. }
  4223. const PARAM = 0b0000,
  4224. PARAM_YIELD = 0b0001,
  4225. PARAM_AWAIT = 0b0010,
  4226. PARAM_RETURN = 0b0100,
  4227. PARAM_IN = 0b1000;
  4228. class ProductionParameterHandler {
  4229. constructor() {
  4230. this.stacks = [];
  4231. }
  4232. enter(flags) {
  4233. this.stacks.push(flags);
  4234. }
  4235. exit() {
  4236. this.stacks.pop();
  4237. }
  4238. currentFlags() {
  4239. return this.stacks[this.stacks.length - 1];
  4240. }
  4241. get hasAwait() {
  4242. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4243. }
  4244. get hasYield() {
  4245. return (this.currentFlags() & PARAM_YIELD) > 0;
  4246. }
  4247. get hasReturn() {
  4248. return (this.currentFlags() & PARAM_RETURN) > 0;
  4249. }
  4250. get hasIn() {
  4251. return (this.currentFlags() & PARAM_IN) > 0;
  4252. }
  4253. }
  4254. function functionFlags(isAsync, isGenerator) {
  4255. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4256. }
  4257. function nonNull(x) {
  4258. if (x == null) {
  4259. throw new Error(`Unexpected ${x} value.`);
  4260. }
  4261. return x;
  4262. }
  4263. function assert(x) {
  4264. if (!x) {
  4265. throw new Error("Assert fail");
  4266. }
  4267. }
  4268. const TSErrors = Object.freeze({
  4269. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4270. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4271. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  4272. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  4273. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  4274. DuplicateModifier: "Duplicate modifier: '%0'",
  4275. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4276. EmptyTypeArguments: "Type argument list cannot be empty.",
  4277. EmptyTypeParameters: "Type parameter list cannot be empty.",
  4278. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4279. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4280. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4281. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
  4282. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  4283. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  4284. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4285. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4286. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4287. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4288. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4289. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  4290. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4291. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4292. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4293. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4294. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4295. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4296. });
  4297. function keywordTypeFromName(value) {
  4298. switch (value) {
  4299. case "any":
  4300. return "TSAnyKeyword";
  4301. case "boolean":
  4302. return "TSBooleanKeyword";
  4303. case "bigint":
  4304. return "TSBigIntKeyword";
  4305. case "never":
  4306. return "TSNeverKeyword";
  4307. case "number":
  4308. return "TSNumberKeyword";
  4309. case "object":
  4310. return "TSObjectKeyword";
  4311. case "string":
  4312. return "TSStringKeyword";
  4313. case "symbol":
  4314. return "TSSymbolKeyword";
  4315. case "undefined":
  4316. return "TSUndefinedKeyword";
  4317. case "unknown":
  4318. return "TSUnknownKeyword";
  4319. default:
  4320. return undefined;
  4321. }
  4322. }
  4323. var typescript = (superClass => class extends superClass {
  4324. getScopeHandler() {
  4325. return TypeScriptScopeHandler;
  4326. }
  4327. tsIsIdentifier() {
  4328. return this.match(types.name);
  4329. }
  4330. tsNextTokenCanFollowModifier() {
  4331. this.next();
  4332. return !this.hasPrecedingLineBreak() && !this.match(types.parenL) && !this.match(types.parenR) && !this.match(types.colon) && !this.match(types.eq) && !this.match(types.question) && !this.match(types.bang);
  4333. }
  4334. tsParseModifier(allowedModifiers) {
  4335. if (!this.match(types.name)) {
  4336. return undefined;
  4337. }
  4338. const modifier = this.state.value;
  4339. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4340. return modifier;
  4341. }
  4342. return undefined;
  4343. }
  4344. tsParseModifiers(modified, allowedModifiers) {
  4345. for (;;) {
  4346. const startPos = this.state.start;
  4347. const modifier = this.tsParseModifier(allowedModifiers);
  4348. if (!modifier) break;
  4349. if (Object.hasOwnProperty.call(modified, modifier)) {
  4350. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4351. }
  4352. modified[modifier] = true;
  4353. }
  4354. }
  4355. tsIsListTerminator(kind) {
  4356. switch (kind) {
  4357. case "EnumMembers":
  4358. case "TypeMembers":
  4359. return this.match(types.braceR);
  4360. case "HeritageClauseElement":
  4361. return this.match(types.braceL);
  4362. case "TupleElementTypes":
  4363. return this.match(types.bracketR);
  4364. case "TypeParametersOrArguments":
  4365. return this.isRelational(">");
  4366. }
  4367. throw new Error("Unreachable");
  4368. }
  4369. tsParseList(kind, parseElement) {
  4370. const result = [];
  4371. while (!this.tsIsListTerminator(kind)) {
  4372. result.push(parseElement());
  4373. }
  4374. return result;
  4375. }
  4376. tsParseDelimitedList(kind, parseElement) {
  4377. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4378. }
  4379. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4380. const result = [];
  4381. for (;;) {
  4382. if (this.tsIsListTerminator(kind)) {
  4383. break;
  4384. }
  4385. const element = parseElement();
  4386. if (element == null) {
  4387. return undefined;
  4388. }
  4389. result.push(element);
  4390. if (this.eat(types.comma)) {
  4391. continue;
  4392. }
  4393. if (this.tsIsListTerminator(kind)) {
  4394. break;
  4395. }
  4396. if (expectSuccess) {
  4397. this.expect(types.comma);
  4398. }
  4399. return undefined;
  4400. }
  4401. return result;
  4402. }
  4403. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4404. if (!skipFirstToken) {
  4405. if (bracket) {
  4406. this.expect(types.bracketL);
  4407. } else {
  4408. this.expectRelational("<");
  4409. }
  4410. }
  4411. const result = this.tsParseDelimitedList(kind, parseElement);
  4412. if (bracket) {
  4413. this.expect(types.bracketR);
  4414. } else {
  4415. this.expectRelational(">");
  4416. }
  4417. return result;
  4418. }
  4419. tsParseImportType() {
  4420. const node = this.startNode();
  4421. this.expect(types._import);
  4422. this.expect(types.parenL);
  4423. if (!this.match(types.string)) {
  4424. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4425. }
  4426. node.argument = this.parseExprAtom();
  4427. this.expect(types.parenR);
  4428. if (this.eat(types.dot)) {
  4429. node.qualifier = this.tsParseEntityName(true);
  4430. }
  4431. if (this.isRelational("<")) {
  4432. node.typeParameters = this.tsParseTypeArguments();
  4433. }
  4434. return this.finishNode(node, "TSImportType");
  4435. }
  4436. tsParseEntityName(allowReservedWords) {
  4437. let entity = this.parseIdentifier();
  4438. while (this.eat(types.dot)) {
  4439. const node = this.startNodeAtNode(entity);
  4440. node.left = entity;
  4441. node.right = this.parseIdentifier(allowReservedWords);
  4442. entity = this.finishNode(node, "TSQualifiedName");
  4443. }
  4444. return entity;
  4445. }
  4446. tsParseTypeReference() {
  4447. const node = this.startNode();
  4448. node.typeName = this.tsParseEntityName(false);
  4449. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4450. node.typeParameters = this.tsParseTypeArguments();
  4451. }
  4452. return this.finishNode(node, "TSTypeReference");
  4453. }
  4454. tsParseThisTypePredicate(lhs) {
  4455. this.next();
  4456. const node = this.startNodeAtNode(lhs);
  4457. node.parameterName = lhs;
  4458. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4459. return this.finishNode(node, "TSTypePredicate");
  4460. }
  4461. tsParseThisTypeNode() {
  4462. const node = this.startNode();
  4463. this.next();
  4464. return this.finishNode(node, "TSThisType");
  4465. }
  4466. tsParseTypeQuery() {
  4467. const node = this.startNode();
  4468. this.expect(types._typeof);
  4469. if (this.match(types._import)) {
  4470. node.exprName = this.tsParseImportType();
  4471. } else {
  4472. node.exprName = this.tsParseEntityName(true);
  4473. }
  4474. return this.finishNode(node, "TSTypeQuery");
  4475. }
  4476. tsParseTypeParameter() {
  4477. const node = this.startNode();
  4478. node.name = this.parseIdentifierName(node.start);
  4479. node.constraint = this.tsEatThenParseType(types._extends);
  4480. node.default = this.tsEatThenParseType(types.eq);
  4481. return this.finishNode(node, "TSTypeParameter");
  4482. }
  4483. tsTryParseTypeParameters() {
  4484. if (this.isRelational("<")) {
  4485. return this.tsParseTypeParameters();
  4486. }
  4487. }
  4488. tsParseTypeParameters() {
  4489. const node = this.startNode();
  4490. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4491. this.next();
  4492. } else {
  4493. this.unexpected();
  4494. }
  4495. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4496. if (node.params.length === 0) {
  4497. this.raise(node.start, TSErrors.EmptyTypeParameters);
  4498. }
  4499. return this.finishNode(node, "TSTypeParameterDeclaration");
  4500. }
  4501. tsTryNextParseConstantContext() {
  4502. if (this.lookahead().type === types._const) {
  4503. this.next();
  4504. return this.tsParseTypeReference();
  4505. }
  4506. return null;
  4507. }
  4508. tsFillSignature(returnToken, signature) {
  4509. const returnTokenRequired = returnToken === types.arrow;
  4510. signature.typeParameters = this.tsTryParseTypeParameters();
  4511. this.expect(types.parenL);
  4512. signature.parameters = this.tsParseBindingListForSignature();
  4513. if (returnTokenRequired) {
  4514. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4515. } else if (this.match(returnToken)) {
  4516. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4517. }
  4518. }
  4519. tsParseBindingListForSignature() {
  4520. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4521. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4522. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4523. }
  4524. return pattern;
  4525. });
  4526. }
  4527. tsParseTypeMemberSemicolon() {
  4528. if (!this.eat(types.comma)) {
  4529. this.semicolon();
  4530. }
  4531. }
  4532. tsParseSignatureMember(kind, node) {
  4533. this.tsFillSignature(types.colon, node);
  4534. this.tsParseTypeMemberSemicolon();
  4535. return this.finishNode(node, kind);
  4536. }
  4537. tsIsUnambiguouslyIndexSignature() {
  4538. this.next();
  4539. return this.eat(types.name) && this.match(types.colon);
  4540. }
  4541. tsTryParseIndexSignature(node) {
  4542. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4543. return undefined;
  4544. }
  4545. this.expect(types.bracketL);
  4546. const id = this.parseIdentifier();
  4547. id.typeAnnotation = this.tsParseTypeAnnotation();
  4548. this.resetEndLocation(id);
  4549. this.expect(types.bracketR);
  4550. node.parameters = [id];
  4551. const type = this.tsTryParseTypeAnnotation();
  4552. if (type) node.typeAnnotation = type;
  4553. this.tsParseTypeMemberSemicolon();
  4554. return this.finishNode(node, "TSIndexSignature");
  4555. }
  4556. tsParsePropertyOrMethodSignature(node, readonly) {
  4557. if (this.eat(types.question)) node.optional = true;
  4558. const nodeAny = node;
  4559. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  4560. const method = nodeAny;
  4561. this.tsFillSignature(types.colon, method);
  4562. this.tsParseTypeMemberSemicolon();
  4563. return this.finishNode(method, "TSMethodSignature");
  4564. } else {
  4565. const property = nodeAny;
  4566. if (readonly) property.readonly = true;
  4567. const type = this.tsTryParseTypeAnnotation();
  4568. if (type) property.typeAnnotation = type;
  4569. this.tsParseTypeMemberSemicolon();
  4570. return this.finishNode(property, "TSPropertySignature");
  4571. }
  4572. }
  4573. tsParseTypeMember() {
  4574. const node = this.startNode();
  4575. if (this.match(types.parenL) || this.isRelational("<")) {
  4576. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4577. }
  4578. if (this.match(types._new)) {
  4579. const id = this.startNode();
  4580. this.next();
  4581. if (this.match(types.parenL) || this.isRelational("<")) {
  4582. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4583. } else {
  4584. node.key = this.createIdentifier(id, "new");
  4585. return this.tsParsePropertyOrMethodSignature(node, false);
  4586. }
  4587. }
  4588. const readonly = !!this.tsParseModifier(["readonly"]);
  4589. const idx = this.tsTryParseIndexSignature(node);
  4590. if (idx) {
  4591. if (readonly) node.readonly = true;
  4592. return idx;
  4593. }
  4594. this.parsePropertyName(node, false);
  4595. return this.tsParsePropertyOrMethodSignature(node, readonly);
  4596. }
  4597. tsParseTypeLiteral() {
  4598. const node = this.startNode();
  4599. node.members = this.tsParseObjectTypeMembers();
  4600. return this.finishNode(node, "TSTypeLiteral");
  4601. }
  4602. tsParseObjectTypeMembers() {
  4603. this.expect(types.braceL);
  4604. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4605. this.expect(types.braceR);
  4606. return members;
  4607. }
  4608. tsIsStartOfMappedType() {
  4609. this.next();
  4610. if (this.eat(types.plusMin)) {
  4611. return this.isContextual("readonly");
  4612. }
  4613. if (this.isContextual("readonly")) {
  4614. this.next();
  4615. }
  4616. if (!this.match(types.bracketL)) {
  4617. return false;
  4618. }
  4619. this.next();
  4620. if (!this.tsIsIdentifier()) {
  4621. return false;
  4622. }
  4623. this.next();
  4624. return this.match(types._in);
  4625. }
  4626. tsParseMappedTypeParameter() {
  4627. const node = this.startNode();
  4628. node.name = this.parseIdentifierName(node.start);
  4629. node.constraint = this.tsExpectThenParseType(types._in);
  4630. return this.finishNode(node, "TSTypeParameter");
  4631. }
  4632. tsParseMappedType() {
  4633. const node = this.startNode();
  4634. this.expect(types.braceL);
  4635. if (this.match(types.plusMin)) {
  4636. node.readonly = this.state.value;
  4637. this.next();
  4638. this.expectContextual("readonly");
  4639. } else if (this.eatContextual("readonly")) {
  4640. node.readonly = true;
  4641. }
  4642. this.expect(types.bracketL);
  4643. node.typeParameter = this.tsParseMappedTypeParameter();
  4644. node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
  4645. this.expect(types.bracketR);
  4646. if (this.match(types.plusMin)) {
  4647. node.optional = this.state.value;
  4648. this.next();
  4649. this.expect(types.question);
  4650. } else if (this.eat(types.question)) {
  4651. node.optional = true;
  4652. }
  4653. node.typeAnnotation = this.tsTryParseType();
  4654. this.semicolon();
  4655. this.expect(types.braceR);
  4656. return this.finishNode(node, "TSMappedType");
  4657. }
  4658. tsParseTupleType() {
  4659. const node = this.startNode();
  4660. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4661. let seenOptionalElement = false;
  4662. let labeledElements = null;
  4663. node.elementTypes.forEach(elementNode => {
  4664. var _labeledElements;
  4665. let {
  4666. type
  4667. } = elementNode;
  4668. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  4669. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4670. }
  4671. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  4672. if (type === "TSRestType") {
  4673. elementNode = elementNode.typeAnnotation;
  4674. type = elementNode.type;
  4675. }
  4676. const isLabeled = type === "TSNamedTupleMember";
  4677. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  4678. if (labeledElements !== isLabeled) {
  4679. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  4680. }
  4681. });
  4682. return this.finishNode(node, "TSTupleType");
  4683. }
  4684. tsParseTupleElementType() {
  4685. const {
  4686. start: startPos,
  4687. startLoc
  4688. } = this.state;
  4689. const rest = this.eat(types.ellipsis);
  4690. let type = this.tsParseType();
  4691. const optional = this.eat(types.question);
  4692. const labeled = this.eat(types.colon);
  4693. if (labeled) {
  4694. const labeledNode = this.startNodeAtNode(type);
  4695. labeledNode.optional = optional;
  4696. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  4697. labeledNode.label = type.typeName;
  4698. } else {
  4699. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  4700. labeledNode.label = type;
  4701. }
  4702. labeledNode.elementType = this.tsParseType();
  4703. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  4704. } else if (optional) {
  4705. const optionalTypeNode = this.startNodeAtNode(type);
  4706. optionalTypeNode.typeAnnotation = type;
  4707. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  4708. }
  4709. if (rest) {
  4710. const restNode = this.startNodeAt(startPos, startLoc);
  4711. restNode.typeAnnotation = type;
  4712. type = this.finishNode(restNode, "TSRestType");
  4713. }
  4714. return type;
  4715. }
  4716. tsParseParenthesizedType() {
  4717. const node = this.startNode();
  4718. this.expect(types.parenL);
  4719. node.typeAnnotation = this.tsParseType();
  4720. this.expect(types.parenR);
  4721. return this.finishNode(node, "TSParenthesizedType");
  4722. }
  4723. tsParseFunctionOrConstructorType(type) {
  4724. const node = this.startNode();
  4725. if (type === "TSConstructorType") {
  4726. this.expect(types._new);
  4727. }
  4728. this.tsFillSignature(types.arrow, node);
  4729. return this.finishNode(node, type);
  4730. }
  4731. tsParseLiteralTypeNode() {
  4732. const node = this.startNode();
  4733. node.literal = (() => {
  4734. switch (this.state.type) {
  4735. case types.num:
  4736. case types.bigint:
  4737. case types.string:
  4738. case types._true:
  4739. case types._false:
  4740. return this.parseExprAtom();
  4741. default:
  4742. throw this.unexpected();
  4743. }
  4744. })();
  4745. return this.finishNode(node, "TSLiteralType");
  4746. }
  4747. tsParseTemplateLiteralType() {
  4748. const node = this.startNode();
  4749. node.literal = this.parseTemplate(false);
  4750. return this.finishNode(node, "TSLiteralType");
  4751. }
  4752. parseTemplateSubstitution() {
  4753. if (this.state.inType) return this.tsParseType();
  4754. return super.parseTemplateSubstitution();
  4755. }
  4756. tsParseThisTypeOrThisTypePredicate() {
  4757. const thisKeyword = this.tsParseThisTypeNode();
  4758. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4759. return this.tsParseThisTypePredicate(thisKeyword);
  4760. } else {
  4761. return thisKeyword;
  4762. }
  4763. }
  4764. tsParseNonArrayType() {
  4765. switch (this.state.type) {
  4766. case types.name:
  4767. case types._void:
  4768. case types._null:
  4769. {
  4770. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4771. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4772. const node = this.startNode();
  4773. this.next();
  4774. return this.finishNode(node, type);
  4775. }
  4776. return this.tsParseTypeReference();
  4777. }
  4778. case types.string:
  4779. case types.num:
  4780. case types.bigint:
  4781. case types._true:
  4782. case types._false:
  4783. return this.tsParseLiteralTypeNode();
  4784. case types.plusMin:
  4785. if (this.state.value === "-") {
  4786. const node = this.startNode();
  4787. const nextToken = this.lookahead();
  4788. if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
  4789. throw this.unexpected();
  4790. }
  4791. node.literal = this.parseMaybeUnary();
  4792. return this.finishNode(node, "TSLiteralType");
  4793. }
  4794. break;
  4795. case types._this:
  4796. return this.tsParseThisTypeOrThisTypePredicate();
  4797. case types._typeof:
  4798. return this.tsParseTypeQuery();
  4799. case types._import:
  4800. return this.tsParseImportType();
  4801. case types.braceL:
  4802. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4803. case types.bracketL:
  4804. return this.tsParseTupleType();
  4805. case types.parenL:
  4806. return this.tsParseParenthesizedType();
  4807. case types.backQuote:
  4808. return this.tsParseTemplateLiteralType();
  4809. }
  4810. throw this.unexpected();
  4811. }
  4812. tsParseArrayTypeOrHigher() {
  4813. let type = this.tsParseNonArrayType();
  4814. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4815. if (this.match(types.bracketR)) {
  4816. const node = this.startNodeAtNode(type);
  4817. node.elementType = type;
  4818. this.expect(types.bracketR);
  4819. type = this.finishNode(node, "TSArrayType");
  4820. } else {
  4821. const node = this.startNodeAtNode(type);
  4822. node.objectType = type;
  4823. node.indexType = this.tsParseType();
  4824. this.expect(types.bracketR);
  4825. type = this.finishNode(node, "TSIndexedAccessType");
  4826. }
  4827. }
  4828. return type;
  4829. }
  4830. tsParseTypeOperator(operator) {
  4831. const node = this.startNode();
  4832. this.expectContextual(operator);
  4833. node.operator = operator;
  4834. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4835. if (operator === "readonly") {
  4836. this.tsCheckTypeAnnotationForReadOnly(node);
  4837. }
  4838. return this.finishNode(node, "TSTypeOperator");
  4839. }
  4840. tsCheckTypeAnnotationForReadOnly(node) {
  4841. switch (node.typeAnnotation.type) {
  4842. case "TSTupleType":
  4843. case "TSArrayType":
  4844. return;
  4845. default:
  4846. this.raise(node.start, TSErrors.UnexpectedReadonly);
  4847. }
  4848. }
  4849. tsParseInferType() {
  4850. const node = this.startNode();
  4851. this.expectContextual("infer");
  4852. const typeParameter = this.startNode();
  4853. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4854. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4855. return this.finishNode(node, "TSInferType");
  4856. }
  4857. tsParseTypeOperatorOrHigher() {
  4858. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4859. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4860. }
  4861. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4862. this.eat(operator);
  4863. let type = parseConstituentType();
  4864. if (this.match(operator)) {
  4865. const types = [type];
  4866. while (this.eat(operator)) {
  4867. types.push(parseConstituentType());
  4868. }
  4869. const node = this.startNodeAtNode(type);
  4870. node.types = types;
  4871. type = this.finishNode(node, kind);
  4872. }
  4873. return type;
  4874. }
  4875. tsParseIntersectionTypeOrHigher() {
  4876. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4877. }
  4878. tsParseUnionTypeOrHigher() {
  4879. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4880. }
  4881. tsIsStartOfFunctionType() {
  4882. if (this.isRelational("<")) {
  4883. return true;
  4884. }
  4885. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4886. }
  4887. tsSkipParameterStart() {
  4888. if (this.match(types.name) || this.match(types._this)) {
  4889. this.next();
  4890. return true;
  4891. }
  4892. if (this.match(types.braceL)) {
  4893. let braceStackCounter = 1;
  4894. this.next();
  4895. while (braceStackCounter > 0) {
  4896. if (this.match(types.braceL)) {
  4897. ++braceStackCounter;
  4898. } else if (this.match(types.braceR)) {
  4899. --braceStackCounter;
  4900. }
  4901. this.next();
  4902. }
  4903. return true;
  4904. }
  4905. if (this.match(types.bracketL)) {
  4906. let braceStackCounter = 1;
  4907. this.next();
  4908. while (braceStackCounter > 0) {
  4909. if (this.match(types.bracketL)) {
  4910. ++braceStackCounter;
  4911. } else if (this.match(types.bracketR)) {
  4912. --braceStackCounter;
  4913. }
  4914. this.next();
  4915. }
  4916. return true;
  4917. }
  4918. return false;
  4919. }
  4920. tsIsUnambiguouslyStartOfFunctionType() {
  4921. this.next();
  4922. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4923. return true;
  4924. }
  4925. if (this.tsSkipParameterStart()) {
  4926. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4927. return true;
  4928. }
  4929. if (this.match(types.parenR)) {
  4930. this.next();
  4931. if (this.match(types.arrow)) {
  4932. return true;
  4933. }
  4934. }
  4935. }
  4936. return false;
  4937. }
  4938. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4939. return this.tsInType(() => {
  4940. const t = this.startNode();
  4941. this.expect(returnToken);
  4942. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4943. if (asserts && this.match(types._this)) {
  4944. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4945. if (thisTypePredicate.type === "TSThisType") {
  4946. const node = this.startNodeAtNode(t);
  4947. node.parameterName = thisTypePredicate;
  4948. node.asserts = true;
  4949. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4950. } else {
  4951. thisTypePredicate.asserts = true;
  4952. }
  4953. t.typeAnnotation = thisTypePredicate;
  4954. return this.finishNode(t, "TSTypeAnnotation");
  4955. }
  4956. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4957. if (!typePredicateVariable) {
  4958. if (!asserts) {
  4959. return this.tsParseTypeAnnotation(false, t);
  4960. }
  4961. const node = this.startNodeAtNode(t);
  4962. node.parameterName = this.parseIdentifier();
  4963. node.asserts = asserts;
  4964. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4965. return this.finishNode(t, "TSTypeAnnotation");
  4966. }
  4967. const type = this.tsParseTypeAnnotation(false);
  4968. const node = this.startNodeAtNode(t);
  4969. node.parameterName = typePredicateVariable;
  4970. node.typeAnnotation = type;
  4971. node.asserts = asserts;
  4972. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4973. return this.finishNode(t, "TSTypeAnnotation");
  4974. });
  4975. }
  4976. tsTryParseTypeOrTypePredicateAnnotation() {
  4977. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4978. }
  4979. tsTryParseTypeAnnotation() {
  4980. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4981. }
  4982. tsTryParseType() {
  4983. return this.tsEatThenParseType(types.colon);
  4984. }
  4985. tsParseTypePredicatePrefix() {
  4986. const id = this.parseIdentifier();
  4987. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4988. this.next();
  4989. return id;
  4990. }
  4991. }
  4992. tsParseTypePredicateAsserts() {
  4993. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4994. return false;
  4995. }
  4996. const containsEsc = this.state.containsEsc;
  4997. this.next();
  4998. if (!this.match(types.name) && !this.match(types._this)) {
  4999. return false;
  5000. }
  5001. if (containsEsc) {
  5002. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  5003. }
  5004. return true;
  5005. }
  5006. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  5007. this.tsInType(() => {
  5008. if (eatColon) this.expect(types.colon);
  5009. t.typeAnnotation = this.tsParseType();
  5010. });
  5011. return this.finishNode(t, "TSTypeAnnotation");
  5012. }
  5013. tsParseType() {
  5014. assert(this.state.inType);
  5015. const type = this.tsParseNonConditionalType();
  5016. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  5017. return type;
  5018. }
  5019. const node = this.startNodeAtNode(type);
  5020. node.checkType = type;
  5021. node.extendsType = this.tsParseNonConditionalType();
  5022. this.expect(types.question);
  5023. node.trueType = this.tsParseType();
  5024. this.expect(types.colon);
  5025. node.falseType = this.tsParseType();
  5026. return this.finishNode(node, "TSConditionalType");
  5027. }
  5028. tsParseNonConditionalType() {
  5029. if (this.tsIsStartOfFunctionType()) {
  5030. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  5031. }
  5032. if (this.match(types._new)) {
  5033. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  5034. }
  5035. return this.tsParseUnionTypeOrHigher();
  5036. }
  5037. tsParseTypeAssertion() {
  5038. const node = this.startNode();
  5039. const _const = this.tsTryNextParseConstantContext();
  5040. node.typeAnnotation = _const || this.tsNextThenParseType();
  5041. this.expectRelational(">");
  5042. node.expression = this.parseMaybeUnary();
  5043. return this.finishNode(node, "TSTypeAssertion");
  5044. }
  5045. tsParseHeritageClause(descriptor) {
  5046. const originalStart = this.state.start;
  5047. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  5048. if (!delimitedList.length) {
  5049. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  5050. }
  5051. return delimitedList;
  5052. }
  5053. tsParseExpressionWithTypeArguments() {
  5054. const node = this.startNode();
  5055. node.expression = this.tsParseEntityName(false);
  5056. if (this.isRelational("<")) {
  5057. node.typeParameters = this.tsParseTypeArguments();
  5058. }
  5059. return this.finishNode(node, "TSExpressionWithTypeArguments");
  5060. }
  5061. tsParseInterfaceDeclaration(node) {
  5062. node.id = this.parseIdentifier();
  5063. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  5064. node.typeParameters = this.tsTryParseTypeParameters();
  5065. if (this.eat(types._extends)) {
  5066. node.extends = this.tsParseHeritageClause("extends");
  5067. }
  5068. const body = this.startNode();
  5069. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  5070. node.body = this.finishNode(body, "TSInterfaceBody");
  5071. return this.finishNode(node, "TSInterfaceDeclaration");
  5072. }
  5073. tsParseTypeAliasDeclaration(node) {
  5074. node.id = this.parseIdentifier();
  5075. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  5076. node.typeParameters = this.tsTryParseTypeParameters();
  5077. node.typeAnnotation = this.tsInType(() => {
  5078. this.expect(types.eq);
  5079. if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
  5080. const node = this.startNode();
  5081. this.next();
  5082. return this.finishNode(node, "TSIntrinsicKeyword");
  5083. }
  5084. return this.tsParseType();
  5085. });
  5086. this.semicolon();
  5087. return this.finishNode(node, "TSTypeAliasDeclaration");
  5088. }
  5089. tsInNoContext(cb) {
  5090. const oldContext = this.state.context;
  5091. this.state.context = [oldContext[0]];
  5092. try {
  5093. return cb();
  5094. } finally {
  5095. this.state.context = oldContext;
  5096. }
  5097. }
  5098. tsInType(cb) {
  5099. const oldInType = this.state.inType;
  5100. this.state.inType = true;
  5101. try {
  5102. return cb();
  5103. } finally {
  5104. this.state.inType = oldInType;
  5105. }
  5106. }
  5107. tsEatThenParseType(token) {
  5108. return !this.match(token) ? undefined : this.tsNextThenParseType();
  5109. }
  5110. tsExpectThenParseType(token) {
  5111. return this.tsDoThenParseType(() => this.expect(token));
  5112. }
  5113. tsNextThenParseType() {
  5114. return this.tsDoThenParseType(() => this.next());
  5115. }
  5116. tsDoThenParseType(cb) {
  5117. return this.tsInType(() => {
  5118. cb();
  5119. return this.tsParseType();
  5120. });
  5121. }
  5122. tsParseEnumMember() {
  5123. const node = this.startNode();
  5124. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  5125. if (this.eat(types.eq)) {
  5126. node.initializer = this.parseMaybeAssignAllowIn();
  5127. }
  5128. return this.finishNode(node, "TSEnumMember");
  5129. }
  5130. tsParseEnumDeclaration(node, isConst) {
  5131. if (isConst) node.const = true;
  5132. node.id = this.parseIdentifier();
  5133. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  5134. this.expect(types.braceL);
  5135. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  5136. this.expect(types.braceR);
  5137. return this.finishNode(node, "TSEnumDeclaration");
  5138. }
  5139. tsParseModuleBlock() {
  5140. const node = this.startNode();
  5141. this.scope.enter(SCOPE_OTHER);
  5142. this.expect(types.braceL);
  5143. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  5144. this.scope.exit();
  5145. return this.finishNode(node, "TSModuleBlock");
  5146. }
  5147. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  5148. node.id = this.parseIdentifier();
  5149. if (!nested) {
  5150. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  5151. }
  5152. if (this.eat(types.dot)) {
  5153. const inner = this.startNode();
  5154. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  5155. node.body = inner;
  5156. } else {
  5157. this.scope.enter(SCOPE_TS_MODULE);
  5158. this.prodParam.enter(PARAM);
  5159. node.body = this.tsParseModuleBlock();
  5160. this.prodParam.exit();
  5161. this.scope.exit();
  5162. }
  5163. return this.finishNode(node, "TSModuleDeclaration");
  5164. }
  5165. tsParseAmbientExternalModuleDeclaration(node) {
  5166. if (this.isContextual("global")) {
  5167. node.global = true;
  5168. node.id = this.parseIdentifier();
  5169. } else if (this.match(types.string)) {
  5170. node.id = this.parseExprAtom();
  5171. } else {
  5172. this.unexpected();
  5173. }
  5174. if (this.match(types.braceL)) {
  5175. this.scope.enter(SCOPE_TS_MODULE);
  5176. this.prodParam.enter(PARAM);
  5177. node.body = this.tsParseModuleBlock();
  5178. this.prodParam.exit();
  5179. this.scope.exit();
  5180. } else {
  5181. this.semicolon();
  5182. }
  5183. return this.finishNode(node, "TSModuleDeclaration");
  5184. }
  5185. tsParseImportEqualsDeclaration(node, isExport) {
  5186. node.isExport = isExport || false;
  5187. node.id = this.parseIdentifier();
  5188. this.checkLVal(node.id, BIND_LEXICAL, undefined, "import equals declaration");
  5189. this.expect(types.eq);
  5190. node.moduleReference = this.tsParseModuleReference();
  5191. this.semicolon();
  5192. return this.finishNode(node, "TSImportEqualsDeclaration");
  5193. }
  5194. tsIsExternalModuleReference() {
  5195. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5196. }
  5197. tsParseModuleReference() {
  5198. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5199. }
  5200. tsParseExternalModuleReference() {
  5201. const node = this.startNode();
  5202. this.expectContextual("require");
  5203. this.expect(types.parenL);
  5204. if (!this.match(types.string)) {
  5205. throw this.unexpected();
  5206. }
  5207. node.expression = this.parseExprAtom();
  5208. this.expect(types.parenR);
  5209. return this.finishNode(node, "TSExternalModuleReference");
  5210. }
  5211. tsLookAhead(f) {
  5212. const state = this.state.clone();
  5213. const res = f();
  5214. this.state = state;
  5215. return res;
  5216. }
  5217. tsTryParseAndCatch(f) {
  5218. const result = this.tryParse(abort => f() || abort());
  5219. if (result.aborted || !result.node) return undefined;
  5220. if (result.error) this.state = result.failState;
  5221. return result.node;
  5222. }
  5223. tsTryParse(f) {
  5224. const state = this.state.clone();
  5225. const result = f();
  5226. if (result !== undefined && result !== false) {
  5227. return result;
  5228. } else {
  5229. this.state = state;
  5230. return undefined;
  5231. }
  5232. }
  5233. tsTryParseDeclare(nany) {
  5234. if (this.isLineTerminator()) {
  5235. return;
  5236. }
  5237. let starttype = this.state.type;
  5238. let kind;
  5239. if (this.isContextual("let")) {
  5240. starttype = types._var;
  5241. kind = "let";
  5242. }
  5243. return this.tsInDeclareContext(() => {
  5244. switch (starttype) {
  5245. case types._function:
  5246. nany.declare = true;
  5247. return this.parseFunctionStatement(nany, false, true);
  5248. case types._class:
  5249. nany.declare = true;
  5250. return this.parseClass(nany, true, false);
  5251. case types._const:
  5252. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5253. this.expect(types._const);
  5254. this.expectContextual("enum");
  5255. return this.tsParseEnumDeclaration(nany, true);
  5256. }
  5257. case types._var:
  5258. kind = kind || this.state.value;
  5259. return this.parseVarStatement(nany, kind);
  5260. case types.name:
  5261. {
  5262. const value = this.state.value;
  5263. if (value === "global") {
  5264. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5265. } else {
  5266. return this.tsParseDeclaration(nany, value, true);
  5267. }
  5268. }
  5269. }
  5270. });
  5271. }
  5272. tsTryParseExportDeclaration() {
  5273. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5274. }
  5275. tsParseExpressionStatement(node, expr) {
  5276. switch (expr.name) {
  5277. case "declare":
  5278. {
  5279. const declaration = this.tsTryParseDeclare(node);
  5280. if (declaration) {
  5281. declaration.declare = true;
  5282. return declaration;
  5283. }
  5284. break;
  5285. }
  5286. case "global":
  5287. if (this.match(types.braceL)) {
  5288. this.scope.enter(SCOPE_TS_MODULE);
  5289. this.prodParam.enter(PARAM);
  5290. const mod = node;
  5291. mod.global = true;
  5292. mod.id = expr;
  5293. mod.body = this.tsParseModuleBlock();
  5294. this.scope.exit();
  5295. this.prodParam.exit();
  5296. return this.finishNode(mod, "TSModuleDeclaration");
  5297. }
  5298. break;
  5299. default:
  5300. return this.tsParseDeclaration(node, expr.name, false);
  5301. }
  5302. }
  5303. tsParseDeclaration(node, value, next) {
  5304. switch (value) {
  5305. case "abstract":
  5306. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  5307. const cls = node;
  5308. cls.abstract = true;
  5309. if (next) {
  5310. this.next();
  5311. if (!this.match(types._class)) {
  5312. this.unexpected(null, types._class);
  5313. }
  5314. }
  5315. return this.parseClass(cls, true, false);
  5316. }
  5317. break;
  5318. case "enum":
  5319. if (next || this.match(types.name)) {
  5320. if (next) this.next();
  5321. return this.tsParseEnumDeclaration(node, false);
  5322. }
  5323. break;
  5324. case "interface":
  5325. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5326. if (next) this.next();
  5327. return this.tsParseInterfaceDeclaration(node);
  5328. }
  5329. break;
  5330. case "module":
  5331. if (next) this.next();
  5332. if (this.match(types.string)) {
  5333. return this.tsParseAmbientExternalModuleDeclaration(node);
  5334. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5335. return this.tsParseModuleOrNamespaceDeclaration(node);
  5336. }
  5337. break;
  5338. case "namespace":
  5339. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5340. if (next) this.next();
  5341. return this.tsParseModuleOrNamespaceDeclaration(node);
  5342. }
  5343. break;
  5344. case "type":
  5345. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5346. if (next) this.next();
  5347. return this.tsParseTypeAliasDeclaration(node);
  5348. }
  5349. break;
  5350. }
  5351. }
  5352. tsCheckLineTerminatorAndMatch(tokenType, next) {
  5353. return (next || this.match(tokenType)) && !this.isLineTerminator();
  5354. }
  5355. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5356. if (!this.isRelational("<")) {
  5357. return undefined;
  5358. }
  5359. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5360. this.state.maybeInArrowParameters = true;
  5361. const res = this.tsTryParseAndCatch(() => {
  5362. const node = this.startNodeAt(startPos, startLoc);
  5363. node.typeParameters = this.tsParseTypeParameters();
  5364. super.parseFunctionParams(node);
  5365. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5366. this.expect(types.arrow);
  5367. return node;
  5368. });
  5369. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5370. if (!res) {
  5371. return undefined;
  5372. }
  5373. return this.parseArrowExpression(res, null, true);
  5374. }
  5375. tsParseTypeArguments() {
  5376. const node = this.startNode();
  5377. node.params = this.tsInType(() => this.tsInNoContext(() => {
  5378. this.expectRelational("<");
  5379. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  5380. }));
  5381. if (node.params.length === 0) {
  5382. this.raise(node.start, TSErrors.EmptyTypeArguments);
  5383. }
  5384. this.state.exprAllowed = false;
  5385. this.expectRelational(">");
  5386. return this.finishNode(node, "TSTypeParameterInstantiation");
  5387. }
  5388. tsIsDeclarationStart() {
  5389. if (this.match(types.name)) {
  5390. switch (this.state.value) {
  5391. case "abstract":
  5392. case "declare":
  5393. case "enum":
  5394. case "interface":
  5395. case "module":
  5396. case "namespace":
  5397. case "type":
  5398. return true;
  5399. }
  5400. }
  5401. return false;
  5402. }
  5403. isExportDefaultSpecifier() {
  5404. if (this.tsIsDeclarationStart()) return false;
  5405. return super.isExportDefaultSpecifier();
  5406. }
  5407. parseAssignableListItem(allowModifiers, decorators) {
  5408. const startPos = this.state.start;
  5409. const startLoc = this.state.startLoc;
  5410. let accessibility;
  5411. let readonly = false;
  5412. if (allowModifiers !== undefined) {
  5413. accessibility = this.parseAccessModifier();
  5414. readonly = !!this.tsParseModifier(["readonly"]);
  5415. if (allowModifiers === false && (accessibility || readonly)) {
  5416. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  5417. }
  5418. }
  5419. const left = this.parseMaybeDefault();
  5420. this.parseAssignableListItemTypes(left);
  5421. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  5422. if (accessibility || readonly) {
  5423. const pp = this.startNodeAt(startPos, startLoc);
  5424. if (decorators.length) {
  5425. pp.decorators = decorators;
  5426. }
  5427. if (accessibility) pp.accessibility = accessibility;
  5428. if (readonly) pp.readonly = readonly;
  5429. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  5430. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  5431. }
  5432. pp.parameter = elt;
  5433. return this.finishNode(pp, "TSParameterProperty");
  5434. }
  5435. if (decorators.length) {
  5436. left.decorators = decorators;
  5437. }
  5438. return elt;
  5439. }
  5440. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5441. if (this.match(types.colon)) {
  5442. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5443. }
  5444. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  5445. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  5446. this.finishNode(node, bodilessType);
  5447. return;
  5448. }
  5449. if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) {
  5450. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  5451. if (node.declare) {
  5452. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  5453. return;
  5454. }
  5455. }
  5456. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5457. }
  5458. registerFunctionStatementId(node) {
  5459. if (!node.body && node.id) {
  5460. this.checkLVal(node.id, BIND_TS_AMBIENT, null, "function name");
  5461. } else {
  5462. super.registerFunctionStatementId(...arguments);
  5463. }
  5464. }
  5465. tsCheckForInvalidTypeCasts(items) {
  5466. items.forEach(node => {
  5467. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  5468. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  5469. }
  5470. });
  5471. }
  5472. toReferencedList(exprList, isInParens) {
  5473. this.tsCheckForInvalidTypeCasts(exprList);
  5474. return exprList;
  5475. }
  5476. parseArrayLike(...args) {
  5477. const node = super.parseArrayLike(...args);
  5478. if (node.type === "ArrayExpression") {
  5479. this.tsCheckForInvalidTypeCasts(node.elements);
  5480. }
  5481. return node;
  5482. }
  5483. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5484. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5485. this.state.exprAllowed = false;
  5486. this.next();
  5487. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5488. nonNullExpression.expression = base;
  5489. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5490. }
  5491. if (this.isRelational("<")) {
  5492. const result = this.tsTryParseAndCatch(() => {
  5493. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5494. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5495. if (asyncArrowFn) {
  5496. return asyncArrowFn;
  5497. }
  5498. }
  5499. const node = this.startNodeAt(startPos, startLoc);
  5500. node.callee = base;
  5501. const typeArguments = this.tsParseTypeArguments();
  5502. if (typeArguments) {
  5503. if (!noCalls && this.eat(types.parenL)) {
  5504. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5505. this.tsCheckForInvalidTypeCasts(node.arguments);
  5506. node.typeParameters = typeArguments;
  5507. return this.finishCallExpression(node, state.optionalChainMember);
  5508. } else if (this.match(types.backQuote)) {
  5509. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  5510. result.typeParameters = typeArguments;
  5511. return result;
  5512. }
  5513. }
  5514. this.unexpected();
  5515. });
  5516. if (result) return result;
  5517. }
  5518. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5519. }
  5520. parseNewArguments(node) {
  5521. if (this.isRelational("<")) {
  5522. const typeParameters = this.tsTryParseAndCatch(() => {
  5523. const args = this.tsParseTypeArguments();
  5524. if (!this.match(types.parenL)) this.unexpected();
  5525. return args;
  5526. });
  5527. if (typeParameters) {
  5528. node.typeParameters = typeParameters;
  5529. }
  5530. }
  5531. super.parseNewArguments(node);
  5532. }
  5533. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  5534. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5535. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5536. node.expression = left;
  5537. const _const = this.tsTryNextParseConstantContext();
  5538. if (_const) {
  5539. node.typeAnnotation = _const;
  5540. } else {
  5541. node.typeAnnotation = this.tsNextThenParseType();
  5542. }
  5543. this.finishNode(node, "TSAsExpression");
  5544. this.reScan_lt_gt();
  5545. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  5546. }
  5547. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  5548. }
  5549. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5550. checkDuplicateExports() {}
  5551. parseImport(node) {
  5552. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5553. const ahead = this.lookahead();
  5554. if (this.match(types.name) && ahead.type === types.eq) {
  5555. return this.tsParseImportEqualsDeclaration(node);
  5556. }
  5557. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  5558. node.importKind = "type";
  5559. this.next();
  5560. }
  5561. }
  5562. if (!node.importKind) {
  5563. node.importKind = "value";
  5564. }
  5565. const importNode = super.parseImport(node);
  5566. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5567. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5568. }
  5569. return importNode;
  5570. }
  5571. parseExport(node) {
  5572. if (this.match(types._import)) {
  5573. this.expect(types._import);
  5574. return this.tsParseImportEqualsDeclaration(node, true);
  5575. } else if (this.eat(types.eq)) {
  5576. const assign = node;
  5577. assign.expression = this.parseExpression();
  5578. this.semicolon();
  5579. return this.finishNode(assign, "TSExportAssignment");
  5580. } else if (this.eatContextual("as")) {
  5581. const decl = node;
  5582. this.expectContextual("namespace");
  5583. decl.id = this.parseIdentifier();
  5584. this.semicolon();
  5585. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5586. } else {
  5587. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5588. this.next();
  5589. node.exportKind = "type";
  5590. } else {
  5591. node.exportKind = "value";
  5592. }
  5593. return super.parseExport(node);
  5594. }
  5595. }
  5596. isAbstractClass() {
  5597. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5598. }
  5599. parseExportDefaultExpression() {
  5600. if (this.isAbstractClass()) {
  5601. const cls = this.startNode();
  5602. this.next();
  5603. this.parseClass(cls, true, true);
  5604. cls.abstract = true;
  5605. return cls;
  5606. }
  5607. if (this.state.value === "interface") {
  5608. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5609. if (result) return result;
  5610. }
  5611. return super.parseExportDefaultExpression();
  5612. }
  5613. parseStatementContent(context, topLevel) {
  5614. if (this.state.type === types._const) {
  5615. const ahead = this.lookahead();
  5616. if (ahead.type === types.name && ahead.value === "enum") {
  5617. const node = this.startNode();
  5618. this.expect(types._const);
  5619. this.expectContextual("enum");
  5620. return this.tsParseEnumDeclaration(node, true);
  5621. }
  5622. }
  5623. return super.parseStatementContent(context, topLevel);
  5624. }
  5625. parseAccessModifier() {
  5626. return this.tsParseModifier(["public", "protected", "private"]);
  5627. }
  5628. parseClassMember(classBody, member, state) {
  5629. this.tsParseModifiers(member, ["declare"]);
  5630. const accessibility = this.parseAccessModifier();
  5631. if (accessibility) member.accessibility = accessibility;
  5632. this.tsParseModifiers(member, ["declare"]);
  5633. const callParseClassMember = () => {
  5634. super.parseClassMember(classBody, member, state);
  5635. };
  5636. if (member.declare) {
  5637. this.tsInDeclareContext(callParseClassMember);
  5638. } else {
  5639. callParseClassMember();
  5640. }
  5641. }
  5642. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  5643. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5644. const idx = this.tsTryParseIndexSignature(member);
  5645. if (idx) {
  5646. classBody.body.push(idx);
  5647. if (member.abstract) {
  5648. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5649. }
  5650. if (isStatic) {
  5651. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5652. }
  5653. if (member.accessibility) {
  5654. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5655. }
  5656. if (member.declare) {
  5657. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  5658. }
  5659. return;
  5660. }
  5661. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  5662. }
  5663. parsePostMemberNameModifiers(methodOrProp) {
  5664. const optional = this.eat(types.question);
  5665. if (optional) methodOrProp.optional = true;
  5666. if (methodOrProp.readonly && this.match(types.parenL)) {
  5667. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5668. }
  5669. if (methodOrProp.declare && this.match(types.parenL)) {
  5670. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5671. }
  5672. }
  5673. parseExpressionStatement(node, expr) {
  5674. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5675. return decl || super.parseExpressionStatement(node, expr);
  5676. }
  5677. shouldParseExportDeclaration() {
  5678. if (this.tsIsDeclarationStart()) return true;
  5679. return super.shouldParseExportDeclaration();
  5680. }
  5681. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  5682. if (!refNeedsArrowPos || !this.match(types.question)) {
  5683. return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  5684. }
  5685. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  5686. if (!result.node) {
  5687. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5688. return expr;
  5689. }
  5690. if (result.error) this.state = result.failState;
  5691. return result.node;
  5692. }
  5693. parseParenItem(node, startPos, startLoc) {
  5694. node = super.parseParenItem(node, startPos, startLoc);
  5695. if (this.eat(types.question)) {
  5696. node.optional = true;
  5697. this.resetEndLocation(node);
  5698. }
  5699. if (this.match(types.colon)) {
  5700. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5701. typeCastNode.expression = node;
  5702. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5703. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5704. }
  5705. return node;
  5706. }
  5707. parseExportDeclaration(node) {
  5708. const startPos = this.state.start;
  5709. const startLoc = this.state.startLoc;
  5710. const isDeclare = this.eatContextual("declare");
  5711. let declaration;
  5712. if (this.match(types.name)) {
  5713. declaration = this.tsTryParseExportDeclaration();
  5714. }
  5715. if (!declaration) {
  5716. declaration = super.parseExportDeclaration(node);
  5717. }
  5718. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5719. node.exportKind = "type";
  5720. }
  5721. if (declaration && isDeclare) {
  5722. this.resetStartLocation(declaration, startPos, startLoc);
  5723. declaration.declare = true;
  5724. }
  5725. return declaration;
  5726. }
  5727. parseClassId(node, isStatement, optionalId) {
  5728. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5729. return;
  5730. }
  5731. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5732. const typeParameters = this.tsTryParseTypeParameters();
  5733. if (typeParameters) node.typeParameters = typeParameters;
  5734. }
  5735. parseClassPropertyAnnotation(node) {
  5736. if (!node.optional && this.eat(types.bang)) {
  5737. node.definite = true;
  5738. }
  5739. const type = this.tsTryParseTypeAnnotation();
  5740. if (type) node.typeAnnotation = type;
  5741. }
  5742. parseClassProperty(node) {
  5743. this.parseClassPropertyAnnotation(node);
  5744. if (this.state.isDeclareContext && this.match(types.eq)) {
  5745. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5746. }
  5747. return super.parseClassProperty(node);
  5748. }
  5749. parseClassPrivateProperty(node) {
  5750. if (node.abstract) {
  5751. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  5752. }
  5753. if (node.accessibility) {
  5754. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  5755. }
  5756. this.parseClassPropertyAnnotation(node);
  5757. return super.parseClassPrivateProperty(node);
  5758. }
  5759. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5760. const typeParameters = this.tsTryParseTypeParameters();
  5761. if (typeParameters && isConstructor) {
  5762. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  5763. }
  5764. if (typeParameters) method.typeParameters = typeParameters;
  5765. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5766. }
  5767. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5768. const typeParameters = this.tsTryParseTypeParameters();
  5769. if (typeParameters) method.typeParameters = typeParameters;
  5770. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5771. }
  5772. parseClassSuper(node) {
  5773. super.parseClassSuper(node);
  5774. if (node.superClass && this.isRelational("<")) {
  5775. node.superTypeParameters = this.tsParseTypeArguments();
  5776. }
  5777. if (this.eatContextual("implements")) {
  5778. node.implements = this.tsParseHeritageClause("implements");
  5779. }
  5780. }
  5781. parseObjPropValue(prop, ...args) {
  5782. const typeParameters = this.tsTryParseTypeParameters();
  5783. if (typeParameters) prop.typeParameters = typeParameters;
  5784. super.parseObjPropValue(prop, ...args);
  5785. }
  5786. parseFunctionParams(node, allowModifiers) {
  5787. const typeParameters = this.tsTryParseTypeParameters();
  5788. if (typeParameters) node.typeParameters = typeParameters;
  5789. super.parseFunctionParams(node, allowModifiers);
  5790. }
  5791. parseVarId(decl, kind) {
  5792. super.parseVarId(decl, kind);
  5793. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5794. decl.definite = true;
  5795. }
  5796. const type = this.tsTryParseTypeAnnotation();
  5797. if (type) {
  5798. decl.id.typeAnnotation = type;
  5799. this.resetEndLocation(decl.id);
  5800. }
  5801. }
  5802. parseAsyncArrowFromCallExpression(node, call) {
  5803. if (this.match(types.colon)) {
  5804. node.returnType = this.tsParseTypeAnnotation();
  5805. }
  5806. return super.parseAsyncArrowFromCallExpression(node, call);
  5807. }
  5808. parseMaybeAssign(...args) {
  5809. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  5810. let state;
  5811. let jsx;
  5812. let typeCast;
  5813. if (this.match(types.jsxTagStart)) {
  5814. state = this.state.clone();
  5815. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5816. if (!jsx.error) return jsx.node;
  5817. const {
  5818. context
  5819. } = this.state;
  5820. if (context[context.length - 1] === types$1.j_oTag) {
  5821. context.length -= 2;
  5822. } else if (context[context.length - 1] === types$1.j_expr) {
  5823. context.length -= 1;
  5824. }
  5825. }
  5826. if (!((_jsx = jsx) == null ? void 0 : _jsx.error) && !this.isRelational("<")) {
  5827. return super.parseMaybeAssign(...args);
  5828. }
  5829. let typeParameters;
  5830. state = state || this.state.clone();
  5831. const arrow = this.tryParse(abort => {
  5832. var _typeParameters;
  5833. typeParameters = this.tsParseTypeParameters();
  5834. const expr = super.parseMaybeAssign(...args);
  5835. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5836. abort();
  5837. }
  5838. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  5839. this.resetStartLocationFromNode(expr, typeParameters);
  5840. }
  5841. expr.typeParameters = typeParameters;
  5842. return expr;
  5843. }, state);
  5844. if (!arrow.error && !arrow.aborted) return arrow.node;
  5845. if (!jsx) {
  5846. assert(!this.hasPlugin("jsx"));
  5847. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5848. if (!typeCast.error) return typeCast.node;
  5849. }
  5850. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  5851. this.state = jsx.failState;
  5852. return jsx.node;
  5853. }
  5854. if (arrow.node) {
  5855. this.state = arrow.failState;
  5856. return arrow.node;
  5857. }
  5858. if ((_typeCast = typeCast) == null ? void 0 : _typeCast.node) {
  5859. this.state = typeCast.failState;
  5860. return typeCast.node;
  5861. }
  5862. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  5863. if (arrow.thrown) throw arrow.error;
  5864. if ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.thrown) throw typeCast.error;
  5865. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  5866. }
  5867. parseMaybeUnary(refExpressionErrors) {
  5868. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5869. return this.tsParseTypeAssertion();
  5870. } else {
  5871. return super.parseMaybeUnary(refExpressionErrors);
  5872. }
  5873. }
  5874. parseArrow(node) {
  5875. if (this.match(types.colon)) {
  5876. const result = this.tryParse(abort => {
  5877. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5878. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5879. return returnType;
  5880. });
  5881. if (result.aborted) return;
  5882. if (!result.thrown) {
  5883. if (result.error) this.state = result.failState;
  5884. node.returnType = result.node;
  5885. }
  5886. }
  5887. return super.parseArrow(node);
  5888. }
  5889. parseAssignableListItemTypes(param) {
  5890. if (this.eat(types.question)) {
  5891. if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) {
  5892. this.raise(param.start, TSErrors.PatternIsOptional);
  5893. }
  5894. param.optional = true;
  5895. }
  5896. const type = this.tsTryParseTypeAnnotation();
  5897. if (type) param.typeAnnotation = type;
  5898. this.resetEndLocation(param);
  5899. return param;
  5900. }
  5901. toAssignable(node) {
  5902. switch (node.type) {
  5903. case "TSTypeCastExpression":
  5904. return super.toAssignable(this.typeCastToParameter(node));
  5905. case "TSParameterProperty":
  5906. return super.toAssignable(node);
  5907. case "TSAsExpression":
  5908. case "TSNonNullExpression":
  5909. case "TSTypeAssertion":
  5910. node.expression = this.toAssignable(node.expression);
  5911. return node;
  5912. default:
  5913. return super.toAssignable(node);
  5914. }
  5915. }
  5916. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  5917. switch (expr.type) {
  5918. case "TSTypeCastExpression":
  5919. return;
  5920. case "TSParameterProperty":
  5921. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  5922. return;
  5923. case "TSAsExpression":
  5924. case "TSNonNullExpression":
  5925. case "TSTypeAssertion":
  5926. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  5927. return;
  5928. default:
  5929. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  5930. return;
  5931. }
  5932. }
  5933. parseBindingAtom() {
  5934. switch (this.state.type) {
  5935. case types._this:
  5936. return this.parseIdentifier(true);
  5937. default:
  5938. return super.parseBindingAtom();
  5939. }
  5940. }
  5941. parseMaybeDecoratorArguments(expr) {
  5942. if (this.isRelational("<")) {
  5943. const typeArguments = this.tsParseTypeArguments();
  5944. if (this.match(types.parenL)) {
  5945. const call = super.parseMaybeDecoratorArguments(expr);
  5946. call.typeParameters = typeArguments;
  5947. return call;
  5948. }
  5949. this.unexpected(this.state.start, types.parenL);
  5950. }
  5951. return super.parseMaybeDecoratorArguments(expr);
  5952. }
  5953. isClassMethod() {
  5954. return this.isRelational("<") || super.isClassMethod();
  5955. }
  5956. isClassProperty() {
  5957. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5958. }
  5959. parseMaybeDefault(...args) {
  5960. const node = super.parseMaybeDefault(...args);
  5961. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5962. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  5963. }
  5964. return node;
  5965. }
  5966. getTokenFromCode(code) {
  5967. if (this.state.inType && (code === 62 || code === 60)) {
  5968. return this.finishOp(types.relational, 1);
  5969. } else {
  5970. return super.getTokenFromCode(code);
  5971. }
  5972. }
  5973. reScan_lt_gt() {
  5974. if (this.match(types.relational)) {
  5975. const code = this.input.charCodeAt(this.state.start);
  5976. if (code === 60 || code === 62) {
  5977. this.state.pos -= 1;
  5978. this.readToken_lt_gt(code);
  5979. }
  5980. }
  5981. }
  5982. toAssignableList(exprList) {
  5983. for (let i = 0; i < exprList.length; i++) {
  5984. const expr = exprList[i];
  5985. if (!expr) continue;
  5986. switch (expr.type) {
  5987. case "TSTypeCastExpression":
  5988. exprList[i] = this.typeCastToParameter(expr);
  5989. break;
  5990. case "TSAsExpression":
  5991. case "TSTypeAssertion":
  5992. if (!this.state.maybeInArrowParameters) {
  5993. exprList[i] = this.typeCastToParameter(expr);
  5994. } else {
  5995. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  5996. }
  5997. break;
  5998. }
  5999. }
  6000. return super.toAssignableList(...arguments);
  6001. }
  6002. typeCastToParameter(node) {
  6003. node.expression.typeAnnotation = node.typeAnnotation;
  6004. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  6005. return node.expression;
  6006. }
  6007. shouldParseArrow() {
  6008. return this.match(types.colon) || super.shouldParseArrow();
  6009. }
  6010. shouldParseAsyncArrow() {
  6011. return this.match(types.colon) || super.shouldParseAsyncArrow();
  6012. }
  6013. canHaveLeadingDecorator() {
  6014. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  6015. }
  6016. jsxParseOpeningElementAfterName(node) {
  6017. if (this.isRelational("<")) {
  6018. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  6019. if (typeArguments) node.typeParameters = typeArguments;
  6020. }
  6021. return super.jsxParseOpeningElementAfterName(node);
  6022. }
  6023. getGetterSetterExpectedParamCount(method) {
  6024. const baseCount = super.getGetterSetterExpectedParamCount(method);
  6025. const firstParam = method.params[0];
  6026. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  6027. return hasContextParam ? baseCount + 1 : baseCount;
  6028. }
  6029. parseCatchClauseParam() {
  6030. const param = super.parseCatchClauseParam();
  6031. const type = this.tsTryParseTypeAnnotation();
  6032. if (type) {
  6033. param.typeAnnotation = type;
  6034. this.resetEndLocation(param);
  6035. }
  6036. return param;
  6037. }
  6038. tsInDeclareContext(cb) {
  6039. const oldIsDeclareContext = this.state.isDeclareContext;
  6040. this.state.isDeclareContext = true;
  6041. try {
  6042. return cb();
  6043. } finally {
  6044. this.state.isDeclareContext = oldIsDeclareContext;
  6045. }
  6046. }
  6047. });
  6048. types.placeholder = new TokenType("%%", {
  6049. startsExpr: true
  6050. });
  6051. var placeholders = (superClass => class extends superClass {
  6052. parsePlaceholder(expectedNode) {
  6053. if (this.match(types.placeholder)) {
  6054. const node = this.startNode();
  6055. this.next();
  6056. this.assertNoSpace("Unexpected space in placeholder.");
  6057. node.name = super.parseIdentifier(true);
  6058. this.assertNoSpace("Unexpected space in placeholder.");
  6059. this.expect(types.placeholder);
  6060. return this.finishPlaceholder(node, expectedNode);
  6061. }
  6062. }
  6063. finishPlaceholder(node, expectedNode) {
  6064. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  6065. node.expectedNode = expectedNode;
  6066. return isFinished ? node : this.finishNode(node, "Placeholder");
  6067. }
  6068. getTokenFromCode(code) {
  6069. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  6070. return this.finishOp(types.placeholder, 2);
  6071. }
  6072. return super.getTokenFromCode(...arguments);
  6073. }
  6074. parseExprAtom() {
  6075. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  6076. }
  6077. parseIdentifier() {
  6078. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  6079. }
  6080. checkReservedWord(word) {
  6081. if (word !== undefined) super.checkReservedWord(...arguments);
  6082. }
  6083. parseBindingAtom() {
  6084. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  6085. }
  6086. checkLVal(expr) {
  6087. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  6088. }
  6089. toAssignable(node) {
  6090. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  6091. node.expectedNode = "Pattern";
  6092. return node;
  6093. }
  6094. return super.toAssignable(...arguments);
  6095. }
  6096. verifyBreakContinue(node) {
  6097. if (node.label && node.label.type === "Placeholder") return;
  6098. super.verifyBreakContinue(...arguments);
  6099. }
  6100. parseExpressionStatement(node, expr) {
  6101. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  6102. return super.parseExpressionStatement(...arguments);
  6103. }
  6104. if (this.match(types.colon)) {
  6105. const stmt = node;
  6106. stmt.label = this.finishPlaceholder(expr, "Identifier");
  6107. this.next();
  6108. stmt.body = this.parseStatement("label");
  6109. return this.finishNode(stmt, "LabeledStatement");
  6110. }
  6111. this.semicolon();
  6112. node.name = expr.name;
  6113. return this.finishPlaceholder(node, "Statement");
  6114. }
  6115. parseBlock() {
  6116. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  6117. }
  6118. parseFunctionId() {
  6119. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  6120. }
  6121. parseClass(node, isStatement, optionalId) {
  6122. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  6123. this.next();
  6124. this.takeDecorators(node);
  6125. const oldStrict = this.state.strict;
  6126. const placeholder = this.parsePlaceholder("Identifier");
  6127. if (placeholder) {
  6128. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  6129. node.id = placeholder;
  6130. } else if (optionalId || !isStatement) {
  6131. node.id = null;
  6132. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  6133. return this.finishNode(node, type);
  6134. } else {
  6135. this.unexpected(null, "A class name is required");
  6136. }
  6137. } else {
  6138. this.parseClassId(node, isStatement, optionalId);
  6139. }
  6140. this.parseClassSuper(node);
  6141. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  6142. return this.finishNode(node, type);
  6143. }
  6144. parseExport(node) {
  6145. const placeholder = this.parsePlaceholder("Identifier");
  6146. if (!placeholder) return super.parseExport(...arguments);
  6147. if (!this.isContextual("from") && !this.match(types.comma)) {
  6148. node.specifiers = [];
  6149. node.source = null;
  6150. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  6151. return this.finishNode(node, "ExportNamedDeclaration");
  6152. }
  6153. this.expectPlugin("exportDefaultFrom");
  6154. const specifier = this.startNode();
  6155. specifier.exported = placeholder;
  6156. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  6157. return super.parseExport(node);
  6158. }
  6159. isExportDefaultSpecifier() {
  6160. if (this.match(types._default)) {
  6161. const next = this.nextTokenStart();
  6162. if (this.isUnparsedContextual(next, "from")) {
  6163. if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
  6164. return true;
  6165. }
  6166. }
  6167. }
  6168. return super.isExportDefaultSpecifier();
  6169. }
  6170. maybeParseExportDefaultSpecifier(node) {
  6171. if (node.specifiers && node.specifiers.length > 0) {
  6172. return true;
  6173. }
  6174. return super.maybeParseExportDefaultSpecifier(...arguments);
  6175. }
  6176. checkExport(node) {
  6177. const {
  6178. specifiers
  6179. } = node;
  6180. if (specifiers == null ? void 0 : specifiers.length) {
  6181. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  6182. }
  6183. super.checkExport(node);
  6184. node.specifiers = specifiers;
  6185. }
  6186. parseImport(node) {
  6187. const placeholder = this.parsePlaceholder("Identifier");
  6188. if (!placeholder) return super.parseImport(...arguments);
  6189. node.specifiers = [];
  6190. if (!this.isContextual("from") && !this.match(types.comma)) {
  6191. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  6192. this.semicolon();
  6193. return this.finishNode(node, "ImportDeclaration");
  6194. }
  6195. const specifier = this.startNodeAtNode(placeholder);
  6196. specifier.local = placeholder;
  6197. this.finishNode(specifier, "ImportDefaultSpecifier");
  6198. node.specifiers.push(specifier);
  6199. if (this.eat(types.comma)) {
  6200. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  6201. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  6202. }
  6203. this.expectContextual("from");
  6204. node.source = this.parseImportSource();
  6205. this.semicolon();
  6206. return this.finishNode(node, "ImportDeclaration");
  6207. }
  6208. parseImportSource() {
  6209. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  6210. }
  6211. });
  6212. var v8intrinsic = (superClass => class extends superClass {
  6213. parseV8Intrinsic() {
  6214. if (this.match(types.modulo)) {
  6215. const v8IntrinsicStart = this.state.start;
  6216. const node = this.startNode();
  6217. this.eat(types.modulo);
  6218. if (this.match(types.name)) {
  6219. const name = this.parseIdentifierName(this.state.start);
  6220. const identifier = this.createIdentifier(node, name);
  6221. identifier.type = "V8IntrinsicIdentifier";
  6222. if (this.match(types.parenL)) {
  6223. return identifier;
  6224. }
  6225. }
  6226. this.unexpected(v8IntrinsicStart);
  6227. }
  6228. }
  6229. parseExprAtom() {
  6230. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  6231. }
  6232. });
  6233. function hasPlugin(plugins, name) {
  6234. return plugins.some(plugin => {
  6235. if (Array.isArray(plugin)) {
  6236. return plugin[0] === name;
  6237. } else {
  6238. return plugin === name;
  6239. }
  6240. });
  6241. }
  6242. function getPluginOption(plugins, name, option) {
  6243. const plugin = plugins.find(plugin => {
  6244. if (Array.isArray(plugin)) {
  6245. return plugin[0] === name;
  6246. } else {
  6247. return plugin === name;
  6248. }
  6249. });
  6250. if (plugin && Array.isArray(plugin)) {
  6251. return plugin[1][option];
  6252. }
  6253. return null;
  6254. }
  6255. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6256. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6257. function validatePlugins(plugins) {
  6258. if (hasPlugin(plugins, "decorators")) {
  6259. if (hasPlugin(plugins, "decorators-legacy")) {
  6260. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6261. }
  6262. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6263. if (decoratorsBeforeExport == null) {
  6264. 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'.");
  6265. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6266. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6267. }
  6268. }
  6269. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6270. throw new Error("Cannot combine flow and typescript plugins.");
  6271. }
  6272. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6273. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6274. }
  6275. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6276. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6277. }
  6278. if (hasPlugin(plugins, "moduleAttributes")) {
  6279. if (hasPlugin(plugins, "importAssertions")) {
  6280. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  6281. }
  6282. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  6283. if (moduleAttributesVerionPluginOption !== "may-2020") {
  6284. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  6285. }
  6286. }
  6287. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6288. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6289. }
  6290. }
  6291. const mixinPlugins = {
  6292. estree,
  6293. jsx,
  6294. flow,
  6295. typescript,
  6296. v8intrinsic,
  6297. placeholders
  6298. };
  6299. const mixinPluginNames = Object.keys(mixinPlugins);
  6300. const defaultOptions = {
  6301. sourceType: "script",
  6302. sourceFilename: undefined,
  6303. startLine: 1,
  6304. allowAwaitOutsideFunction: false,
  6305. allowReturnOutsideFunction: false,
  6306. allowImportExportEverywhere: false,
  6307. allowSuperOutsideMethod: false,
  6308. allowUndeclaredExports: false,
  6309. plugins: [],
  6310. strictMode: null,
  6311. ranges: false,
  6312. tokens: false,
  6313. createParenthesizedExpressions: false,
  6314. errorRecovery: false
  6315. };
  6316. function getOptions(opts) {
  6317. const options = {};
  6318. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  6319. const key = _Object$keys[_i];
  6320. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6321. }
  6322. return options;
  6323. }
  6324. class State {
  6325. constructor() {
  6326. this.strict = void 0;
  6327. this.curLine = void 0;
  6328. this.startLoc = void 0;
  6329. this.endLoc = void 0;
  6330. this.errors = [];
  6331. this.potentialArrowAt = -1;
  6332. this.noArrowAt = [];
  6333. this.noArrowParamsConversionAt = [];
  6334. this.maybeInArrowParameters = false;
  6335. this.inPipeline = false;
  6336. this.inType = false;
  6337. this.noAnonFunctionType = false;
  6338. this.inPropertyName = false;
  6339. this.hasFlowComment = false;
  6340. this.isIterator = false;
  6341. this.isDeclareContext = false;
  6342. this.topicContext = {
  6343. maxNumOfResolvableTopics: 0,
  6344. maxTopicIndex: null
  6345. };
  6346. this.soloAwait = false;
  6347. this.inFSharpPipelineDirectBody = false;
  6348. this.labels = [];
  6349. this.decoratorStack = [[]];
  6350. this.comments = [];
  6351. this.trailingComments = [];
  6352. this.leadingComments = [];
  6353. this.commentStack = [];
  6354. this.commentPreviousNode = null;
  6355. this.pos = 0;
  6356. this.lineStart = 0;
  6357. this.type = types.eof;
  6358. this.value = null;
  6359. this.start = 0;
  6360. this.end = 0;
  6361. this.lastTokEndLoc = null;
  6362. this.lastTokStartLoc = null;
  6363. this.lastTokStart = 0;
  6364. this.lastTokEnd = 0;
  6365. this.context = [types$1.braceStatement];
  6366. this.exprAllowed = true;
  6367. this.containsEsc = false;
  6368. this.octalPositions = [];
  6369. this.exportedIdentifiers = [];
  6370. this.tokensLength = 0;
  6371. }
  6372. init(options) {
  6373. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6374. this.curLine = options.startLine;
  6375. this.startLoc = this.endLoc = this.curPosition();
  6376. }
  6377. curPosition() {
  6378. return new Position(this.curLine, this.pos - this.lineStart);
  6379. }
  6380. clone(skipArrays) {
  6381. const state = new State();
  6382. const keys = Object.keys(this);
  6383. for (let i = 0, length = keys.length; i < length; i++) {
  6384. const key = keys[i];
  6385. let val = this[key];
  6386. if (!skipArrays && Array.isArray(val)) {
  6387. val = val.slice();
  6388. }
  6389. state[key] = val;
  6390. }
  6391. return state;
  6392. }
  6393. }
  6394. var _isDigit = function isDigit(code) {
  6395. return code >= 48 && code <= 57;
  6396. };
  6397. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6398. const forbiddenNumericSeparatorSiblings = {
  6399. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6400. hex: [46, 88, 95, 120]
  6401. };
  6402. const allowedNumericSeparatorSiblings = {};
  6403. allowedNumericSeparatorSiblings.bin = [48, 49];
  6404. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6405. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6406. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6407. class Token {
  6408. constructor(state) {
  6409. this.type = state.type;
  6410. this.value = state.value;
  6411. this.start = state.start;
  6412. this.end = state.end;
  6413. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  6414. }
  6415. }
  6416. class Tokenizer extends ParserError {
  6417. constructor(options, input) {
  6418. super();
  6419. this.isLookahead = void 0;
  6420. this.tokens = [];
  6421. this.state = new State();
  6422. this.state.init(options);
  6423. this.input = input;
  6424. this.length = input.length;
  6425. this.isLookahead = false;
  6426. }
  6427. pushToken(token) {
  6428. this.tokens.length = this.state.tokensLength;
  6429. this.tokens.push(token);
  6430. ++this.state.tokensLength;
  6431. }
  6432. next() {
  6433. if (!this.isLookahead) {
  6434. this.checkKeywordEscapes();
  6435. if (this.options.tokens) {
  6436. this.pushToken(new Token(this.state));
  6437. }
  6438. }
  6439. this.state.lastTokEnd = this.state.end;
  6440. this.state.lastTokStart = this.state.start;
  6441. this.state.lastTokEndLoc = this.state.endLoc;
  6442. this.state.lastTokStartLoc = this.state.startLoc;
  6443. this.nextToken();
  6444. }
  6445. eat(type) {
  6446. if (this.match(type)) {
  6447. this.next();
  6448. return true;
  6449. } else {
  6450. return false;
  6451. }
  6452. }
  6453. match(type) {
  6454. return this.state.type === type;
  6455. }
  6456. lookahead() {
  6457. const old = this.state;
  6458. this.state = old.clone(true);
  6459. this.isLookahead = true;
  6460. this.next();
  6461. this.isLookahead = false;
  6462. const curr = this.state;
  6463. this.state = old;
  6464. return curr;
  6465. }
  6466. nextTokenStart() {
  6467. return this.nextTokenStartSince(this.state.pos);
  6468. }
  6469. nextTokenStartSince(pos) {
  6470. skipWhiteSpace.lastIndex = pos;
  6471. const skip = skipWhiteSpace.exec(this.input);
  6472. return pos + skip[0].length;
  6473. }
  6474. lookaheadCharCode() {
  6475. return this.input.charCodeAt(this.nextTokenStart());
  6476. }
  6477. setStrict(strict) {
  6478. this.state.strict = strict;
  6479. if (!this.match(types.num) && !this.match(types.string)) return;
  6480. this.state.pos = this.state.start;
  6481. while (this.state.pos < this.state.lineStart) {
  6482. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  6483. --this.state.curLine;
  6484. }
  6485. this.nextToken();
  6486. }
  6487. curContext() {
  6488. return this.state.context[this.state.context.length - 1];
  6489. }
  6490. nextToken() {
  6491. const curContext = this.curContext();
  6492. if (!(curContext == null ? void 0 : curContext.preserveSpace)) this.skipSpace();
  6493. this.state.octalPositions = [];
  6494. this.state.start = this.state.pos;
  6495. this.state.startLoc = this.state.curPosition();
  6496. if (this.state.pos >= this.length) {
  6497. this.finishToken(types.eof);
  6498. return;
  6499. }
  6500. const override = curContext == null ? void 0 : curContext.override;
  6501. if (override) {
  6502. override(this);
  6503. } else {
  6504. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6505. }
  6506. }
  6507. pushComment(block, text, start, end, startLoc, endLoc) {
  6508. const comment = {
  6509. type: block ? "CommentBlock" : "CommentLine",
  6510. value: text,
  6511. start: start,
  6512. end: end,
  6513. loc: new SourceLocation(startLoc, endLoc)
  6514. };
  6515. if (this.options.tokens) this.pushToken(comment);
  6516. this.state.comments.push(comment);
  6517. this.addComment(comment);
  6518. }
  6519. skipBlockComment() {
  6520. const startLoc = this.state.curPosition();
  6521. const start = this.state.pos;
  6522. const end = this.input.indexOf("*/", this.state.pos + 2);
  6523. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  6524. this.state.pos = end + 2;
  6525. lineBreakG.lastIndex = start;
  6526. let match;
  6527. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6528. ++this.state.curLine;
  6529. this.state.lineStart = match.index + match[0].length;
  6530. }
  6531. if (this.isLookahead) return;
  6532. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6533. }
  6534. skipLineComment(startSkip) {
  6535. const start = this.state.pos;
  6536. const startLoc = this.state.curPosition();
  6537. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6538. if (this.state.pos < this.length) {
  6539. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6540. ch = this.input.charCodeAt(this.state.pos);
  6541. }
  6542. }
  6543. if (this.isLookahead) return;
  6544. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6545. }
  6546. skipSpace() {
  6547. loop: while (this.state.pos < this.length) {
  6548. const ch = this.input.charCodeAt(this.state.pos);
  6549. switch (ch) {
  6550. case 32:
  6551. case 160:
  6552. case 9:
  6553. ++this.state.pos;
  6554. break;
  6555. case 13:
  6556. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6557. ++this.state.pos;
  6558. }
  6559. case 10:
  6560. case 8232:
  6561. case 8233:
  6562. ++this.state.pos;
  6563. ++this.state.curLine;
  6564. this.state.lineStart = this.state.pos;
  6565. break;
  6566. case 47:
  6567. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6568. case 42:
  6569. this.skipBlockComment();
  6570. break;
  6571. case 47:
  6572. this.skipLineComment(2);
  6573. break;
  6574. default:
  6575. break loop;
  6576. }
  6577. break;
  6578. default:
  6579. if (isWhitespace(ch)) {
  6580. ++this.state.pos;
  6581. } else {
  6582. break loop;
  6583. }
  6584. }
  6585. }
  6586. }
  6587. finishToken(type, val) {
  6588. this.state.end = this.state.pos;
  6589. this.state.endLoc = this.state.curPosition();
  6590. const prevType = this.state.type;
  6591. this.state.type = type;
  6592. this.state.value = val;
  6593. if (!this.isLookahead) this.updateContext(prevType);
  6594. }
  6595. readToken_numberSign() {
  6596. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6597. return;
  6598. }
  6599. const nextPos = this.state.pos + 1;
  6600. const next = this.input.charCodeAt(nextPos);
  6601. if (next >= 48 && next <= 57) {
  6602. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  6603. }
  6604. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  6605. this.expectPlugin("recordAndTuple");
  6606. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6607. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  6608. }
  6609. if (next === 123) {
  6610. this.finishToken(types.braceHashL);
  6611. } else {
  6612. this.finishToken(types.bracketHashL);
  6613. }
  6614. this.state.pos += 2;
  6615. } else {
  6616. this.finishOp(types.hash, 1);
  6617. }
  6618. }
  6619. readToken_dot() {
  6620. const next = this.input.charCodeAt(this.state.pos + 1);
  6621. if (next >= 48 && next <= 57) {
  6622. this.readNumber(true);
  6623. return;
  6624. }
  6625. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6626. this.state.pos += 3;
  6627. this.finishToken(types.ellipsis);
  6628. } else {
  6629. ++this.state.pos;
  6630. this.finishToken(types.dot);
  6631. }
  6632. }
  6633. readToken_slash() {
  6634. if (this.state.exprAllowed && !this.state.inType) {
  6635. ++this.state.pos;
  6636. this.readRegexp();
  6637. return;
  6638. }
  6639. const next = this.input.charCodeAt(this.state.pos + 1);
  6640. if (next === 61) {
  6641. this.finishOp(types.assign, 2);
  6642. } else {
  6643. this.finishOp(types.slash, 1);
  6644. }
  6645. }
  6646. readToken_interpreter() {
  6647. if (this.state.pos !== 0 || this.length < 2) return false;
  6648. let ch = this.input.charCodeAt(this.state.pos + 1);
  6649. if (ch !== 33) return false;
  6650. const start = this.state.pos;
  6651. this.state.pos += 1;
  6652. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6653. ch = this.input.charCodeAt(this.state.pos);
  6654. }
  6655. const value = this.input.slice(start + 2, this.state.pos);
  6656. this.finishToken(types.interpreterDirective, value);
  6657. return true;
  6658. }
  6659. readToken_mult_modulo(code) {
  6660. let type = code === 42 ? types.star : types.modulo;
  6661. let width = 1;
  6662. let next = this.input.charCodeAt(this.state.pos + 1);
  6663. const exprAllowed = this.state.exprAllowed;
  6664. if (code === 42 && next === 42) {
  6665. width++;
  6666. next = this.input.charCodeAt(this.state.pos + 2);
  6667. type = types.exponent;
  6668. }
  6669. if (next === 61 && !exprAllowed) {
  6670. width++;
  6671. type = types.assign;
  6672. }
  6673. this.finishOp(type, width);
  6674. }
  6675. readToken_pipe_amp(code) {
  6676. const next = this.input.charCodeAt(this.state.pos + 1);
  6677. if (next === code) {
  6678. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6679. this.finishOp(types.assign, 3);
  6680. } else {
  6681. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6682. }
  6683. return;
  6684. }
  6685. if (code === 124) {
  6686. if (next === 62) {
  6687. this.finishOp(types.pipeline, 2);
  6688. return;
  6689. }
  6690. if (this.hasPlugin("recordAndTuple") && next === 125) {
  6691. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6692. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  6693. }
  6694. this.finishOp(types.braceBarR, 2);
  6695. return;
  6696. }
  6697. if (this.hasPlugin("recordAndTuple") && next === 93) {
  6698. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6699. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  6700. }
  6701. this.finishOp(types.bracketBarR, 2);
  6702. return;
  6703. }
  6704. }
  6705. if (next === 61) {
  6706. this.finishOp(types.assign, 2);
  6707. return;
  6708. }
  6709. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6710. }
  6711. readToken_caret() {
  6712. const next = this.input.charCodeAt(this.state.pos + 1);
  6713. if (next === 61) {
  6714. this.finishOp(types.assign, 2);
  6715. } else {
  6716. this.finishOp(types.bitwiseXOR, 1);
  6717. }
  6718. }
  6719. readToken_plus_min(code) {
  6720. const next = this.input.charCodeAt(this.state.pos + 1);
  6721. if (next === code) {
  6722. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
  6723. this.skipLineComment(3);
  6724. this.skipSpace();
  6725. this.nextToken();
  6726. return;
  6727. }
  6728. this.finishOp(types.incDec, 2);
  6729. return;
  6730. }
  6731. if (next === 61) {
  6732. this.finishOp(types.assign, 2);
  6733. } else {
  6734. this.finishOp(types.plusMin, 1);
  6735. }
  6736. }
  6737. readToken_lt_gt(code) {
  6738. const next = this.input.charCodeAt(this.state.pos + 1);
  6739. let size = 1;
  6740. if (next === code) {
  6741. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6742. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6743. this.finishOp(types.assign, size + 1);
  6744. return;
  6745. }
  6746. this.finishOp(types.bitShift, size);
  6747. return;
  6748. }
  6749. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6750. this.skipLineComment(4);
  6751. this.skipSpace();
  6752. this.nextToken();
  6753. return;
  6754. }
  6755. if (next === 61) {
  6756. size = 2;
  6757. }
  6758. this.finishOp(types.relational, size);
  6759. }
  6760. readToken_eq_excl(code) {
  6761. const next = this.input.charCodeAt(this.state.pos + 1);
  6762. if (next === 61) {
  6763. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6764. return;
  6765. }
  6766. if (code === 61 && next === 62) {
  6767. this.state.pos += 2;
  6768. this.finishToken(types.arrow);
  6769. return;
  6770. }
  6771. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6772. }
  6773. readToken_question() {
  6774. const next = this.input.charCodeAt(this.state.pos + 1);
  6775. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6776. if (next === 63) {
  6777. if (next2 === 61) {
  6778. this.finishOp(types.assign, 3);
  6779. } else {
  6780. this.finishOp(types.nullishCoalescing, 2);
  6781. }
  6782. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6783. this.state.pos += 2;
  6784. this.finishToken(types.questionDot);
  6785. } else {
  6786. ++this.state.pos;
  6787. this.finishToken(types.question);
  6788. }
  6789. }
  6790. getTokenFromCode(code) {
  6791. switch (code) {
  6792. case 46:
  6793. this.readToken_dot();
  6794. return;
  6795. case 40:
  6796. ++this.state.pos;
  6797. this.finishToken(types.parenL);
  6798. return;
  6799. case 41:
  6800. ++this.state.pos;
  6801. this.finishToken(types.parenR);
  6802. return;
  6803. case 59:
  6804. ++this.state.pos;
  6805. this.finishToken(types.semi);
  6806. return;
  6807. case 44:
  6808. ++this.state.pos;
  6809. this.finishToken(types.comma);
  6810. return;
  6811. case 91:
  6812. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6813. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6814. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  6815. }
  6816. this.finishToken(types.bracketBarL);
  6817. this.state.pos += 2;
  6818. } else {
  6819. ++this.state.pos;
  6820. this.finishToken(types.bracketL);
  6821. }
  6822. return;
  6823. case 93:
  6824. ++this.state.pos;
  6825. this.finishToken(types.bracketR);
  6826. return;
  6827. case 123:
  6828. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6829. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6830. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  6831. }
  6832. this.finishToken(types.braceBarL);
  6833. this.state.pos += 2;
  6834. } else {
  6835. ++this.state.pos;
  6836. this.finishToken(types.braceL);
  6837. }
  6838. return;
  6839. case 125:
  6840. ++this.state.pos;
  6841. this.finishToken(types.braceR);
  6842. return;
  6843. case 58:
  6844. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6845. this.finishOp(types.doubleColon, 2);
  6846. } else {
  6847. ++this.state.pos;
  6848. this.finishToken(types.colon);
  6849. }
  6850. return;
  6851. case 63:
  6852. this.readToken_question();
  6853. return;
  6854. case 96:
  6855. ++this.state.pos;
  6856. this.finishToken(types.backQuote);
  6857. return;
  6858. case 48:
  6859. {
  6860. const next = this.input.charCodeAt(this.state.pos + 1);
  6861. if (next === 120 || next === 88) {
  6862. this.readRadixNumber(16);
  6863. return;
  6864. }
  6865. if (next === 111 || next === 79) {
  6866. this.readRadixNumber(8);
  6867. return;
  6868. }
  6869. if (next === 98 || next === 66) {
  6870. this.readRadixNumber(2);
  6871. return;
  6872. }
  6873. }
  6874. case 49:
  6875. case 50:
  6876. case 51:
  6877. case 52:
  6878. case 53:
  6879. case 54:
  6880. case 55:
  6881. case 56:
  6882. case 57:
  6883. this.readNumber(false);
  6884. return;
  6885. case 34:
  6886. case 39:
  6887. this.readString(code);
  6888. return;
  6889. case 47:
  6890. this.readToken_slash();
  6891. return;
  6892. case 37:
  6893. case 42:
  6894. this.readToken_mult_modulo(code);
  6895. return;
  6896. case 124:
  6897. case 38:
  6898. this.readToken_pipe_amp(code);
  6899. return;
  6900. case 94:
  6901. this.readToken_caret();
  6902. return;
  6903. case 43:
  6904. case 45:
  6905. this.readToken_plus_min(code);
  6906. return;
  6907. case 60:
  6908. case 62:
  6909. this.readToken_lt_gt(code);
  6910. return;
  6911. case 61:
  6912. case 33:
  6913. this.readToken_eq_excl(code);
  6914. return;
  6915. case 126:
  6916. this.finishOp(types.tilde, 1);
  6917. return;
  6918. case 64:
  6919. ++this.state.pos;
  6920. this.finishToken(types.at);
  6921. return;
  6922. case 35:
  6923. this.readToken_numberSign();
  6924. return;
  6925. case 92:
  6926. this.readWord();
  6927. return;
  6928. default:
  6929. if (isIdentifierStart(code)) {
  6930. this.readWord();
  6931. return;
  6932. }
  6933. }
  6934. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  6935. }
  6936. finishOp(type, size) {
  6937. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6938. this.state.pos += size;
  6939. this.finishToken(type, str);
  6940. }
  6941. readRegexp() {
  6942. const start = this.state.pos;
  6943. let escaped, inClass;
  6944. for (;;) {
  6945. if (this.state.pos >= this.length) {
  6946. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  6947. }
  6948. const ch = this.input.charAt(this.state.pos);
  6949. if (lineBreak.test(ch)) {
  6950. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  6951. }
  6952. if (escaped) {
  6953. escaped = false;
  6954. } else {
  6955. if (ch === "[") {
  6956. inClass = true;
  6957. } else if (ch === "]" && inClass) {
  6958. inClass = false;
  6959. } else if (ch === "/" && !inClass) {
  6960. break;
  6961. }
  6962. escaped = ch === "\\";
  6963. }
  6964. ++this.state.pos;
  6965. }
  6966. const content = this.input.slice(start, this.state.pos);
  6967. ++this.state.pos;
  6968. let mods = "";
  6969. while (this.state.pos < this.length) {
  6970. const char = this.input[this.state.pos];
  6971. const charCode = this.input.codePointAt(this.state.pos);
  6972. if (VALID_REGEX_FLAGS.has(char)) {
  6973. if (mods.indexOf(char) > -1) {
  6974. this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
  6975. }
  6976. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6977. this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
  6978. } else {
  6979. break;
  6980. }
  6981. ++this.state.pos;
  6982. mods += char;
  6983. }
  6984. this.finishToken(types.regexp, {
  6985. pattern: content,
  6986. flags: mods
  6987. });
  6988. }
  6989. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6990. const start = this.state.pos;
  6991. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6992. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6993. let invalid = false;
  6994. let total = 0;
  6995. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  6996. const code = this.input.charCodeAt(this.state.pos);
  6997. let val;
  6998. if (code === 95) {
  6999. const prev = this.input.charCodeAt(this.state.pos - 1);
  7000. const next = this.input.charCodeAt(this.state.pos + 1);
  7001. if (allowedSiblings.indexOf(next) === -1) {
  7002. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7003. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  7004. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7005. }
  7006. if (!allowNumSeparator) {
  7007. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  7008. }
  7009. ++this.state.pos;
  7010. continue;
  7011. }
  7012. if (code >= 97) {
  7013. val = code - 97 + 10;
  7014. } else if (code >= 65) {
  7015. val = code - 65 + 10;
  7016. } else if (_isDigit(code)) {
  7017. val = code - 48;
  7018. } else {
  7019. val = Infinity;
  7020. }
  7021. if (val >= radix) {
  7022. if (this.options.errorRecovery && val <= 9) {
  7023. val = 0;
  7024. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  7025. } else if (forceLen) {
  7026. val = 0;
  7027. invalid = true;
  7028. } else {
  7029. break;
  7030. }
  7031. }
  7032. ++this.state.pos;
  7033. total = total * radix + val;
  7034. }
  7035. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  7036. return null;
  7037. }
  7038. return total;
  7039. }
  7040. readRadixNumber(radix) {
  7041. const start = this.state.pos;
  7042. let isBigInt = false;
  7043. this.state.pos += 2;
  7044. const val = this.readInt(radix);
  7045. if (val == null) {
  7046. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  7047. }
  7048. const next = this.input.charCodeAt(this.state.pos);
  7049. if (next === 110) {
  7050. ++this.state.pos;
  7051. isBigInt = true;
  7052. } else if (next === 109) {
  7053. throw this.raise(start, ErrorMessages.InvalidDecimal);
  7054. }
  7055. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7056. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7057. }
  7058. if (isBigInt) {
  7059. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  7060. this.finishToken(types.bigint, str);
  7061. return;
  7062. }
  7063. this.finishToken(types.num, val);
  7064. }
  7065. readNumber(startsWithDot) {
  7066. const start = this.state.pos;
  7067. let isFloat = false;
  7068. let isBigInt = false;
  7069. let isDecimal = false;
  7070. let hasExponent = false;
  7071. let isOctal = false;
  7072. if (!startsWithDot && this.readInt(10) === null) {
  7073. this.raise(start, ErrorMessages.InvalidNumber);
  7074. }
  7075. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  7076. if (hasLeadingZero) {
  7077. const integer = this.input.slice(start, this.state.pos);
  7078. if (this.state.strict) {
  7079. this.raise(start, ErrorMessages.StrictOctalLiteral);
  7080. } else {
  7081. const underscorePos = integer.indexOf("_");
  7082. if (underscorePos > 0) {
  7083. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  7084. }
  7085. }
  7086. isOctal = hasLeadingZero && !/[89]/.test(integer);
  7087. }
  7088. let next = this.input.charCodeAt(this.state.pos);
  7089. if (next === 46 && !isOctal) {
  7090. ++this.state.pos;
  7091. this.readInt(10);
  7092. isFloat = true;
  7093. next = this.input.charCodeAt(this.state.pos);
  7094. }
  7095. if ((next === 69 || next === 101) && !isOctal) {
  7096. next = this.input.charCodeAt(++this.state.pos);
  7097. if (next === 43 || next === 45) {
  7098. ++this.state.pos;
  7099. }
  7100. if (this.readInt(10) === null) {
  7101. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  7102. }
  7103. isFloat = true;
  7104. hasExponent = true;
  7105. next = this.input.charCodeAt(this.state.pos);
  7106. }
  7107. if (next === 110) {
  7108. if (isFloat || hasLeadingZero) {
  7109. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  7110. }
  7111. ++this.state.pos;
  7112. isBigInt = true;
  7113. }
  7114. if (next === 109) {
  7115. this.expectPlugin("decimal", this.state.pos);
  7116. if (hasExponent || hasLeadingZero) {
  7117. this.raise(start, ErrorMessages.InvalidDecimal);
  7118. }
  7119. ++this.state.pos;
  7120. isDecimal = true;
  7121. }
  7122. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7123. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7124. }
  7125. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  7126. if (isBigInt) {
  7127. this.finishToken(types.bigint, str);
  7128. return;
  7129. }
  7130. if (isDecimal) {
  7131. this.finishToken(types.decimal, str);
  7132. return;
  7133. }
  7134. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  7135. this.finishToken(types.num, val);
  7136. }
  7137. readCodePoint(throwOnInvalid) {
  7138. const ch = this.input.charCodeAt(this.state.pos);
  7139. let code;
  7140. if (ch === 123) {
  7141. const codePos = ++this.state.pos;
  7142. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  7143. ++this.state.pos;
  7144. if (code !== null && code > 0x10ffff) {
  7145. if (throwOnInvalid) {
  7146. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  7147. } else {
  7148. return null;
  7149. }
  7150. }
  7151. } else {
  7152. code = this.readHexChar(4, false, throwOnInvalid);
  7153. }
  7154. return code;
  7155. }
  7156. readString(quote) {
  7157. let out = "",
  7158. chunkStart = ++this.state.pos;
  7159. for (;;) {
  7160. if (this.state.pos >= this.length) {
  7161. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7162. }
  7163. const ch = this.input.charCodeAt(this.state.pos);
  7164. if (ch === quote) break;
  7165. if (ch === 92) {
  7166. out += this.input.slice(chunkStart, this.state.pos);
  7167. out += this.readEscapedChar(false);
  7168. chunkStart = this.state.pos;
  7169. } else if (ch === 8232 || ch === 8233) {
  7170. ++this.state.pos;
  7171. ++this.state.curLine;
  7172. this.state.lineStart = this.state.pos;
  7173. } else if (isNewLine(ch)) {
  7174. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7175. } else {
  7176. ++this.state.pos;
  7177. }
  7178. }
  7179. out += this.input.slice(chunkStart, this.state.pos++);
  7180. this.finishToken(types.string, out);
  7181. }
  7182. readTmplToken() {
  7183. let out = "",
  7184. chunkStart = this.state.pos,
  7185. containsInvalid = false;
  7186. for (;;) {
  7187. if (this.state.pos >= this.length) {
  7188. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  7189. }
  7190. const ch = this.input.charCodeAt(this.state.pos);
  7191. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  7192. if (this.state.pos === this.state.start && this.match(types.template)) {
  7193. if (ch === 36) {
  7194. this.state.pos += 2;
  7195. this.finishToken(types.dollarBraceL);
  7196. return;
  7197. } else {
  7198. ++this.state.pos;
  7199. this.finishToken(types.backQuote);
  7200. return;
  7201. }
  7202. }
  7203. out += this.input.slice(chunkStart, this.state.pos);
  7204. this.finishToken(types.template, containsInvalid ? null : out);
  7205. return;
  7206. }
  7207. if (ch === 92) {
  7208. out += this.input.slice(chunkStart, this.state.pos);
  7209. const escaped = this.readEscapedChar(true);
  7210. if (escaped === null) {
  7211. containsInvalid = true;
  7212. } else {
  7213. out += escaped;
  7214. }
  7215. chunkStart = this.state.pos;
  7216. } else if (isNewLine(ch)) {
  7217. out += this.input.slice(chunkStart, this.state.pos);
  7218. ++this.state.pos;
  7219. switch (ch) {
  7220. case 13:
  7221. if (this.input.charCodeAt(this.state.pos) === 10) {
  7222. ++this.state.pos;
  7223. }
  7224. case 10:
  7225. out += "\n";
  7226. break;
  7227. default:
  7228. out += String.fromCharCode(ch);
  7229. break;
  7230. }
  7231. ++this.state.curLine;
  7232. this.state.lineStart = this.state.pos;
  7233. chunkStart = this.state.pos;
  7234. } else {
  7235. ++this.state.pos;
  7236. }
  7237. }
  7238. }
  7239. readEscapedChar(inTemplate) {
  7240. const throwOnInvalid = !inTemplate;
  7241. const ch = this.input.charCodeAt(++this.state.pos);
  7242. ++this.state.pos;
  7243. switch (ch) {
  7244. case 110:
  7245. return "\n";
  7246. case 114:
  7247. return "\r";
  7248. case 120:
  7249. {
  7250. const code = this.readHexChar(2, false, throwOnInvalid);
  7251. return code === null ? null : String.fromCharCode(code);
  7252. }
  7253. case 117:
  7254. {
  7255. const code = this.readCodePoint(throwOnInvalid);
  7256. return code === null ? null : String.fromCodePoint(code);
  7257. }
  7258. case 116:
  7259. return "\t";
  7260. case 98:
  7261. return "\b";
  7262. case 118:
  7263. return "\u000b";
  7264. case 102:
  7265. return "\f";
  7266. case 13:
  7267. if (this.input.charCodeAt(this.state.pos) === 10) {
  7268. ++this.state.pos;
  7269. }
  7270. case 10:
  7271. this.state.lineStart = this.state.pos;
  7272. ++this.state.curLine;
  7273. case 8232:
  7274. case 8233:
  7275. return "";
  7276. case 56:
  7277. case 57:
  7278. if (inTemplate) {
  7279. return null;
  7280. } else if (this.state.strict) {
  7281. this.raise(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  7282. }
  7283. default:
  7284. if (ch >= 48 && ch <= 55) {
  7285. const codePos = this.state.pos - 1;
  7286. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  7287. let octalStr = match[0];
  7288. let octal = parseInt(octalStr, 8);
  7289. if (octal > 255) {
  7290. octalStr = octalStr.slice(0, -1);
  7291. octal = parseInt(octalStr, 8);
  7292. }
  7293. this.state.pos += octalStr.length - 1;
  7294. const next = this.input.charCodeAt(this.state.pos);
  7295. if (octalStr !== "0" || next === 56 || next === 57) {
  7296. if (inTemplate) {
  7297. return null;
  7298. } else if (this.state.strict) {
  7299. this.raise(codePos, ErrorMessages.StrictNumericEscape);
  7300. } else {
  7301. this.state.octalPositions.push(codePos);
  7302. }
  7303. }
  7304. return String.fromCharCode(octal);
  7305. }
  7306. return String.fromCharCode(ch);
  7307. }
  7308. }
  7309. readHexChar(len, forceLen, throwOnInvalid) {
  7310. const codePos = this.state.pos;
  7311. const n = this.readInt(16, len, forceLen, false);
  7312. if (n === null) {
  7313. if (throwOnInvalid) {
  7314. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  7315. } else {
  7316. this.state.pos = codePos - 1;
  7317. }
  7318. }
  7319. return n;
  7320. }
  7321. readWord1() {
  7322. let word = "";
  7323. this.state.containsEsc = false;
  7324. const start = this.state.pos;
  7325. let chunkStart = this.state.pos;
  7326. while (this.state.pos < this.length) {
  7327. const ch = this.input.codePointAt(this.state.pos);
  7328. if (isIdentifierChar(ch)) {
  7329. this.state.pos += ch <= 0xffff ? 1 : 2;
  7330. } else if (this.state.isIterator && ch === 64) {
  7331. ++this.state.pos;
  7332. } else if (ch === 92) {
  7333. this.state.containsEsc = true;
  7334. word += this.input.slice(chunkStart, this.state.pos);
  7335. const escStart = this.state.pos;
  7336. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  7337. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  7338. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  7339. continue;
  7340. }
  7341. ++this.state.pos;
  7342. const esc = this.readCodePoint(true);
  7343. if (esc !== null) {
  7344. if (!identifierCheck(esc)) {
  7345. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  7346. }
  7347. word += String.fromCodePoint(esc);
  7348. }
  7349. chunkStart = this.state.pos;
  7350. } else {
  7351. break;
  7352. }
  7353. }
  7354. return word + this.input.slice(chunkStart, this.state.pos);
  7355. }
  7356. isIterator(word) {
  7357. return word === "@@iterator" || word === "@@asyncIterator";
  7358. }
  7359. readWord() {
  7360. const word = this.readWord1();
  7361. const type = keywords.get(word) || types.name;
  7362. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  7363. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word);
  7364. }
  7365. this.finishToken(type, word);
  7366. }
  7367. checkKeywordEscapes() {
  7368. const kw = this.state.type.keyword;
  7369. if (kw && this.state.containsEsc) {
  7370. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
  7371. }
  7372. }
  7373. braceIsBlock(prevType) {
  7374. const parent = this.curContext();
  7375. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  7376. return true;
  7377. }
  7378. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  7379. return !parent.isExpr;
  7380. }
  7381. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  7382. return this.hasPrecedingLineBreak();
  7383. }
  7384. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  7385. return true;
  7386. }
  7387. if (prevType === types.braceL) {
  7388. return parent === types$1.braceStatement;
  7389. }
  7390. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  7391. return false;
  7392. }
  7393. if (prevType === types.relational) {
  7394. return true;
  7395. }
  7396. return !this.state.exprAllowed;
  7397. }
  7398. updateContext(prevType) {
  7399. const type = this.state.type;
  7400. let update;
  7401. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  7402. this.state.exprAllowed = false;
  7403. } else if (update = type.updateContext) {
  7404. update.call(this, prevType);
  7405. } else {
  7406. this.state.exprAllowed = type.beforeExpr;
  7407. }
  7408. }
  7409. }
  7410. class UtilParser extends Tokenizer {
  7411. addExtra(node, key, val) {
  7412. if (!node) return;
  7413. const extra = node.extra = node.extra || {};
  7414. extra[key] = val;
  7415. }
  7416. isRelational(op) {
  7417. return this.match(types.relational) && this.state.value === op;
  7418. }
  7419. expectRelational(op) {
  7420. if (this.isRelational(op)) {
  7421. this.next();
  7422. } else {
  7423. this.unexpected(null, types.relational);
  7424. }
  7425. }
  7426. isContextual(name) {
  7427. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  7428. }
  7429. isUnparsedContextual(nameStart, name) {
  7430. const nameEnd = nameStart + name.length;
  7431. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  7432. }
  7433. isLookaheadContextual(name) {
  7434. const next = this.nextTokenStart();
  7435. return this.isUnparsedContextual(next, name);
  7436. }
  7437. eatContextual(name) {
  7438. return this.isContextual(name) && this.eat(types.name);
  7439. }
  7440. expectContextual(name, message) {
  7441. if (!this.eatContextual(name)) this.unexpected(null, message);
  7442. }
  7443. canInsertSemicolon() {
  7444. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  7445. }
  7446. hasPrecedingLineBreak() {
  7447. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7448. }
  7449. isLineTerminator() {
  7450. return this.eat(types.semi) || this.canInsertSemicolon();
  7451. }
  7452. semicolon() {
  7453. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  7454. }
  7455. expect(type, pos) {
  7456. this.eat(type) || this.unexpected(pos, type);
  7457. }
  7458. assertNoSpace(message = "Unexpected space.") {
  7459. if (this.state.start > this.state.lastTokEnd) {
  7460. this.raise(this.state.lastTokEnd, message);
  7461. }
  7462. }
  7463. unexpected(pos, messageOrType = "Unexpected token") {
  7464. if (typeof messageOrType !== "string") {
  7465. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  7466. }
  7467. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  7468. }
  7469. expectPlugin(name, pos) {
  7470. if (!this.hasPlugin(name)) {
  7471. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7472. missingPlugin: [name]
  7473. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  7474. }
  7475. return true;
  7476. }
  7477. expectOnePlugin(names, pos) {
  7478. if (!names.some(n => this.hasPlugin(n))) {
  7479. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7480. missingPlugin: names
  7481. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  7482. }
  7483. }
  7484. tryParse(fn, oldState = this.state.clone()) {
  7485. const abortSignal = {
  7486. node: null
  7487. };
  7488. try {
  7489. const node = fn((node = null) => {
  7490. abortSignal.node = node;
  7491. throw abortSignal;
  7492. });
  7493. if (this.state.errors.length > oldState.errors.length) {
  7494. const failState = this.state;
  7495. this.state = oldState;
  7496. return {
  7497. node,
  7498. error: failState.errors[oldState.errors.length],
  7499. thrown: false,
  7500. aborted: false,
  7501. failState
  7502. };
  7503. }
  7504. return {
  7505. node,
  7506. error: null,
  7507. thrown: false,
  7508. aborted: false,
  7509. failState: null
  7510. };
  7511. } catch (error) {
  7512. const failState = this.state;
  7513. this.state = oldState;
  7514. if (error instanceof SyntaxError) {
  7515. return {
  7516. node: null,
  7517. error,
  7518. thrown: true,
  7519. aborted: false,
  7520. failState
  7521. };
  7522. }
  7523. if (error === abortSignal) {
  7524. return {
  7525. node: abortSignal.node,
  7526. error: null,
  7527. thrown: false,
  7528. aborted: true,
  7529. failState
  7530. };
  7531. }
  7532. throw error;
  7533. }
  7534. }
  7535. checkExpressionErrors(refExpressionErrors, andThrow) {
  7536. if (!refExpressionErrors) return false;
  7537. const {
  7538. shorthandAssign,
  7539. doubleProto
  7540. } = refExpressionErrors;
  7541. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  7542. if (shorthandAssign >= 0) {
  7543. this.unexpected(shorthandAssign);
  7544. }
  7545. if (doubleProto >= 0) {
  7546. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  7547. }
  7548. }
  7549. isLiteralPropertyName() {
  7550. 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);
  7551. }
  7552. }
  7553. class ExpressionErrors {
  7554. constructor() {
  7555. this.shorthandAssign = -1;
  7556. this.doubleProto = -1;
  7557. }
  7558. }
  7559. class Node {
  7560. constructor(parser, pos, loc) {
  7561. this.type = void 0;
  7562. this.start = void 0;
  7563. this.end = void 0;
  7564. this.loc = void 0;
  7565. this.range = void 0;
  7566. this.leadingComments = void 0;
  7567. this.trailingComments = void 0;
  7568. this.innerComments = void 0;
  7569. this.extra = void 0;
  7570. this.type = "";
  7571. this.start = pos;
  7572. this.end = 0;
  7573. this.loc = new SourceLocation(loc);
  7574. if (parser == null ? void 0 : parser.options.ranges) this.range = [pos, 0];
  7575. if (parser == null ? void 0 : parser.filename) this.loc.filename = parser.filename;
  7576. }
  7577. __clone() {
  7578. const newNode = new Node();
  7579. const keys = Object.keys(this);
  7580. for (let i = 0, length = keys.length; i < length; i++) {
  7581. const key = keys[i];
  7582. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  7583. newNode[key] = this[key];
  7584. }
  7585. }
  7586. return newNode;
  7587. }
  7588. }
  7589. class NodeUtils extends UtilParser {
  7590. startNode() {
  7591. return new Node(this, this.state.start, this.state.startLoc);
  7592. }
  7593. startNodeAt(pos, loc) {
  7594. return new Node(this, pos, loc);
  7595. }
  7596. startNodeAtNode(type) {
  7597. return this.startNodeAt(type.start, type.loc.start);
  7598. }
  7599. finishNode(node, type) {
  7600. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  7601. }
  7602. finishNodeAt(node, type, pos, loc) {
  7603. node.type = type;
  7604. node.end = pos;
  7605. node.loc.end = loc;
  7606. if (this.options.ranges) node.range[1] = pos;
  7607. this.processComment(node);
  7608. return node;
  7609. }
  7610. resetStartLocation(node, start, startLoc) {
  7611. node.start = start;
  7612. node.loc.start = startLoc;
  7613. if (this.options.ranges) node.range[0] = start;
  7614. }
  7615. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  7616. node.end = end;
  7617. node.loc.end = endLoc;
  7618. if (this.options.ranges) node.range[1] = end;
  7619. }
  7620. resetStartLocationFromNode(node, locationNode) {
  7621. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  7622. }
  7623. }
  7624. const unwrapParenthesizedExpression = node => {
  7625. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7626. };
  7627. class LValParser extends NodeUtils {
  7628. toAssignable(node) {
  7629. var _node$extra, _node$extra3;
  7630. let parenthesized = undefined;
  7631. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  7632. parenthesized = unwrapParenthesizedExpression(node);
  7633. if (parenthesized.type !== "Identifier" && parenthesized.type !== "MemberExpression") {
  7634. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  7635. }
  7636. }
  7637. switch (node.type) {
  7638. case "Identifier":
  7639. case "ObjectPattern":
  7640. case "ArrayPattern":
  7641. case "AssignmentPattern":
  7642. break;
  7643. case "ObjectExpression":
  7644. node.type = "ObjectPattern";
  7645. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7646. var _node$extra2;
  7647. const prop = node.properties[i];
  7648. const isLast = i === last;
  7649. this.toAssignableObjectExpressionProp(prop, isLast);
  7650. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  7651. this.raiseRestNotLast(node.extra.trailingComma);
  7652. }
  7653. }
  7654. break;
  7655. case "ObjectProperty":
  7656. this.toAssignable(node.value);
  7657. break;
  7658. case "SpreadElement":
  7659. {
  7660. this.checkToRestConversion(node);
  7661. node.type = "RestElement";
  7662. const arg = node.argument;
  7663. this.toAssignable(arg);
  7664. break;
  7665. }
  7666. case "ArrayExpression":
  7667. node.type = "ArrayPattern";
  7668. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma);
  7669. break;
  7670. case "AssignmentExpression":
  7671. if (node.operator !== "=") {
  7672. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  7673. }
  7674. node.type = "AssignmentPattern";
  7675. delete node.operator;
  7676. this.toAssignable(node.left);
  7677. break;
  7678. case "ParenthesizedExpression":
  7679. this.toAssignable(parenthesized);
  7680. break;
  7681. }
  7682. return node;
  7683. }
  7684. toAssignableObjectExpressionProp(prop, isLast) {
  7685. if (prop.type === "ObjectMethod") {
  7686. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  7687. this.raise(prop.key.start, error);
  7688. } else if (prop.type === "SpreadElement" && !isLast) {
  7689. this.raiseRestNotLast(prop.start);
  7690. } else {
  7691. this.toAssignable(prop);
  7692. }
  7693. }
  7694. toAssignableList(exprList, trailingCommaPos) {
  7695. let end = exprList.length;
  7696. if (end) {
  7697. const last = exprList[end - 1];
  7698. if ((last == null ? void 0 : last.type) === "RestElement") {
  7699. --end;
  7700. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  7701. last.type = "RestElement";
  7702. const arg = last.argument;
  7703. this.toAssignable(arg);
  7704. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7705. this.unexpected(arg.start);
  7706. }
  7707. if (trailingCommaPos) {
  7708. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7709. }
  7710. --end;
  7711. }
  7712. }
  7713. for (let i = 0; i < end; i++) {
  7714. const elt = exprList[i];
  7715. if (elt) {
  7716. this.toAssignable(elt);
  7717. if (elt.type === "RestElement") {
  7718. this.raiseRestNotLast(elt.start);
  7719. }
  7720. }
  7721. }
  7722. return exprList;
  7723. }
  7724. toReferencedList(exprList, isParenthesizedExpr) {
  7725. return exprList;
  7726. }
  7727. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7728. this.toReferencedList(exprList, isParenthesizedExpr);
  7729. for (let _i = 0; _i < exprList.length; _i++) {
  7730. const expr = exprList[_i];
  7731. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  7732. this.toReferencedListDeep(expr.elements);
  7733. }
  7734. }
  7735. }
  7736. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  7737. const node = this.startNode();
  7738. this.next();
  7739. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  7740. return this.finishNode(node, "SpreadElement");
  7741. }
  7742. parseRestBinding() {
  7743. const node = this.startNode();
  7744. this.next();
  7745. node.argument = this.parseBindingAtom();
  7746. return this.finishNode(node, "RestElement");
  7747. }
  7748. parseBindingAtom() {
  7749. switch (this.state.type) {
  7750. case types.bracketL:
  7751. {
  7752. const node = this.startNode();
  7753. this.next();
  7754. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7755. return this.finishNode(node, "ArrayPattern");
  7756. }
  7757. case types.braceL:
  7758. return this.parseObjectLike(types.braceR, true);
  7759. }
  7760. return this.parseIdentifier();
  7761. }
  7762. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7763. const elts = [];
  7764. let first = true;
  7765. while (!this.eat(close)) {
  7766. if (first) {
  7767. first = false;
  7768. } else {
  7769. this.expect(types.comma);
  7770. }
  7771. if (allowEmpty && this.match(types.comma)) {
  7772. elts.push(null);
  7773. } else if (this.eat(close)) {
  7774. break;
  7775. } else if (this.match(types.ellipsis)) {
  7776. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7777. this.checkCommaAfterRest(closeCharCode);
  7778. this.expect(close);
  7779. break;
  7780. } else {
  7781. const decorators = [];
  7782. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7783. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  7784. }
  7785. while (this.match(types.at)) {
  7786. decorators.push(this.parseDecorator());
  7787. }
  7788. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7789. }
  7790. }
  7791. return elts;
  7792. }
  7793. parseAssignableListItem(allowModifiers, decorators) {
  7794. const left = this.parseMaybeDefault();
  7795. this.parseAssignableListItemTypes(left);
  7796. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7797. if (decorators.length) {
  7798. left.decorators = decorators;
  7799. }
  7800. return elt;
  7801. }
  7802. parseAssignableListItemTypes(param) {
  7803. return param;
  7804. }
  7805. parseMaybeDefault(startPos, startLoc, left) {
  7806. var _startLoc, _startPos, _left;
  7807. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  7808. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  7809. left = (_left = left) != null ? _left : this.parseBindingAtom();
  7810. if (!this.eat(types.eq)) return left;
  7811. const node = this.startNodeAt(startPos, startLoc);
  7812. node.left = left;
  7813. node.right = this.parseMaybeAssignAllowIn();
  7814. return this.finishNode(node, "AssignmentPattern");
  7815. }
  7816. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding, strictModeChanged = false) {
  7817. switch (expr.type) {
  7818. case "Identifier":
  7819. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) {
  7820. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, expr.name);
  7821. }
  7822. if (checkClashes) {
  7823. const key = `_${expr.name}`;
  7824. if (checkClashes[key]) {
  7825. this.raise(expr.start, ErrorMessages.ParamDupe);
  7826. } else {
  7827. checkClashes[key] = true;
  7828. }
  7829. }
  7830. if (disallowLetBinding && expr.name === "let") {
  7831. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  7832. }
  7833. if (!(bindingType & BIND_NONE)) {
  7834. this.scope.declareName(expr.name, bindingType, expr.start);
  7835. }
  7836. break;
  7837. case "MemberExpression":
  7838. if (bindingType !== BIND_NONE) {
  7839. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  7840. }
  7841. break;
  7842. case "ObjectPattern":
  7843. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7844. let prop = _expr$properties[_i2];
  7845. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  7846. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  7847. }
  7848. break;
  7849. case "ArrayPattern":
  7850. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7851. const elem = _expr$elements[_i3];
  7852. if (elem) {
  7853. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding);
  7854. }
  7855. }
  7856. break;
  7857. case "AssignmentPattern":
  7858. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  7859. break;
  7860. case "RestElement":
  7861. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  7862. break;
  7863. case "ParenthesizedExpression":
  7864. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  7865. break;
  7866. default:
  7867. {
  7868. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  7869. }
  7870. }
  7871. }
  7872. checkToRestConversion(node) {
  7873. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7874. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  7875. }
  7876. }
  7877. checkCommaAfterRest(close) {
  7878. if (this.match(types.comma)) {
  7879. if (this.lookaheadCharCode() === close) {
  7880. this.raiseTrailingCommaAfterRest(this.state.start);
  7881. } else {
  7882. this.raiseRestNotLast(this.state.start);
  7883. }
  7884. }
  7885. }
  7886. raiseRestNotLast(pos) {
  7887. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  7888. }
  7889. raiseTrailingCommaAfterRest(pos) {
  7890. this.raise(pos, ErrorMessages.RestTrailingComma);
  7891. }
  7892. }
  7893. const kExpression = 0,
  7894. kMaybeArrowParameterDeclaration = 1,
  7895. kMaybeAsyncArrowParameterDeclaration = 2,
  7896. kParameterDeclaration = 3;
  7897. class ExpressionScope {
  7898. constructor(type = kExpression) {
  7899. this.type = void 0;
  7900. this.type = type;
  7901. }
  7902. canBeArrowParameterDeclaration() {
  7903. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  7904. }
  7905. isCertainlyParameterDeclaration() {
  7906. return this.type === kParameterDeclaration;
  7907. }
  7908. }
  7909. class ArrowHeadParsingScope extends ExpressionScope {
  7910. constructor(type) {
  7911. super(type);
  7912. this.errors = new Map();
  7913. }
  7914. recordDeclarationError(pos, message) {
  7915. this.errors.set(pos, message);
  7916. }
  7917. clearDeclarationError(pos) {
  7918. this.errors.delete(pos);
  7919. }
  7920. iterateErrors(iterator) {
  7921. this.errors.forEach(iterator);
  7922. }
  7923. }
  7924. class ExpressionScopeHandler {
  7925. constructor(raise) {
  7926. this.stack = [new ExpressionScope()];
  7927. this.raise = raise;
  7928. }
  7929. enter(scope) {
  7930. this.stack.push(scope);
  7931. }
  7932. exit() {
  7933. this.stack.pop();
  7934. }
  7935. recordParameterInitializerError(pos, message) {
  7936. const {
  7937. stack
  7938. } = this;
  7939. let i = stack.length - 1;
  7940. let scope = stack[i];
  7941. while (!scope.isCertainlyParameterDeclaration()) {
  7942. if (scope.canBeArrowParameterDeclaration()) {
  7943. scope.recordDeclarationError(pos, message);
  7944. } else {
  7945. return;
  7946. }
  7947. scope = stack[--i];
  7948. }
  7949. this.raise(pos, message);
  7950. }
  7951. recordAsyncArrowParametersError(pos, message) {
  7952. const {
  7953. stack
  7954. } = this;
  7955. let i = stack.length - 1;
  7956. let scope = stack[i];
  7957. while (scope.canBeArrowParameterDeclaration()) {
  7958. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  7959. scope.recordDeclarationError(pos, message);
  7960. }
  7961. scope = stack[--i];
  7962. }
  7963. }
  7964. validateAsPattern() {
  7965. const {
  7966. stack
  7967. } = this;
  7968. const currentScope = stack[stack.length - 1];
  7969. if (!currentScope.canBeArrowParameterDeclaration()) return;
  7970. currentScope.iterateErrors((message, pos) => {
  7971. this.raise(pos, message);
  7972. let i = stack.length - 2;
  7973. let scope = stack[i];
  7974. while (scope.canBeArrowParameterDeclaration()) {
  7975. scope.clearDeclarationError(pos);
  7976. scope = stack[--i];
  7977. }
  7978. });
  7979. }
  7980. }
  7981. function newParameterDeclarationScope() {
  7982. return new ExpressionScope(kParameterDeclaration);
  7983. }
  7984. function newArrowHeadScope() {
  7985. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  7986. }
  7987. function newAsyncArrowScope() {
  7988. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  7989. }
  7990. function newExpressionScope() {
  7991. return new ExpressionScope();
  7992. }
  7993. class ExpressionParser extends LValParser {
  7994. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  7995. if (prop.type === "SpreadElement" || prop.type === "ObjectMethod" || prop.computed || prop.shorthand) {
  7996. return;
  7997. }
  7998. const key = prop.key;
  7999. const name = key.type === "Identifier" ? key.name : key.value;
  8000. if (name === "__proto__") {
  8001. if (isRecord) {
  8002. this.raise(key.start, ErrorMessages.RecordNoProto);
  8003. return;
  8004. }
  8005. if (protoRef.used) {
  8006. if (refExpressionErrors) {
  8007. if (refExpressionErrors.doubleProto === -1) {
  8008. refExpressionErrors.doubleProto = key.start;
  8009. }
  8010. } else {
  8011. this.raise(key.start, ErrorMessages.DuplicateProto);
  8012. }
  8013. }
  8014. protoRef.used = true;
  8015. }
  8016. }
  8017. shouldExitDescending(expr, potentialArrowAt) {
  8018. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  8019. }
  8020. getExpression() {
  8021. let paramFlags = PARAM;
  8022. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  8023. paramFlags |= PARAM_AWAIT;
  8024. }
  8025. this.scope.enter(SCOPE_PROGRAM);
  8026. this.prodParam.enter(paramFlags);
  8027. this.nextToken();
  8028. const expr = this.parseExpression();
  8029. if (!this.match(types.eof)) {
  8030. this.unexpected();
  8031. }
  8032. expr.comments = this.state.comments;
  8033. expr.errors = this.state.errors;
  8034. return expr;
  8035. }
  8036. parseExpression(disallowIn, refExpressionErrors) {
  8037. if (disallowIn) {
  8038. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8039. }
  8040. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8041. }
  8042. parseExpressionBase(refExpressionErrors) {
  8043. const startPos = this.state.start;
  8044. const startLoc = this.state.startLoc;
  8045. const expr = this.parseMaybeAssign(refExpressionErrors);
  8046. if (this.match(types.comma)) {
  8047. const node = this.startNodeAt(startPos, startLoc);
  8048. node.expressions = [expr];
  8049. while (this.eat(types.comma)) {
  8050. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  8051. }
  8052. this.toReferencedList(node.expressions);
  8053. return this.finishNode(node, "SequenceExpression");
  8054. }
  8055. return expr;
  8056. }
  8057. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8058. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8059. }
  8060. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8061. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8062. }
  8063. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8064. const startPos = this.state.start;
  8065. const startLoc = this.state.startLoc;
  8066. if (this.isContextual("yield")) {
  8067. if (this.prodParam.hasYield) {
  8068. this.state.exprAllowed = true;
  8069. let left = this.parseYield();
  8070. if (afterLeftParse) {
  8071. left = afterLeftParse.call(this, left, startPos, startLoc);
  8072. }
  8073. return left;
  8074. }
  8075. }
  8076. let ownExpressionErrors;
  8077. if (refExpressionErrors) {
  8078. ownExpressionErrors = false;
  8079. } else {
  8080. refExpressionErrors = new ExpressionErrors();
  8081. ownExpressionErrors = true;
  8082. }
  8083. if (this.match(types.parenL) || this.match(types.name)) {
  8084. this.state.potentialArrowAt = this.state.start;
  8085. }
  8086. let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
  8087. if (afterLeftParse) {
  8088. left = afterLeftParse.call(this, left, startPos, startLoc);
  8089. }
  8090. if (this.state.type.isAssign) {
  8091. const node = this.startNodeAt(startPos, startLoc);
  8092. const operator = this.state.value;
  8093. node.operator = operator;
  8094. if (this.match(types.eq)) {
  8095. node.left = this.toAssignable(left);
  8096. refExpressionErrors.doubleProto = -1;
  8097. } else {
  8098. node.left = left;
  8099. }
  8100. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  8101. refExpressionErrors.shorthandAssign = -1;
  8102. }
  8103. this.checkLVal(left, undefined, undefined, "assignment expression");
  8104. this.next();
  8105. node.right = this.parseMaybeAssign();
  8106. return this.finishNode(node, "AssignmentExpression");
  8107. } else if (ownExpressionErrors) {
  8108. this.checkExpressionErrors(refExpressionErrors, true);
  8109. }
  8110. return left;
  8111. }
  8112. parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
  8113. const startPos = this.state.start;
  8114. const startLoc = this.state.startLoc;
  8115. const potentialArrowAt = this.state.potentialArrowAt;
  8116. const expr = this.parseExprOps(refExpressionErrors);
  8117. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8118. return expr;
  8119. }
  8120. return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  8121. }
  8122. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  8123. if (this.eat(types.question)) {
  8124. const node = this.startNodeAt(startPos, startLoc);
  8125. node.test = expr;
  8126. node.consequent = this.parseMaybeAssignAllowIn();
  8127. this.expect(types.colon);
  8128. node.alternate = this.parseMaybeAssign();
  8129. return this.finishNode(node, "ConditionalExpression");
  8130. }
  8131. return expr;
  8132. }
  8133. parseExprOps(refExpressionErrors) {
  8134. const startPos = this.state.start;
  8135. const startLoc = this.state.startLoc;
  8136. const potentialArrowAt = this.state.potentialArrowAt;
  8137. const expr = this.parseMaybeUnary(refExpressionErrors);
  8138. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8139. return expr;
  8140. }
  8141. return this.parseExprOp(expr, startPos, startLoc, -1);
  8142. }
  8143. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8144. let prec = this.state.type.binop;
  8145. if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
  8146. if (prec > minPrec) {
  8147. const op = this.state.type;
  8148. if (op === types.pipeline) {
  8149. this.expectPlugin("pipelineOperator");
  8150. if (this.state.inFSharpPipelineDirectBody) {
  8151. return left;
  8152. }
  8153. this.state.inPipeline = true;
  8154. this.checkPipelineAtInfixOperator(left, leftStartPos);
  8155. }
  8156. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8157. node.left = left;
  8158. node.operator = this.state.value;
  8159. if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  8160. this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  8161. }
  8162. const logical = op === types.logicalOR || op === types.logicalAND;
  8163. const coalesce = op === types.nullishCoalescing;
  8164. if (coalesce) {
  8165. prec = types.logicalAND.binop;
  8166. }
  8167. this.next();
  8168. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  8169. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  8170. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  8171. }
  8172. }
  8173. node.right = this.parseExprOpRightExpr(op, prec);
  8174. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  8175. const nextOp = this.state.type;
  8176. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  8177. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  8178. }
  8179. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8180. }
  8181. }
  8182. return left;
  8183. }
  8184. parseExprOpRightExpr(op, prec) {
  8185. const startPos = this.state.start;
  8186. const startLoc = this.state.startLoc;
  8187. switch (op) {
  8188. case types.pipeline:
  8189. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  8190. case "smart":
  8191. return this.withTopicPermittingContext(() => {
  8192. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  8193. });
  8194. case "fsharp":
  8195. return this.withSoloAwaitPermittingContext(() => {
  8196. return this.parseFSharpPipelineBody(prec);
  8197. });
  8198. }
  8199. default:
  8200. return this.parseExprOpBaseRightExpr(op, prec);
  8201. }
  8202. }
  8203. parseExprOpBaseRightExpr(op, prec) {
  8204. const startPos = this.state.start;
  8205. const startLoc = this.state.startLoc;
  8206. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
  8207. }
  8208. parseMaybeUnary(refExpressionErrors) {
  8209. if (this.isContextual("await") && this.isAwaitAllowed()) {
  8210. return this.parseAwait();
  8211. }
  8212. const update = this.match(types.incDec);
  8213. const node = this.startNode();
  8214. if (this.state.type.prefix) {
  8215. node.operator = this.state.value;
  8216. node.prefix = true;
  8217. if (this.match(types._throw)) {
  8218. this.expectPlugin("throwExpressions");
  8219. }
  8220. const isDelete = this.match(types._delete);
  8221. this.next();
  8222. node.argument = this.parseMaybeUnary();
  8223. this.checkExpressionErrors(refExpressionErrors, true);
  8224. if (this.state.strict && isDelete) {
  8225. const arg = node.argument;
  8226. if (arg.type === "Identifier") {
  8227. this.raise(node.start, ErrorMessages.StrictDelete);
  8228. } else if ((arg.type === "MemberExpression" || arg.type === "OptionalMemberExpression") && arg.property.type === "PrivateName") {
  8229. this.raise(node.start, ErrorMessages.DeletePrivateField);
  8230. }
  8231. }
  8232. if (!update) {
  8233. return this.finishNode(node, "UnaryExpression");
  8234. }
  8235. }
  8236. return this.parseUpdate(node, update, refExpressionErrors);
  8237. }
  8238. parseUpdate(node, update, refExpressionErrors) {
  8239. if (update) {
  8240. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  8241. return this.finishNode(node, "UpdateExpression");
  8242. }
  8243. const startPos = this.state.start;
  8244. const startLoc = this.state.startLoc;
  8245. let expr = this.parseExprSubscripts(refExpressionErrors);
  8246. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  8247. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  8248. const node = this.startNodeAt(startPos, startLoc);
  8249. node.operator = this.state.value;
  8250. node.prefix = false;
  8251. node.argument = expr;
  8252. this.checkLVal(expr, undefined, undefined, "postfix operation");
  8253. this.next();
  8254. expr = this.finishNode(node, "UpdateExpression");
  8255. }
  8256. return expr;
  8257. }
  8258. parseExprSubscripts(refExpressionErrors) {
  8259. const startPos = this.state.start;
  8260. const startLoc = this.state.startLoc;
  8261. const potentialArrowAt = this.state.potentialArrowAt;
  8262. const expr = this.parseExprAtom(refExpressionErrors);
  8263. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8264. return expr;
  8265. }
  8266. return this.parseSubscripts(expr, startPos, startLoc);
  8267. }
  8268. parseSubscripts(base, startPos, startLoc, noCalls) {
  8269. const state = {
  8270. optionalChainMember: false,
  8271. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  8272. stop: false
  8273. };
  8274. do {
  8275. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  8276. state.maybeAsyncArrow = false;
  8277. } while (!state.stop);
  8278. return base;
  8279. }
  8280. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8281. if (!noCalls && this.eat(types.doubleColon)) {
  8282. return this.parseBind(base, startPos, startLoc, noCalls, state);
  8283. } else if (this.match(types.backQuote)) {
  8284. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8285. }
  8286. let optional = false;
  8287. if (this.match(types.questionDot)) {
  8288. state.optionalChainMember = optional = true;
  8289. if (noCalls && this.lookaheadCharCode() === 40) {
  8290. state.stop = true;
  8291. return base;
  8292. }
  8293. this.next();
  8294. }
  8295. if (!noCalls && this.match(types.parenL)) {
  8296. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  8297. } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
  8298. return this.parseMember(base, startPos, startLoc, state, optional);
  8299. } else {
  8300. state.stop = true;
  8301. return base;
  8302. }
  8303. }
  8304. parseMember(base, startPos, startLoc, state, optional) {
  8305. const node = this.startNodeAt(startPos, startLoc);
  8306. const computed = this.eat(types.bracketL);
  8307. node.object = base;
  8308. node.computed = computed;
  8309. const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
  8310. if (property.type === "PrivateName") {
  8311. if (node.object.type === "Super") {
  8312. this.raise(startPos, ErrorMessages.SuperPrivateField);
  8313. }
  8314. this.classScope.usePrivateName(property.id.name, property.start);
  8315. }
  8316. node.property = property;
  8317. if (computed) {
  8318. this.expect(types.bracketR);
  8319. }
  8320. if (state.optionalChainMember) {
  8321. node.optional = optional;
  8322. return this.finishNode(node, "OptionalMemberExpression");
  8323. } else {
  8324. return this.finishNode(node, "MemberExpression");
  8325. }
  8326. }
  8327. parseBind(base, startPos, startLoc, noCalls, state) {
  8328. const node = this.startNodeAt(startPos, startLoc);
  8329. node.object = base;
  8330. node.callee = this.parseNoCallExpr();
  8331. state.stop = true;
  8332. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  8333. }
  8334. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  8335. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8336. this.state.maybeInArrowParameters = true;
  8337. this.next();
  8338. let node = this.startNodeAt(startPos, startLoc);
  8339. node.callee = base;
  8340. if (state.maybeAsyncArrow) {
  8341. this.expressionScope.enter(newAsyncArrowScope());
  8342. }
  8343. if (state.optionalChainMember) {
  8344. node.optional = optional;
  8345. }
  8346. if (optional) {
  8347. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8348. } else {
  8349. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  8350. }
  8351. this.finishCallExpression(node, state.optionalChainMember);
  8352. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  8353. state.stop = true;
  8354. this.expressionScope.validateAsPattern();
  8355. this.expressionScope.exit();
  8356. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  8357. } else {
  8358. if (state.maybeAsyncArrow) {
  8359. this.expressionScope.exit();
  8360. }
  8361. this.toReferencedArguments(node);
  8362. }
  8363. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8364. return node;
  8365. }
  8366. toReferencedArguments(node, isParenthesizedExpr) {
  8367. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  8368. }
  8369. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  8370. const node = this.startNodeAt(startPos, startLoc);
  8371. node.tag = base;
  8372. node.quasi = this.parseTemplate(true);
  8373. if (state.optionalChainMember) {
  8374. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  8375. }
  8376. return this.finishNode(node, "TaggedTemplateExpression");
  8377. }
  8378. atPossibleAsyncArrow(base) {
  8379. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  8380. }
  8381. finishCallExpression(node, optional) {
  8382. if (node.callee.type === "Import") {
  8383. if (node.arguments.length === 2) {
  8384. if (!this.hasPlugin("moduleAttributes")) {
  8385. this.expectPlugin("importAssertions");
  8386. }
  8387. }
  8388. if (node.arguments.length === 0 || node.arguments.length > 2) {
  8389. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  8390. } else {
  8391. for (let _i = 0, _node$arguments = node.arguments; _i < _node$arguments.length; _i++) {
  8392. const arg = _node$arguments[_i];
  8393. if (arg.type === "SpreadElement") {
  8394. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  8395. }
  8396. }
  8397. }
  8398. }
  8399. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  8400. }
  8401. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  8402. const elts = [];
  8403. let innerParenStart;
  8404. let first = true;
  8405. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8406. this.state.inFSharpPipelineDirectBody = false;
  8407. while (!this.eat(close)) {
  8408. if (first) {
  8409. first = false;
  8410. } else {
  8411. this.expect(types.comma);
  8412. if (this.match(close)) {
  8413. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  8414. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  8415. }
  8416. if (nodeForExtra) {
  8417. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8418. }
  8419. this.next();
  8420. break;
  8421. }
  8422. }
  8423. if (this.match(types.parenL) && !innerParenStart) {
  8424. innerParenStart = this.state.start;
  8425. }
  8426. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8427. start: 0
  8428. } : undefined, allowPlaceholder));
  8429. }
  8430. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  8431. this.unexpected();
  8432. }
  8433. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8434. return elts;
  8435. }
  8436. shouldParseAsyncArrow() {
  8437. return this.match(types.arrow) && !this.canInsertSemicolon();
  8438. }
  8439. parseAsyncArrowFromCallExpression(node, call) {
  8440. var _call$extra;
  8441. this.expect(types.arrow);
  8442. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8443. return node;
  8444. }
  8445. parseNoCallExpr() {
  8446. const startPos = this.state.start;
  8447. const startLoc = this.state.startLoc;
  8448. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8449. }
  8450. parseExprAtom(refExpressionErrors) {
  8451. if (this.state.type === types.slash) this.readRegexp();
  8452. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8453. let node;
  8454. switch (this.state.type) {
  8455. case types._super:
  8456. return this.parseSuper();
  8457. case types._import:
  8458. node = this.startNode();
  8459. this.next();
  8460. if (this.match(types.dot)) {
  8461. return this.parseImportMetaProperty(node);
  8462. }
  8463. if (!this.match(types.parenL)) {
  8464. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  8465. }
  8466. return this.finishNode(node, "Import");
  8467. case types._this:
  8468. node = this.startNode();
  8469. this.next();
  8470. return this.finishNode(node, "ThisExpression");
  8471. case types.name:
  8472. {
  8473. const containsEsc = this.state.containsEsc;
  8474. const id = this.parseIdentifier();
  8475. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  8476. if (this.match(types._function)) {
  8477. const last = this.state.context.length - 1;
  8478. if (this.state.context[last] !== types$1.functionStatement) {
  8479. throw new Error("Internal error");
  8480. }
  8481. this.state.context[last] = types$1.functionExpression;
  8482. this.next();
  8483. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  8484. } else if (this.match(types.name)) {
  8485. return this.parseAsyncArrowUnaryFunction(id);
  8486. }
  8487. }
  8488. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8489. this.next();
  8490. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  8491. }
  8492. return id;
  8493. }
  8494. case types._do:
  8495. {
  8496. return this.parseDo();
  8497. }
  8498. case types.regexp:
  8499. {
  8500. const value = this.state.value;
  8501. node = this.parseLiteral(value.value, "RegExpLiteral");
  8502. node.pattern = value.pattern;
  8503. node.flags = value.flags;
  8504. return node;
  8505. }
  8506. case types.num:
  8507. return this.parseLiteral(this.state.value, "NumericLiteral");
  8508. case types.bigint:
  8509. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8510. case types.decimal:
  8511. return this.parseLiteral(this.state.value, "DecimalLiteral");
  8512. case types.string:
  8513. return this.parseLiteral(this.state.value, "StringLiteral");
  8514. case types._null:
  8515. node = this.startNode();
  8516. this.next();
  8517. return this.finishNode(node, "NullLiteral");
  8518. case types._true:
  8519. case types._false:
  8520. return this.parseBooleanLiteral();
  8521. case types.parenL:
  8522. return this.parseParenAndDistinguishExpression(canBeArrow);
  8523. case types.bracketBarL:
  8524. case types.bracketHashL:
  8525. {
  8526. return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
  8527. }
  8528. case types.bracketL:
  8529. {
  8530. return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
  8531. }
  8532. case types.braceBarL:
  8533. case types.braceHashL:
  8534. {
  8535. return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
  8536. }
  8537. case types.braceL:
  8538. {
  8539. return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
  8540. }
  8541. case types._function:
  8542. return this.parseFunctionOrFunctionSent();
  8543. case types.at:
  8544. this.parseDecorators();
  8545. case types._class:
  8546. node = this.startNode();
  8547. this.takeDecorators(node);
  8548. return this.parseClass(node, false);
  8549. case types._new:
  8550. return this.parseNewOrNewTarget();
  8551. case types.backQuote:
  8552. return this.parseTemplate(false);
  8553. case types.doubleColon:
  8554. {
  8555. node = this.startNode();
  8556. this.next();
  8557. node.object = null;
  8558. const callee = node.callee = this.parseNoCallExpr();
  8559. if (callee.type === "MemberExpression") {
  8560. return this.finishNode(node, "BindExpression");
  8561. } else {
  8562. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  8563. }
  8564. }
  8565. case types.hash:
  8566. {
  8567. if (this.state.inPipeline) {
  8568. node = this.startNode();
  8569. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  8570. this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
  8571. }
  8572. this.next();
  8573. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  8574. this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
  8575. }
  8576. this.registerTopicReference();
  8577. return this.finishNode(node, "PipelinePrimaryTopicReference");
  8578. }
  8579. const nextCh = this.input.codePointAt(this.state.end);
  8580. if (isIdentifierStart(nextCh) || nextCh === 92) {
  8581. const start = this.state.start;
  8582. node = this.parseMaybePrivateName(true);
  8583. if (this.match(types._in)) {
  8584. this.expectPlugin("privateIn");
  8585. this.classScope.usePrivateName(node.id.name, node.start);
  8586. } else if (this.hasPlugin("privateIn")) {
  8587. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, node.id.name);
  8588. } else {
  8589. throw this.unexpected(start);
  8590. }
  8591. return node;
  8592. }
  8593. }
  8594. case types.relational:
  8595. {
  8596. if (this.state.value === "<") {
  8597. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  8598. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  8599. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  8600. }
  8601. }
  8602. }
  8603. default:
  8604. throw this.unexpected();
  8605. }
  8606. }
  8607. parseAsyncArrowUnaryFunction(id) {
  8608. const node = this.startNodeAtNode(id);
  8609. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  8610. const params = [this.parseIdentifier()];
  8611. this.prodParam.exit();
  8612. if (this.hasPrecedingLineBreak()) {
  8613. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  8614. }
  8615. this.expect(types.arrow);
  8616. this.parseArrowExpression(node, params, true);
  8617. return node;
  8618. }
  8619. parseDo() {
  8620. this.expectPlugin("doExpressions");
  8621. const node = this.startNode();
  8622. this.next();
  8623. const oldLabels = this.state.labels;
  8624. this.state.labels = [];
  8625. node.body = this.parseBlock();
  8626. this.state.labels = oldLabels;
  8627. return this.finishNode(node, "DoExpression");
  8628. }
  8629. parseSuper() {
  8630. const node = this.startNode();
  8631. this.next();
  8632. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  8633. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  8634. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  8635. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  8636. }
  8637. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  8638. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  8639. }
  8640. return this.finishNode(node, "Super");
  8641. }
  8642. parseBooleanLiteral() {
  8643. const node = this.startNode();
  8644. node.value = this.match(types._true);
  8645. this.next();
  8646. return this.finishNode(node, "BooleanLiteral");
  8647. }
  8648. parseMaybePrivateName(isPrivateNameAllowed) {
  8649. const isPrivate = this.match(types.hash);
  8650. if (isPrivate) {
  8651. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  8652. if (!isPrivateNameAllowed) {
  8653. this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
  8654. }
  8655. const node = this.startNode();
  8656. this.next();
  8657. this.assertNoSpace("Unexpected space between # and identifier");
  8658. node.id = this.parseIdentifier(true);
  8659. return this.finishNode(node, "PrivateName");
  8660. } else {
  8661. return this.parseIdentifier(true);
  8662. }
  8663. }
  8664. parseFunctionOrFunctionSent() {
  8665. const node = this.startNode();
  8666. this.next();
  8667. if (this.prodParam.hasYield && this.match(types.dot)) {
  8668. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  8669. this.next();
  8670. return this.parseMetaProperty(node, meta, "sent");
  8671. }
  8672. return this.parseFunction(node);
  8673. }
  8674. parseMetaProperty(node, meta, propertyName) {
  8675. node.meta = meta;
  8676. if (meta.name === "function" && propertyName === "sent") {
  8677. if (this.isContextual(propertyName)) {
  8678. this.expectPlugin("functionSent");
  8679. } else if (!this.hasPlugin("functionSent")) {
  8680. this.unexpected();
  8681. }
  8682. }
  8683. const containsEsc = this.state.containsEsc;
  8684. node.property = this.parseIdentifier(true);
  8685. if (node.property.name !== propertyName || containsEsc) {
  8686. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  8687. }
  8688. return this.finishNode(node, "MetaProperty");
  8689. }
  8690. parseImportMetaProperty(node) {
  8691. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  8692. this.next();
  8693. if (this.isContextual("meta")) {
  8694. if (!this.inModule) {
  8695. this.raiseWithData(id.start, {
  8696. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8697. }, ErrorMessages.ImportMetaOutsideModule);
  8698. }
  8699. this.sawUnambiguousESM = true;
  8700. }
  8701. return this.parseMetaProperty(node, id, "meta");
  8702. }
  8703. parseLiteral(value, type, startPos, startLoc) {
  8704. startPos = startPos || this.state.start;
  8705. startLoc = startLoc || this.state.startLoc;
  8706. const node = this.startNodeAt(startPos, startLoc);
  8707. this.addExtra(node, "rawValue", value);
  8708. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  8709. node.value = value;
  8710. this.next();
  8711. return this.finishNode(node, type);
  8712. }
  8713. parseParenAndDistinguishExpression(canBeArrow) {
  8714. const startPos = this.state.start;
  8715. const startLoc = this.state.startLoc;
  8716. let val;
  8717. this.next();
  8718. this.expressionScope.enter(newArrowHeadScope());
  8719. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8720. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8721. this.state.maybeInArrowParameters = true;
  8722. this.state.inFSharpPipelineDirectBody = false;
  8723. const innerStartPos = this.state.start;
  8724. const innerStartLoc = this.state.startLoc;
  8725. const exprList = [];
  8726. const refExpressionErrors = new ExpressionErrors();
  8727. const refNeedsArrowPos = {
  8728. start: 0
  8729. };
  8730. let first = true;
  8731. let spreadStart;
  8732. let optionalCommaStart;
  8733. while (!this.match(types.parenR)) {
  8734. if (first) {
  8735. first = false;
  8736. } else {
  8737. this.expect(types.comma, refNeedsArrowPos.start || null);
  8738. if (this.match(types.parenR)) {
  8739. optionalCommaStart = this.state.start;
  8740. break;
  8741. }
  8742. }
  8743. if (this.match(types.ellipsis)) {
  8744. const spreadNodeStartPos = this.state.start;
  8745. const spreadNodeStartLoc = this.state.startLoc;
  8746. spreadStart = this.state.start;
  8747. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  8748. this.checkCommaAfterRest(41);
  8749. break;
  8750. } else {
  8751. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  8752. }
  8753. }
  8754. const innerEndPos = this.state.lastTokEnd;
  8755. const innerEndLoc = this.state.lastTokEndLoc;
  8756. this.expect(types.parenR);
  8757. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8758. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8759. let arrowNode = this.startNodeAt(startPos, startLoc);
  8760. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  8761. this.expressionScope.validateAsPattern();
  8762. this.expressionScope.exit();
  8763. for (let _i2 = 0; _i2 < exprList.length; _i2++) {
  8764. const param = exprList[_i2];
  8765. if (param.extra && param.extra.parenthesized) {
  8766. this.unexpected(param.extra.parenStart);
  8767. }
  8768. }
  8769. this.parseArrowExpression(arrowNode, exprList, false);
  8770. return arrowNode;
  8771. }
  8772. this.expressionScope.exit();
  8773. if (!exprList.length) {
  8774. this.unexpected(this.state.lastTokStart);
  8775. }
  8776. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8777. if (spreadStart) this.unexpected(spreadStart);
  8778. this.checkExpressionErrors(refExpressionErrors, true);
  8779. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8780. this.toReferencedListDeep(exprList, true);
  8781. if (exprList.length > 1) {
  8782. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8783. val.expressions = exprList;
  8784. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8785. } else {
  8786. val = exprList[0];
  8787. }
  8788. if (!this.options.createParenthesizedExpressions) {
  8789. this.addExtra(val, "parenthesized", true);
  8790. this.addExtra(val, "parenStart", startPos);
  8791. return val;
  8792. }
  8793. const parenExpression = this.startNodeAt(startPos, startLoc);
  8794. parenExpression.expression = val;
  8795. this.finishNode(parenExpression, "ParenthesizedExpression");
  8796. return parenExpression;
  8797. }
  8798. shouldParseArrow() {
  8799. return !this.canInsertSemicolon();
  8800. }
  8801. parseArrow(node) {
  8802. if (this.eat(types.arrow)) {
  8803. return node;
  8804. }
  8805. }
  8806. parseParenItem(node, startPos, startLoc) {
  8807. return node;
  8808. }
  8809. parseNewOrNewTarget() {
  8810. const node = this.startNode();
  8811. this.next();
  8812. if (this.match(types.dot)) {
  8813. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  8814. this.next();
  8815. const metaProp = this.parseMetaProperty(node, meta, "target");
  8816. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  8817. let error = ErrorMessages.UnexpectedNewTarget;
  8818. if (this.hasPlugin("classProperties")) {
  8819. error += " or class properties";
  8820. }
  8821. this.raise(metaProp.start, error);
  8822. }
  8823. return metaProp;
  8824. }
  8825. return this.parseNew(node);
  8826. }
  8827. parseNew(node) {
  8828. node.callee = this.parseNoCallExpr();
  8829. if (node.callee.type === "Import") {
  8830. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  8831. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  8832. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  8833. } else if (this.eat(types.questionDot)) {
  8834. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  8835. }
  8836. this.parseNewArguments(node);
  8837. return this.finishNode(node, "NewExpression");
  8838. }
  8839. parseNewArguments(node) {
  8840. if (this.eat(types.parenL)) {
  8841. const args = this.parseExprList(types.parenR);
  8842. this.toReferencedList(args);
  8843. node.arguments = args;
  8844. } else {
  8845. node.arguments = [];
  8846. }
  8847. }
  8848. parseTemplateElement(isTagged) {
  8849. const elem = this.startNode();
  8850. if (this.state.value === null) {
  8851. if (!isTagged) {
  8852. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  8853. }
  8854. }
  8855. elem.value = {
  8856. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8857. cooked: this.state.value
  8858. };
  8859. this.next();
  8860. elem.tail = this.match(types.backQuote);
  8861. return this.finishNode(elem, "TemplateElement");
  8862. }
  8863. parseTemplate(isTagged) {
  8864. const node = this.startNode();
  8865. this.next();
  8866. node.expressions = [];
  8867. let curElt = this.parseTemplateElement(isTagged);
  8868. node.quasis = [curElt];
  8869. while (!curElt.tail) {
  8870. this.expect(types.dollarBraceL);
  8871. node.expressions.push(this.parseTemplateSubstitution());
  8872. this.expect(types.braceR);
  8873. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8874. }
  8875. this.next();
  8876. return this.finishNode(node, "TemplateLiteral");
  8877. }
  8878. parseTemplateSubstitution() {
  8879. return this.parseExpression();
  8880. }
  8881. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  8882. if (isRecord) {
  8883. this.expectPlugin("recordAndTuple");
  8884. }
  8885. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8886. this.state.inFSharpPipelineDirectBody = false;
  8887. const propHash = Object.create(null);
  8888. let first = true;
  8889. const node = this.startNode();
  8890. node.properties = [];
  8891. this.next();
  8892. while (!this.match(close)) {
  8893. if (first) {
  8894. first = false;
  8895. } else {
  8896. this.expect(types.comma);
  8897. if (this.match(close)) {
  8898. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8899. break;
  8900. }
  8901. }
  8902. const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
  8903. if (!isPattern) {
  8904. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  8905. }
  8906. if (isRecord && prop.type !== "ObjectProperty" && prop.type !== "SpreadElement") {
  8907. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  8908. }
  8909. if (prop.shorthand) {
  8910. this.addExtra(prop, "shorthand", true);
  8911. }
  8912. node.properties.push(prop);
  8913. }
  8914. this.state.exprAllowed = false;
  8915. this.next();
  8916. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8917. let type = "ObjectExpression";
  8918. if (isPattern) {
  8919. type = "ObjectPattern";
  8920. } else if (isRecord) {
  8921. type = "RecordExpression";
  8922. }
  8923. return this.finishNode(node, type);
  8924. }
  8925. maybeAsyncOrAccessorProp(prop) {
  8926. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
  8927. }
  8928. parsePropertyDefinition(isPattern, refExpressionErrors) {
  8929. let decorators = [];
  8930. if (this.match(types.at)) {
  8931. if (this.hasPlugin("decorators")) {
  8932. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  8933. }
  8934. while (this.match(types.at)) {
  8935. decorators.push(this.parseDecorator());
  8936. }
  8937. }
  8938. const prop = this.startNode();
  8939. let isGenerator = false;
  8940. let isAsync = false;
  8941. let isAccessor = false;
  8942. let startPos;
  8943. let startLoc;
  8944. if (this.match(types.ellipsis)) {
  8945. if (decorators.length) this.unexpected();
  8946. if (isPattern) {
  8947. this.next();
  8948. prop.argument = this.parseIdentifier();
  8949. this.checkCommaAfterRest(125);
  8950. return this.finishNode(prop, "RestElement");
  8951. }
  8952. return this.parseSpread();
  8953. }
  8954. if (decorators.length) {
  8955. prop.decorators = decorators;
  8956. decorators = [];
  8957. }
  8958. prop.method = false;
  8959. if (isPattern || refExpressionErrors) {
  8960. startPos = this.state.start;
  8961. startLoc = this.state.startLoc;
  8962. }
  8963. if (!isPattern) {
  8964. isGenerator = this.eat(types.star);
  8965. }
  8966. const containsEsc = this.state.containsEsc;
  8967. const key = this.parsePropertyName(prop, false);
  8968. if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  8969. const keyName = key.name;
  8970. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  8971. isAsync = true;
  8972. isGenerator = this.eat(types.star);
  8973. this.parsePropertyName(prop, false);
  8974. }
  8975. if (keyName === "get" || keyName === "set") {
  8976. isAccessor = true;
  8977. prop.kind = keyName;
  8978. if (this.match(types.star)) {
  8979. isGenerator = true;
  8980. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  8981. this.next();
  8982. }
  8983. this.parsePropertyName(prop, false);
  8984. }
  8985. }
  8986. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  8987. return prop;
  8988. }
  8989. getGetterSetterExpectedParamCount(method) {
  8990. return method.kind === "get" ? 0 : 1;
  8991. }
  8992. getObjectOrClassMethodParams(method) {
  8993. return method.params;
  8994. }
  8995. checkGetterSetterParams(method) {
  8996. var _params;
  8997. const paramCount = this.getGetterSetterExpectedParamCount(method);
  8998. const params = this.getObjectOrClassMethodParams(method);
  8999. const start = method.start;
  9000. if (params.length !== paramCount) {
  9001. if (method.kind === "get") {
  9002. this.raise(start, ErrorMessages.BadGetterArity);
  9003. } else {
  9004. this.raise(start, ErrorMessages.BadSetterArity);
  9005. }
  9006. }
  9007. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  9008. this.raise(start, ErrorMessages.BadSetterRestParameter);
  9009. }
  9010. }
  9011. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  9012. if (isAccessor) {
  9013. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  9014. this.checkGetterSetterParams(prop);
  9015. return prop;
  9016. }
  9017. if (isAsync || isGenerator || this.match(types.parenL)) {
  9018. if (isPattern) this.unexpected();
  9019. prop.kind = "method";
  9020. prop.method = true;
  9021. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  9022. }
  9023. }
  9024. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  9025. prop.shorthand = false;
  9026. if (this.eat(types.colon)) {
  9027. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  9028. return this.finishNode(prop, "ObjectProperty");
  9029. }
  9030. if (!prop.computed && prop.key.type === "Identifier") {
  9031. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  9032. if (isPattern) {
  9033. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9034. } else if (this.match(types.eq) && refExpressionErrors) {
  9035. if (refExpressionErrors.shorthandAssign === -1) {
  9036. refExpressionErrors.shorthandAssign = this.state.start;
  9037. }
  9038. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9039. } else {
  9040. prop.value = prop.key.__clone();
  9041. }
  9042. prop.shorthand = true;
  9043. return this.finishNode(prop, "ObjectProperty");
  9044. }
  9045. }
  9046. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9047. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  9048. if (!node) this.unexpected();
  9049. return node;
  9050. }
  9051. parsePropertyName(prop, isPrivateNameAllowed) {
  9052. if (this.eat(types.bracketL)) {
  9053. prop.computed = true;
  9054. prop.key = this.parseMaybeAssignAllowIn();
  9055. this.expect(types.bracketR);
  9056. } else {
  9057. const oldInPropertyName = this.state.inPropertyName;
  9058. this.state.inPropertyName = true;
  9059. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  9060. if (prop.key.type !== "PrivateName") {
  9061. prop.computed = false;
  9062. }
  9063. this.state.inPropertyName = oldInPropertyName;
  9064. }
  9065. return prop.key;
  9066. }
  9067. initFunction(node, isAsync) {
  9068. node.id = null;
  9069. node.generator = false;
  9070. node.async = !!isAsync;
  9071. }
  9072. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  9073. this.initFunction(node, isAsync);
  9074. node.generator = !!isGenerator;
  9075. const allowModifiers = isConstructor;
  9076. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  9077. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9078. this.parseFunctionParams(node, allowModifiers);
  9079. this.parseFunctionBodyAndFinish(node, type, true);
  9080. this.prodParam.exit();
  9081. this.scope.exit();
  9082. return node;
  9083. }
  9084. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  9085. if (isTuple) {
  9086. this.expectPlugin("recordAndTuple");
  9087. }
  9088. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9089. this.state.inFSharpPipelineDirectBody = false;
  9090. const node = this.startNode();
  9091. this.next();
  9092. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  9093. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9094. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  9095. }
  9096. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  9097. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  9098. let flags = functionFlags(isAsync, false);
  9099. if (!this.match(types.bracketL) && this.prodParam.hasIn) {
  9100. flags |= PARAM_IN;
  9101. }
  9102. this.prodParam.enter(flags);
  9103. this.initFunction(node, isAsync);
  9104. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9105. if (params) {
  9106. this.state.maybeInArrowParameters = true;
  9107. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  9108. }
  9109. this.state.maybeInArrowParameters = false;
  9110. this.parseFunctionBody(node, true);
  9111. this.prodParam.exit();
  9112. this.scope.exit();
  9113. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9114. return this.finishNode(node, "ArrowFunctionExpression");
  9115. }
  9116. setArrowFunctionParameters(node, params, trailingCommaPos) {
  9117. node.params = this.toAssignableList(params, trailingCommaPos);
  9118. }
  9119. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  9120. this.parseFunctionBody(node, false, isMethod);
  9121. this.finishNode(node, type);
  9122. }
  9123. parseFunctionBody(node, allowExpression, isMethod = false) {
  9124. const isExpression = allowExpression && !this.match(types.braceL);
  9125. this.expressionScope.enter(newExpressionScope());
  9126. if (isExpression) {
  9127. node.body = this.parseMaybeAssign();
  9128. this.checkParams(node, false, allowExpression, false);
  9129. } else {
  9130. const oldStrict = this.state.strict;
  9131. const oldLabels = this.state.labels;
  9132. this.state.labels = [];
  9133. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  9134. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  9135. const nonSimple = !this.isSimpleParamList(node.params);
  9136. if (hasStrictModeDirective && nonSimple) {
  9137. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  9138. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  9139. }
  9140. const strictModeChanged = !oldStrict && this.state.strict;
  9141. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  9142. if (this.state.strict && node.id) {
  9143. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, strictModeChanged);
  9144. }
  9145. });
  9146. this.prodParam.exit();
  9147. this.expressionScope.exit();
  9148. this.state.labels = oldLabels;
  9149. }
  9150. }
  9151. isSimpleParamList(params) {
  9152. for (let i = 0, len = params.length; i < len; i++) {
  9153. if (params[i].type !== "Identifier") return false;
  9154. }
  9155. return true;
  9156. }
  9157. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  9158. const nameHash = Object.create(null);
  9159. for (let i = 0; i < node.params.length; i++) {
  9160. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged);
  9161. }
  9162. }
  9163. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  9164. const elts = [];
  9165. let first = true;
  9166. while (!this.eat(close)) {
  9167. if (first) {
  9168. first = false;
  9169. } else {
  9170. this.expect(types.comma);
  9171. if (this.match(close)) {
  9172. if (nodeForExtra) {
  9173. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  9174. }
  9175. this.next();
  9176. break;
  9177. }
  9178. }
  9179. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  9180. }
  9181. return elts;
  9182. }
  9183. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  9184. let elt;
  9185. if (this.match(types.comma)) {
  9186. if (!allowEmpty) {
  9187. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  9188. }
  9189. elt = null;
  9190. } else if (this.match(types.ellipsis)) {
  9191. const spreadNodeStartPos = this.state.start;
  9192. const spreadNodeStartLoc = this.state.startLoc;
  9193. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  9194. } else if (this.match(types.question)) {
  9195. this.expectPlugin("partialApplication");
  9196. if (!allowPlaceholder) {
  9197. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  9198. }
  9199. const node = this.startNode();
  9200. this.next();
  9201. elt = this.finishNode(node, "ArgumentPlaceholder");
  9202. } else {
  9203. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  9204. }
  9205. return elt;
  9206. }
  9207. parseIdentifier(liberal) {
  9208. const node = this.startNode();
  9209. const name = this.parseIdentifierName(node.start, liberal);
  9210. return this.createIdentifier(node, name);
  9211. }
  9212. createIdentifier(node, name) {
  9213. node.name = name;
  9214. node.loc.identifierName = name;
  9215. return this.finishNode(node, "Identifier");
  9216. }
  9217. parseIdentifierName(pos, liberal) {
  9218. let name;
  9219. const {
  9220. start,
  9221. type
  9222. } = this.state;
  9223. if (type === types.name) {
  9224. name = this.state.value;
  9225. } else if (type.keyword) {
  9226. name = type.keyword;
  9227. const curContext = this.curContext();
  9228. if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
  9229. this.state.context.pop();
  9230. }
  9231. } else {
  9232. throw this.unexpected();
  9233. }
  9234. if (liberal) {
  9235. this.state.type = types.name;
  9236. } else {
  9237. this.checkReservedWord(name, start, !!type.keyword, false);
  9238. }
  9239. this.next();
  9240. return name;
  9241. }
  9242. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9243. if (this.prodParam.hasYield && word === "yield") {
  9244. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  9245. return;
  9246. }
  9247. if (word === "await") {
  9248. if (this.prodParam.hasAwait) {
  9249. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9250. return;
  9251. } else {
  9252. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9253. }
  9254. }
  9255. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  9256. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  9257. return;
  9258. }
  9259. if (checkKeywords && isKeyword(word)) {
  9260. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  9261. return;
  9262. }
  9263. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  9264. if (reservedTest(word, this.inModule)) {
  9265. if (!this.prodParam.hasAwait && word === "await") {
  9266. this.raise(startLoc, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction);
  9267. } else {
  9268. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  9269. }
  9270. }
  9271. }
  9272. isAwaitAllowed() {
  9273. if (this.scope.inFunction) return this.prodParam.hasAwait;
  9274. if (this.options.allowAwaitOutsideFunction) return true;
  9275. if (this.hasPlugin("topLevelAwait")) {
  9276. return this.inModule && this.prodParam.hasAwait;
  9277. }
  9278. return false;
  9279. }
  9280. parseAwait() {
  9281. const node = this.startNode();
  9282. this.next();
  9283. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  9284. if (this.eat(types.star)) {
  9285. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  9286. }
  9287. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  9288. if (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)) {
  9289. this.ambiguousScriptDifferentAst = true;
  9290. } else {
  9291. this.sawUnambiguousESM = true;
  9292. }
  9293. }
  9294. if (!this.state.soloAwait) {
  9295. node.argument = this.parseMaybeUnary();
  9296. }
  9297. return this.finishNode(node, "AwaitExpression");
  9298. }
  9299. parseYield() {
  9300. const node = this.startNode();
  9301. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  9302. this.next();
  9303. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  9304. node.delegate = false;
  9305. node.argument = null;
  9306. } else {
  9307. node.delegate = this.eat(types.star);
  9308. node.argument = this.parseMaybeAssign();
  9309. }
  9310. return this.finishNode(node, "YieldExpression");
  9311. }
  9312. checkPipelineAtInfixOperator(left, leftStartPos) {
  9313. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  9314. if (left.type === "SequenceExpression") {
  9315. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  9316. }
  9317. }
  9318. }
  9319. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  9320. this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
  9321. return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
  9322. }
  9323. checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
  9324. if (this.match(types.arrow)) {
  9325. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  9326. } else if (childExpression.type === "SequenceExpression") {
  9327. this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
  9328. }
  9329. }
  9330. parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
  9331. const bodyNode = this.startNodeAt(startPos, startLoc);
  9332. const isSimpleReference = this.isSimpleReference(childExpression);
  9333. if (isSimpleReference) {
  9334. bodyNode.callee = childExpression;
  9335. } else {
  9336. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  9337. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  9338. }
  9339. bodyNode.expression = childExpression;
  9340. }
  9341. return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
  9342. }
  9343. isSimpleReference(expression) {
  9344. switch (expression.type) {
  9345. case "MemberExpression":
  9346. return !expression.computed && this.isSimpleReference(expression.object);
  9347. case "Identifier":
  9348. return true;
  9349. default:
  9350. return false;
  9351. }
  9352. }
  9353. withTopicPermittingContext(callback) {
  9354. const outerContextTopicState = this.state.topicContext;
  9355. this.state.topicContext = {
  9356. maxNumOfResolvableTopics: 1,
  9357. maxTopicIndex: null
  9358. };
  9359. try {
  9360. return callback();
  9361. } finally {
  9362. this.state.topicContext = outerContextTopicState;
  9363. }
  9364. }
  9365. withTopicForbiddingContext(callback) {
  9366. const outerContextTopicState = this.state.topicContext;
  9367. this.state.topicContext = {
  9368. maxNumOfResolvableTopics: 0,
  9369. maxTopicIndex: null
  9370. };
  9371. try {
  9372. return callback();
  9373. } finally {
  9374. this.state.topicContext = outerContextTopicState;
  9375. }
  9376. }
  9377. withSoloAwaitPermittingContext(callback) {
  9378. const outerContextSoloAwaitState = this.state.soloAwait;
  9379. this.state.soloAwait = true;
  9380. try {
  9381. return callback();
  9382. } finally {
  9383. this.state.soloAwait = outerContextSoloAwaitState;
  9384. }
  9385. }
  9386. allowInAnd(callback) {
  9387. const flags = this.prodParam.currentFlags();
  9388. const prodParamToSet = PARAM_IN & ~flags;
  9389. if (prodParamToSet) {
  9390. this.prodParam.enter(flags | PARAM_IN);
  9391. try {
  9392. return callback();
  9393. } finally {
  9394. this.prodParam.exit();
  9395. }
  9396. }
  9397. return callback();
  9398. }
  9399. disallowInAnd(callback) {
  9400. const flags = this.prodParam.currentFlags();
  9401. const prodParamToClear = PARAM_IN & flags;
  9402. if (prodParamToClear) {
  9403. this.prodParam.enter(flags & ~PARAM_IN);
  9404. try {
  9405. return callback();
  9406. } finally {
  9407. this.prodParam.exit();
  9408. }
  9409. }
  9410. return callback();
  9411. }
  9412. registerTopicReference() {
  9413. this.state.topicContext.maxTopicIndex = 0;
  9414. }
  9415. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  9416. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  9417. }
  9418. topicReferenceWasUsedInCurrentTopicContext() {
  9419. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  9420. }
  9421. parseFSharpPipelineBody(prec) {
  9422. const startPos = this.state.start;
  9423. const startLoc = this.state.startLoc;
  9424. this.state.potentialArrowAt = this.state.start;
  9425. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9426. this.state.inFSharpPipelineDirectBody = true;
  9427. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
  9428. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9429. return ret;
  9430. }
  9431. }
  9432. const loopLabel = {
  9433. kind: "loop"
  9434. },
  9435. switchLabel = {
  9436. kind: "switch"
  9437. };
  9438. const FUNC_NO_FLAGS = 0b000,
  9439. FUNC_STATEMENT = 0b001,
  9440. FUNC_HANGING_STATEMENT = 0b010,
  9441. FUNC_NULLABLE_ID = 0b100;
  9442. const loneSurrogate = /[\uD800-\uDFFF]/u;
  9443. class StatementParser extends ExpressionParser {
  9444. parseTopLevel(file, program) {
  9445. program.sourceType = this.options.sourceType;
  9446. program.interpreter = this.parseInterpreterDirective();
  9447. this.parseBlockBody(program, true, true, types.eof);
  9448. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9449. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  9450. const [name] = _Array$from[_i];
  9451. const pos = this.scope.undefinedExports.get(name);
  9452. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  9453. }
  9454. }
  9455. file.program = this.finishNode(program, "Program");
  9456. file.comments = this.state.comments;
  9457. if (this.options.tokens) file.tokens = this.tokens;
  9458. return this.finishNode(file, "File");
  9459. }
  9460. stmtToDirective(stmt) {
  9461. const expr = stmt.expression;
  9462. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9463. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9464. const raw = this.input.slice(expr.start, expr.end);
  9465. const val = directiveLiteral.value = raw.slice(1, -1);
  9466. this.addExtra(directiveLiteral, "raw", raw);
  9467. this.addExtra(directiveLiteral, "rawValue", val);
  9468. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9469. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9470. }
  9471. parseInterpreterDirective() {
  9472. if (!this.match(types.interpreterDirective)) {
  9473. return null;
  9474. }
  9475. const node = this.startNode();
  9476. node.value = this.state.value;
  9477. this.next();
  9478. return this.finishNode(node, "InterpreterDirective");
  9479. }
  9480. isLet(context) {
  9481. if (!this.isContextual("let")) {
  9482. return false;
  9483. }
  9484. const next = this.nextTokenStart();
  9485. const nextCh = this.input.charCodeAt(next);
  9486. if (nextCh === 91) return true;
  9487. if (context) return false;
  9488. if (nextCh === 123) return true;
  9489. if (isIdentifierStart(nextCh)) {
  9490. let pos = next + 1;
  9491. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9492. ++pos;
  9493. }
  9494. const ident = this.input.slice(next, pos);
  9495. if (!keywordRelationalOperator.test(ident)) return true;
  9496. }
  9497. return false;
  9498. }
  9499. parseStatement(context, topLevel) {
  9500. if (this.match(types.at)) {
  9501. this.parseDecorators(true);
  9502. }
  9503. return this.parseStatementContent(context, topLevel);
  9504. }
  9505. parseStatementContent(context, topLevel) {
  9506. let starttype = this.state.type;
  9507. const node = this.startNode();
  9508. let kind;
  9509. if (this.isLet(context)) {
  9510. starttype = types._var;
  9511. kind = "let";
  9512. }
  9513. switch (starttype) {
  9514. case types._break:
  9515. case types._continue:
  9516. return this.parseBreakContinueStatement(node, starttype.keyword);
  9517. case types._debugger:
  9518. return this.parseDebuggerStatement(node);
  9519. case types._do:
  9520. return this.parseDoStatement(node);
  9521. case types._for:
  9522. return this.parseForStatement(node);
  9523. case types._function:
  9524. if (this.lookaheadCharCode() === 46) break;
  9525. if (context) {
  9526. if (this.state.strict) {
  9527. this.raise(this.state.start, ErrorMessages.StrictFunction);
  9528. } else if (context !== "if" && context !== "label") {
  9529. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  9530. }
  9531. }
  9532. return this.parseFunctionStatement(node, false, !context);
  9533. case types._class:
  9534. if (context) this.unexpected();
  9535. return this.parseClass(node, true);
  9536. case types._if:
  9537. return this.parseIfStatement(node);
  9538. case types._return:
  9539. return this.parseReturnStatement(node);
  9540. case types._switch:
  9541. return this.parseSwitchStatement(node);
  9542. case types._throw:
  9543. return this.parseThrowStatement(node);
  9544. case types._try:
  9545. return this.parseTryStatement(node);
  9546. case types._const:
  9547. case types._var:
  9548. kind = kind || this.state.value;
  9549. if (context && kind !== "var") {
  9550. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  9551. }
  9552. return this.parseVarStatement(node, kind);
  9553. case types._while:
  9554. return this.parseWhileStatement(node);
  9555. case types._with:
  9556. return this.parseWithStatement(node);
  9557. case types.braceL:
  9558. return this.parseBlock();
  9559. case types.semi:
  9560. return this.parseEmptyStatement(node);
  9561. case types._import:
  9562. {
  9563. const nextTokenCharCode = this.lookaheadCharCode();
  9564. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  9565. break;
  9566. }
  9567. }
  9568. case types._export:
  9569. {
  9570. if (!this.options.allowImportExportEverywhere && !topLevel) {
  9571. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  9572. }
  9573. this.next();
  9574. let result;
  9575. if (starttype === types._import) {
  9576. result = this.parseImport(node);
  9577. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  9578. this.sawUnambiguousESM = true;
  9579. }
  9580. } else {
  9581. result = this.parseExport(node);
  9582. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  9583. this.sawUnambiguousESM = true;
  9584. }
  9585. }
  9586. this.assertModuleNodeAllowed(node);
  9587. return result;
  9588. }
  9589. default:
  9590. {
  9591. if (this.isAsyncFunction()) {
  9592. if (context) {
  9593. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  9594. }
  9595. this.next();
  9596. return this.parseFunctionStatement(node, true, !context);
  9597. }
  9598. }
  9599. }
  9600. const maybeName = this.state.value;
  9601. const expr = this.parseExpression();
  9602. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  9603. return this.parseLabeledStatement(node, maybeName, expr, context);
  9604. } else {
  9605. return this.parseExpressionStatement(node, expr);
  9606. }
  9607. }
  9608. assertModuleNodeAllowed(node) {
  9609. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  9610. this.raiseWithData(node.start, {
  9611. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9612. }, ErrorMessages.ImportOutsideModule);
  9613. }
  9614. }
  9615. takeDecorators(node) {
  9616. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9617. if (decorators.length) {
  9618. node.decorators = decorators;
  9619. this.resetStartLocationFromNode(node, decorators[0]);
  9620. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  9621. }
  9622. }
  9623. canHaveLeadingDecorator() {
  9624. return this.match(types._class);
  9625. }
  9626. parseDecorators(allowExport) {
  9627. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9628. while (this.match(types.at)) {
  9629. const decorator = this.parseDecorator();
  9630. currentContextDecorators.push(decorator);
  9631. }
  9632. if (this.match(types._export)) {
  9633. if (!allowExport) {
  9634. this.unexpected();
  9635. }
  9636. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9637. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  9638. }
  9639. } else if (!this.canHaveLeadingDecorator()) {
  9640. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  9641. }
  9642. }
  9643. parseDecorator() {
  9644. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  9645. const node = this.startNode();
  9646. this.next();
  9647. if (this.hasPlugin("decorators")) {
  9648. this.state.decoratorStack.push([]);
  9649. const startPos = this.state.start;
  9650. const startLoc = this.state.startLoc;
  9651. let expr;
  9652. if (this.eat(types.parenL)) {
  9653. expr = this.parseExpression();
  9654. this.expect(types.parenR);
  9655. } else {
  9656. expr = this.parseIdentifier(false);
  9657. while (this.eat(types.dot)) {
  9658. const node = this.startNodeAt(startPos, startLoc);
  9659. node.object = expr;
  9660. node.property = this.parseIdentifier(true);
  9661. node.computed = false;
  9662. expr = this.finishNode(node, "MemberExpression");
  9663. }
  9664. }
  9665. node.expression = this.parseMaybeDecoratorArguments(expr);
  9666. this.state.decoratorStack.pop();
  9667. } else {
  9668. node.expression = this.parseExprSubscripts();
  9669. }
  9670. return this.finishNode(node, "Decorator");
  9671. }
  9672. parseMaybeDecoratorArguments(expr) {
  9673. if (this.eat(types.parenL)) {
  9674. const node = this.startNodeAtNode(expr);
  9675. node.callee = expr;
  9676. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  9677. this.toReferencedList(node.arguments);
  9678. return this.finishNode(node, "CallExpression");
  9679. }
  9680. return expr;
  9681. }
  9682. parseBreakContinueStatement(node, keyword) {
  9683. const isBreak = keyword === "break";
  9684. this.next();
  9685. if (this.isLineTerminator()) {
  9686. node.label = null;
  9687. } else {
  9688. node.label = this.parseIdentifier();
  9689. this.semicolon();
  9690. }
  9691. this.verifyBreakContinue(node, keyword);
  9692. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  9693. }
  9694. verifyBreakContinue(node, keyword) {
  9695. const isBreak = keyword === "break";
  9696. let i;
  9697. for (i = 0; i < this.state.labels.length; ++i) {
  9698. const lab = this.state.labels[i];
  9699. if (node.label == null || lab.name === node.label.name) {
  9700. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  9701. if (node.label && isBreak) break;
  9702. }
  9703. }
  9704. if (i === this.state.labels.length) {
  9705. this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
  9706. }
  9707. }
  9708. parseDebuggerStatement(node) {
  9709. this.next();
  9710. this.semicolon();
  9711. return this.finishNode(node, "DebuggerStatement");
  9712. }
  9713. parseHeaderExpression() {
  9714. this.expect(types.parenL);
  9715. const val = this.parseExpression();
  9716. this.expect(types.parenR);
  9717. return val;
  9718. }
  9719. parseDoStatement(node) {
  9720. this.next();
  9721. this.state.labels.push(loopLabel);
  9722. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  9723. this.state.labels.pop();
  9724. this.expect(types._while);
  9725. node.test = this.parseHeaderExpression();
  9726. this.eat(types.semi);
  9727. return this.finishNode(node, "DoWhileStatement");
  9728. }
  9729. parseForStatement(node) {
  9730. this.next();
  9731. this.state.labels.push(loopLabel);
  9732. let awaitAt = -1;
  9733. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  9734. awaitAt = this.state.lastTokStart;
  9735. }
  9736. this.scope.enter(SCOPE_OTHER);
  9737. this.expect(types.parenL);
  9738. if (this.match(types.semi)) {
  9739. if (awaitAt > -1) {
  9740. this.unexpected(awaitAt);
  9741. }
  9742. return this.parseFor(node, null);
  9743. }
  9744. const isLet = this.isLet();
  9745. if (this.match(types._var) || this.match(types._const) || isLet) {
  9746. const init = this.startNode();
  9747. const kind = isLet ? "let" : this.state.value;
  9748. this.next();
  9749. this.parseVar(init, true, kind);
  9750. this.finishNode(init, "VariableDeclaration");
  9751. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  9752. return this.parseForIn(node, init, awaitAt);
  9753. }
  9754. if (awaitAt > -1) {
  9755. this.unexpected(awaitAt);
  9756. }
  9757. return this.parseFor(node, init);
  9758. }
  9759. const refExpressionErrors = new ExpressionErrors();
  9760. const init = this.parseExpression(true, refExpressionErrors);
  9761. if (this.match(types._in) || this.isContextual("of")) {
  9762. this.toAssignable(init);
  9763. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  9764. this.checkLVal(init, undefined, undefined, description);
  9765. return this.parseForIn(node, init, awaitAt);
  9766. } else {
  9767. this.checkExpressionErrors(refExpressionErrors, true);
  9768. }
  9769. if (awaitAt > -1) {
  9770. this.unexpected(awaitAt);
  9771. }
  9772. return this.parseFor(node, init);
  9773. }
  9774. parseFunctionStatement(node, isAsync, declarationPosition) {
  9775. this.next();
  9776. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  9777. }
  9778. parseIfStatement(node) {
  9779. this.next();
  9780. node.test = this.parseHeaderExpression();
  9781. node.consequent = this.parseStatement("if");
  9782. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  9783. return this.finishNode(node, "IfStatement");
  9784. }
  9785. parseReturnStatement(node) {
  9786. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  9787. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  9788. }
  9789. this.next();
  9790. if (this.isLineTerminator()) {
  9791. node.argument = null;
  9792. } else {
  9793. node.argument = this.parseExpression();
  9794. this.semicolon();
  9795. }
  9796. return this.finishNode(node, "ReturnStatement");
  9797. }
  9798. parseSwitchStatement(node) {
  9799. this.next();
  9800. node.discriminant = this.parseHeaderExpression();
  9801. const cases = node.cases = [];
  9802. this.expect(types.braceL);
  9803. this.state.labels.push(switchLabel);
  9804. this.scope.enter(SCOPE_OTHER);
  9805. let cur;
  9806. for (let sawDefault; !this.match(types.braceR);) {
  9807. if (this.match(types._case) || this.match(types._default)) {
  9808. const isCase = this.match(types._case);
  9809. if (cur) this.finishNode(cur, "SwitchCase");
  9810. cases.push(cur = this.startNode());
  9811. cur.consequent = [];
  9812. this.next();
  9813. if (isCase) {
  9814. cur.test = this.parseExpression();
  9815. } else {
  9816. if (sawDefault) {
  9817. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  9818. }
  9819. sawDefault = true;
  9820. cur.test = null;
  9821. }
  9822. this.expect(types.colon);
  9823. } else {
  9824. if (cur) {
  9825. cur.consequent.push(this.parseStatement(null));
  9826. } else {
  9827. this.unexpected();
  9828. }
  9829. }
  9830. }
  9831. this.scope.exit();
  9832. if (cur) this.finishNode(cur, "SwitchCase");
  9833. this.next();
  9834. this.state.labels.pop();
  9835. return this.finishNode(node, "SwitchStatement");
  9836. }
  9837. parseThrowStatement(node) {
  9838. this.next();
  9839. if (this.hasPrecedingLineBreak()) {
  9840. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  9841. }
  9842. node.argument = this.parseExpression();
  9843. this.semicolon();
  9844. return this.finishNode(node, "ThrowStatement");
  9845. }
  9846. parseCatchClauseParam() {
  9847. const param = this.parseBindingAtom();
  9848. const simple = param.type === "Identifier";
  9849. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9850. this.checkLVal(param, BIND_LEXICAL, null, "catch clause");
  9851. return param;
  9852. }
  9853. parseTryStatement(node) {
  9854. this.next();
  9855. node.block = this.parseBlock();
  9856. node.handler = null;
  9857. if (this.match(types._catch)) {
  9858. const clause = this.startNode();
  9859. this.next();
  9860. if (this.match(types.parenL)) {
  9861. this.expect(types.parenL);
  9862. clause.param = this.parseCatchClauseParam();
  9863. this.expect(types.parenR);
  9864. } else {
  9865. clause.param = null;
  9866. this.scope.enter(SCOPE_OTHER);
  9867. }
  9868. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9869. this.scope.exit();
  9870. node.handler = this.finishNode(clause, "CatchClause");
  9871. }
  9872. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9873. if (!node.handler && !node.finalizer) {
  9874. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  9875. }
  9876. return this.finishNode(node, "TryStatement");
  9877. }
  9878. parseVarStatement(node, kind) {
  9879. this.next();
  9880. this.parseVar(node, false, kind);
  9881. this.semicolon();
  9882. return this.finishNode(node, "VariableDeclaration");
  9883. }
  9884. parseWhileStatement(node) {
  9885. this.next();
  9886. node.test = this.parseHeaderExpression();
  9887. this.state.labels.push(loopLabel);
  9888. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9889. this.state.labels.pop();
  9890. return this.finishNode(node, "WhileStatement");
  9891. }
  9892. parseWithStatement(node) {
  9893. if (this.state.strict) {
  9894. this.raise(this.state.start, ErrorMessages.StrictWith);
  9895. }
  9896. this.next();
  9897. node.object = this.parseHeaderExpression();
  9898. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9899. return this.finishNode(node, "WithStatement");
  9900. }
  9901. parseEmptyStatement(node) {
  9902. this.next();
  9903. return this.finishNode(node, "EmptyStatement");
  9904. }
  9905. parseLabeledStatement(node, maybeName, expr, context) {
  9906. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9907. const label = _this$state$labels[_i2];
  9908. if (label.name === maybeName) {
  9909. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  9910. }
  9911. }
  9912. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9913. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9914. const label = this.state.labels[i];
  9915. if (label.statementStart === node.start) {
  9916. label.statementStart = this.state.start;
  9917. label.kind = kind;
  9918. } else {
  9919. break;
  9920. }
  9921. }
  9922. this.state.labels.push({
  9923. name: maybeName,
  9924. kind: kind,
  9925. statementStart: this.state.start
  9926. });
  9927. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9928. this.state.labels.pop();
  9929. node.label = expr;
  9930. return this.finishNode(node, "LabeledStatement");
  9931. }
  9932. parseExpressionStatement(node, expr) {
  9933. node.expression = expr;
  9934. this.semicolon();
  9935. return this.finishNode(node, "ExpressionStatement");
  9936. }
  9937. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  9938. const node = this.startNode();
  9939. this.expect(types.braceL);
  9940. if (createNewLexicalScope) {
  9941. this.scope.enter(SCOPE_OTHER);
  9942. }
  9943. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  9944. if (createNewLexicalScope) {
  9945. this.scope.exit();
  9946. }
  9947. return this.finishNode(node, "BlockStatement");
  9948. }
  9949. isValidDirective(stmt) {
  9950. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9951. }
  9952. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  9953. const body = node.body = [];
  9954. const directives = node.directives = [];
  9955. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  9956. }
  9957. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  9958. const octalPositions = [];
  9959. const oldStrict = this.state.strict;
  9960. let hasStrictModeDirective = false;
  9961. let parsedNonDirective = false;
  9962. while (!this.match(end)) {
  9963. if (!parsedNonDirective && this.state.octalPositions.length) {
  9964. octalPositions.push(...this.state.octalPositions);
  9965. }
  9966. const stmt = this.parseStatement(null, topLevel);
  9967. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  9968. const directive = this.stmtToDirective(stmt);
  9969. directives.push(directive);
  9970. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  9971. hasStrictModeDirective = true;
  9972. this.setStrict(true);
  9973. }
  9974. continue;
  9975. }
  9976. parsedNonDirective = true;
  9977. body.push(stmt);
  9978. }
  9979. if (this.state.strict && octalPositions.length) {
  9980. for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
  9981. const pos = octalPositions[_i3];
  9982. this.raise(pos, ErrorMessages.StrictOctalLiteral);
  9983. }
  9984. }
  9985. if (afterBlockParse) {
  9986. afterBlockParse.call(this, hasStrictModeDirective);
  9987. }
  9988. if (!oldStrict) {
  9989. this.setStrict(false);
  9990. }
  9991. this.next();
  9992. }
  9993. parseFor(node, init) {
  9994. node.init = init;
  9995. this.expect(types.semi);
  9996. node.test = this.match(types.semi) ? null : this.parseExpression();
  9997. this.expect(types.semi);
  9998. node.update = this.match(types.parenR) ? null : this.parseExpression();
  9999. this.expect(types.parenR);
  10000. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10001. this.scope.exit();
  10002. this.state.labels.pop();
  10003. return this.finishNode(node, "ForStatement");
  10004. }
  10005. parseForIn(node, init, awaitAt) {
  10006. const isForIn = this.match(types._in);
  10007. this.next();
  10008. if (isForIn) {
  10009. if (awaitAt > -1) this.unexpected(awaitAt);
  10010. } else {
  10011. node.await = awaitAt > -1;
  10012. }
  10013. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  10014. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  10015. } else if (init.type === "AssignmentPattern") {
  10016. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  10017. }
  10018. node.left = init;
  10019. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  10020. this.expect(types.parenR);
  10021. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10022. this.scope.exit();
  10023. this.state.labels.pop();
  10024. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  10025. }
  10026. parseVar(node, isFor, kind) {
  10027. const declarations = node.declarations = [];
  10028. const isTypescript = this.hasPlugin("typescript");
  10029. node.kind = kind;
  10030. for (;;) {
  10031. const decl = this.startNode();
  10032. this.parseVarId(decl, kind);
  10033. if (this.eat(types.eq)) {
  10034. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  10035. } else {
  10036. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  10037. if (!isTypescript) {
  10038. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  10039. }
  10040. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  10041. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  10042. }
  10043. decl.init = null;
  10044. }
  10045. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  10046. if (!this.eat(types.comma)) break;
  10047. }
  10048. return node;
  10049. }
  10050. parseVarId(decl, kind) {
  10051. decl.id = this.parseBindingAtom();
  10052. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var");
  10053. }
  10054. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  10055. const isStatement = statement & FUNC_STATEMENT;
  10056. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  10057. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  10058. this.initFunction(node, isAsync);
  10059. if (this.match(types.star) && isHangingStatement) {
  10060. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  10061. }
  10062. node.generator = this.eat(types.star);
  10063. if (isStatement) {
  10064. node.id = this.parseFunctionId(requireId);
  10065. }
  10066. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10067. this.state.maybeInArrowParameters = false;
  10068. this.scope.enter(SCOPE_FUNCTION);
  10069. this.prodParam.enter(functionFlags(isAsync, node.generator));
  10070. if (!isStatement) {
  10071. node.id = this.parseFunctionId();
  10072. }
  10073. this.parseFunctionParams(node, false);
  10074. this.withTopicForbiddingContext(() => {
  10075. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  10076. });
  10077. this.prodParam.exit();
  10078. this.scope.exit();
  10079. if (isStatement && !isHangingStatement) {
  10080. this.registerFunctionStatementId(node);
  10081. }
  10082. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10083. return node;
  10084. }
  10085. parseFunctionId(requireId) {
  10086. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  10087. }
  10088. parseFunctionParams(node, allowModifiers) {
  10089. this.expect(types.parenL);
  10090. this.expressionScope.enter(newParameterDeclarationScope());
  10091. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  10092. this.expressionScope.exit();
  10093. }
  10094. registerFunctionStatementId(node) {
  10095. if (!node.id) return;
  10096. 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);
  10097. }
  10098. parseClass(node, isStatement, optionalId) {
  10099. this.next();
  10100. this.takeDecorators(node);
  10101. const oldStrict = this.state.strict;
  10102. this.state.strict = true;
  10103. this.parseClassId(node, isStatement, optionalId);
  10104. this.parseClassSuper(node);
  10105. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  10106. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  10107. }
  10108. isClassProperty() {
  10109. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  10110. }
  10111. isClassMethod() {
  10112. return this.match(types.parenL);
  10113. }
  10114. isNonstaticConstructor(method) {
  10115. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  10116. }
  10117. parseClassBody(constructorAllowsSuper, oldStrict) {
  10118. this.classScope.enter();
  10119. const state = {
  10120. constructorAllowsSuper,
  10121. hadConstructor: false,
  10122. hadStaticBlock: false
  10123. };
  10124. let decorators = [];
  10125. const classBody = this.startNode();
  10126. classBody.body = [];
  10127. this.expect(types.braceL);
  10128. this.withTopicForbiddingContext(() => {
  10129. while (!this.match(types.braceR)) {
  10130. if (this.eat(types.semi)) {
  10131. if (decorators.length > 0) {
  10132. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  10133. }
  10134. continue;
  10135. }
  10136. if (this.match(types.at)) {
  10137. decorators.push(this.parseDecorator());
  10138. continue;
  10139. }
  10140. const member = this.startNode();
  10141. if (decorators.length) {
  10142. member.decorators = decorators;
  10143. this.resetStartLocationFromNode(member, decorators[0]);
  10144. decorators = [];
  10145. }
  10146. this.parseClassMember(classBody, member, state);
  10147. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  10148. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  10149. }
  10150. }
  10151. });
  10152. this.state.strict = oldStrict;
  10153. this.next();
  10154. if (decorators.length) {
  10155. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  10156. }
  10157. this.classScope.exit();
  10158. return this.finishNode(classBody, "ClassBody");
  10159. }
  10160. parseClassMemberFromModifier(classBody, member) {
  10161. const key = this.parseIdentifier(true);
  10162. if (this.isClassMethod()) {
  10163. const method = member;
  10164. method.kind = "method";
  10165. method.computed = false;
  10166. method.key = key;
  10167. method.static = false;
  10168. this.pushClassMethod(classBody, method, false, false, false, false);
  10169. return true;
  10170. } else if (this.isClassProperty()) {
  10171. const prop = member;
  10172. prop.computed = false;
  10173. prop.key = key;
  10174. prop.static = false;
  10175. classBody.body.push(this.parseClassProperty(prop));
  10176. return true;
  10177. }
  10178. return false;
  10179. }
  10180. parseClassMember(classBody, member, state) {
  10181. const isStatic = this.isContextual("static");
  10182. if (isStatic) {
  10183. if (this.parseClassMemberFromModifier(classBody, member)) {
  10184. return;
  10185. }
  10186. if (this.eat(types.braceL)) {
  10187. this.parseClassStaticBlock(classBody, member, state);
  10188. return;
  10189. }
  10190. }
  10191. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  10192. }
  10193. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  10194. const publicMethod = member;
  10195. const privateMethod = member;
  10196. const publicProp = member;
  10197. const privateProp = member;
  10198. const method = publicMethod;
  10199. const publicMember = publicMethod;
  10200. member.static = isStatic;
  10201. if (this.eat(types.star)) {
  10202. method.kind = "method";
  10203. this.parseClassElementName(method);
  10204. if (method.key.type === "PrivateName") {
  10205. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  10206. return;
  10207. }
  10208. if (this.isNonstaticConstructor(publicMethod)) {
  10209. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  10210. }
  10211. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  10212. return;
  10213. }
  10214. const containsEsc = this.state.containsEsc;
  10215. const key = this.parseClassElementName(member);
  10216. const isPrivate = key.type === "PrivateName";
  10217. const isSimple = key.type === "Identifier";
  10218. const maybeQuestionTokenStart = this.state.start;
  10219. this.parsePostMemberNameModifiers(publicMember);
  10220. if (this.isClassMethod()) {
  10221. method.kind = "method";
  10222. if (isPrivate) {
  10223. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10224. return;
  10225. }
  10226. const isConstructor = this.isNonstaticConstructor(publicMethod);
  10227. let allowsDirectSuper = false;
  10228. if (isConstructor) {
  10229. publicMethod.kind = "constructor";
  10230. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  10231. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  10232. }
  10233. state.hadConstructor = true;
  10234. allowsDirectSuper = state.constructorAllowsSuper;
  10235. }
  10236. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  10237. } else if (this.isClassProperty()) {
  10238. if (isPrivate) {
  10239. this.pushClassPrivateProperty(classBody, privateProp);
  10240. } else {
  10241. this.pushClassProperty(classBody, publicProp);
  10242. }
  10243. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  10244. const isGenerator = this.eat(types.star);
  10245. if (publicMember.optional) {
  10246. this.unexpected(maybeQuestionTokenStart);
  10247. }
  10248. method.kind = "method";
  10249. this.parseClassElementName(method);
  10250. this.parsePostMemberNameModifiers(publicMember);
  10251. if (method.key.type === "PrivateName") {
  10252. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  10253. } else {
  10254. if (this.isNonstaticConstructor(publicMethod)) {
  10255. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  10256. }
  10257. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  10258. }
  10259. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  10260. method.kind = key.name;
  10261. this.parseClassElementName(publicMethod);
  10262. if (method.key.type === "PrivateName") {
  10263. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10264. } else {
  10265. if (this.isNonstaticConstructor(publicMethod)) {
  10266. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  10267. }
  10268. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  10269. }
  10270. this.checkGetterSetterParams(publicMethod);
  10271. } else if (this.isLineTerminator()) {
  10272. if (isPrivate) {
  10273. this.pushClassPrivateProperty(classBody, privateProp);
  10274. } else {
  10275. this.pushClassProperty(classBody, publicProp);
  10276. }
  10277. } else {
  10278. this.unexpected();
  10279. }
  10280. }
  10281. parseClassElementName(member) {
  10282. const key = this.parsePropertyName(member, true);
  10283. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  10284. this.raise(key.start, ErrorMessages.StaticPrototype);
  10285. }
  10286. if (key.type === "PrivateName" && key.id.name === "constructor") {
  10287. this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
  10288. }
  10289. return key;
  10290. }
  10291. parseClassStaticBlock(classBody, member, state) {
  10292. var _member$decorators;
  10293. this.expectPlugin("classStaticBlock", member.start);
  10294. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10295. this.expressionScope.enter(newExpressionScope());
  10296. const oldLabels = this.state.labels;
  10297. this.state.labels = [];
  10298. this.prodParam.enter(PARAM);
  10299. const body = member.body = [];
  10300. this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
  10301. this.prodParam.exit();
  10302. this.expressionScope.exit();
  10303. this.scope.exit();
  10304. this.state.labels = oldLabels;
  10305. classBody.body.push(this.finishNode(member, "StaticBlock"));
  10306. if (state.hadStaticBlock) {
  10307. this.raise(member.start, ErrorMessages.DuplicateStaticBlock);
  10308. }
  10309. if ((_member$decorators = member.decorators) == null ? void 0 : _member$decorators.length) {
  10310. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  10311. }
  10312. state.hadStaticBlock = true;
  10313. }
  10314. pushClassProperty(classBody, prop) {
  10315. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  10316. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  10317. }
  10318. classBody.body.push(this.parseClassProperty(prop));
  10319. }
  10320. pushClassPrivateProperty(classBody, prop) {
  10321. this.expectPlugin("classPrivateProperties", prop.key.start);
  10322. const node = this.parseClassPrivateProperty(prop);
  10323. classBody.body.push(node);
  10324. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  10325. }
  10326. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  10327. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  10328. }
  10329. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  10330. this.expectPlugin("classPrivateMethods", method.key.start);
  10331. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  10332. classBody.body.push(node);
  10333. 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;
  10334. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  10335. }
  10336. parsePostMemberNameModifiers(methodOrProp) {}
  10337. parseClassPrivateProperty(node) {
  10338. this.parseInitializer(node);
  10339. this.semicolon();
  10340. return this.finishNode(node, "ClassPrivateProperty");
  10341. }
  10342. parseClassProperty(node) {
  10343. if (!node.typeAnnotation || this.match(types.eq)) {
  10344. this.expectPlugin("classProperties");
  10345. }
  10346. this.parseInitializer(node);
  10347. this.semicolon();
  10348. return this.finishNode(node, "ClassProperty");
  10349. }
  10350. parseInitializer(node) {
  10351. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10352. this.expressionScope.enter(newExpressionScope());
  10353. this.prodParam.enter(PARAM);
  10354. node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
  10355. this.expressionScope.exit();
  10356. this.prodParam.exit();
  10357. this.scope.exit();
  10358. }
  10359. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  10360. if (this.match(types.name)) {
  10361. node.id = this.parseIdentifier();
  10362. if (isStatement) {
  10363. this.checkLVal(node.id, bindingType, undefined, "class name");
  10364. }
  10365. } else {
  10366. if (optionalId || !isStatement) {
  10367. node.id = null;
  10368. } else {
  10369. this.unexpected(null, ErrorMessages.MissingClassName);
  10370. }
  10371. }
  10372. }
  10373. parseClassSuper(node) {
  10374. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  10375. }
  10376. parseExport(node) {
  10377. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  10378. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  10379. const hasStar = parseAfterDefault && this.eatExportStar(node);
  10380. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  10381. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  10382. const isFromRequired = hasDefault || hasStar;
  10383. if (hasStar && !hasNamespace) {
  10384. if (hasDefault) this.unexpected();
  10385. this.parseExportFrom(node, true);
  10386. return this.finishNode(node, "ExportAllDeclaration");
  10387. }
  10388. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  10389. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  10390. throw this.unexpected(null, types.braceL);
  10391. }
  10392. let hasDeclaration;
  10393. if (isFromRequired || hasSpecifiers) {
  10394. hasDeclaration = false;
  10395. this.parseExportFrom(node, isFromRequired);
  10396. } else {
  10397. hasDeclaration = this.maybeParseExportDeclaration(node);
  10398. }
  10399. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  10400. this.checkExport(node, true, false, !!node.source);
  10401. return this.finishNode(node, "ExportNamedDeclaration");
  10402. }
  10403. if (this.eat(types._default)) {
  10404. node.declaration = this.parseExportDefaultExpression();
  10405. this.checkExport(node, true, true);
  10406. return this.finishNode(node, "ExportDefaultDeclaration");
  10407. }
  10408. throw this.unexpected(null, types.braceL);
  10409. }
  10410. eatExportStar(node) {
  10411. return this.eat(types.star);
  10412. }
  10413. maybeParseExportDefaultSpecifier(node) {
  10414. if (this.isExportDefaultSpecifier()) {
  10415. this.expectPlugin("exportDefaultFrom");
  10416. const specifier = this.startNode();
  10417. specifier.exported = this.parseIdentifier(true);
  10418. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10419. return true;
  10420. }
  10421. return false;
  10422. }
  10423. maybeParseExportNamespaceSpecifier(node) {
  10424. if (this.isContextual("as")) {
  10425. if (!node.specifiers) node.specifiers = [];
  10426. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  10427. this.next();
  10428. specifier.exported = this.parseModuleExportName();
  10429. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  10430. return true;
  10431. }
  10432. return false;
  10433. }
  10434. maybeParseExportNamedSpecifiers(node) {
  10435. if (this.match(types.braceL)) {
  10436. if (!node.specifiers) node.specifiers = [];
  10437. node.specifiers.push(...this.parseExportSpecifiers());
  10438. node.source = null;
  10439. node.declaration = null;
  10440. return true;
  10441. }
  10442. return false;
  10443. }
  10444. maybeParseExportDeclaration(node) {
  10445. if (this.shouldParseExportDeclaration()) {
  10446. node.specifiers = [];
  10447. node.source = null;
  10448. node.declaration = this.parseExportDeclaration(node);
  10449. return true;
  10450. }
  10451. return false;
  10452. }
  10453. isAsyncFunction() {
  10454. if (!this.isContextual("async")) return false;
  10455. const next = this.nextTokenStart();
  10456. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10457. }
  10458. parseExportDefaultExpression() {
  10459. const expr = this.startNode();
  10460. const isAsync = this.isAsyncFunction();
  10461. if (this.match(types._function) || isAsync) {
  10462. this.next();
  10463. if (isAsync) {
  10464. this.next();
  10465. }
  10466. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10467. } else if (this.match(types._class)) {
  10468. return this.parseClass(expr, true, true);
  10469. } else if (this.match(types.at)) {
  10470. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10471. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10472. }
  10473. this.parseDecorators(false);
  10474. return this.parseClass(expr, true, true);
  10475. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10476. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  10477. } else {
  10478. const res = this.parseMaybeAssignAllowIn();
  10479. this.semicolon();
  10480. return res;
  10481. }
  10482. }
  10483. parseExportDeclaration(node) {
  10484. return this.parseStatement(null);
  10485. }
  10486. isExportDefaultSpecifier() {
  10487. if (this.match(types.name)) {
  10488. const value = this.state.value;
  10489. if (value === "async" && !this.state.containsEsc || value === "let") {
  10490. return false;
  10491. }
  10492. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  10493. const l = this.lookahead();
  10494. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  10495. this.expectOnePlugin(["flow", "typescript"]);
  10496. return false;
  10497. }
  10498. }
  10499. } else if (!this.match(types._default)) {
  10500. return false;
  10501. }
  10502. const next = this.nextTokenStart();
  10503. const hasFrom = this.isUnparsedContextual(next, "from");
  10504. if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
  10505. return true;
  10506. }
  10507. if (this.match(types._default) && hasFrom) {
  10508. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  10509. return nextAfterFrom === 34 || nextAfterFrom === 39;
  10510. }
  10511. return false;
  10512. }
  10513. parseExportFrom(node, expect) {
  10514. if (this.eatContextual("from")) {
  10515. node.source = this.parseImportSource();
  10516. this.checkExport(node);
  10517. const assertions = this.maybeParseImportAssertions();
  10518. if (assertions) {
  10519. node.assertions = assertions;
  10520. }
  10521. } else {
  10522. if (expect) {
  10523. this.unexpected();
  10524. } else {
  10525. node.source = null;
  10526. }
  10527. }
  10528. this.semicolon();
  10529. }
  10530. shouldParseExportDeclaration() {
  10531. if (this.match(types.at)) {
  10532. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  10533. if (this.hasPlugin("decorators")) {
  10534. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10535. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10536. } else {
  10537. return true;
  10538. }
  10539. }
  10540. }
  10541. 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();
  10542. }
  10543. checkExport(node, checkNames, isDefault, isFrom) {
  10544. if (checkNames) {
  10545. if (isDefault) {
  10546. this.checkDuplicateExports(node, "default");
  10547. if (this.hasPlugin("exportDefaultFrom")) {
  10548. var _declaration$extra;
  10549. const declaration = node.declaration;
  10550. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) == null ? void 0 : _declaration$extra.parenthesized)) {
  10551. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  10552. }
  10553. }
  10554. } else if (node.specifiers && node.specifiers.length) {
  10555. for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
  10556. const specifier = _node$specifiers[_i4];
  10557. const {
  10558. exported
  10559. } = specifier;
  10560. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  10561. this.checkDuplicateExports(specifier, exportedName);
  10562. if (!isFrom && specifier.local) {
  10563. const {
  10564. local
  10565. } = specifier;
  10566. if (local.type === "StringLiteral") {
  10567. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.extra.raw, exportedName);
  10568. } else {
  10569. this.checkReservedWord(local.name, local.start, true, false);
  10570. this.scope.checkLocalExport(local);
  10571. }
  10572. }
  10573. }
  10574. } else if (node.declaration) {
  10575. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  10576. const id = node.declaration.id;
  10577. if (!id) throw new Error("Assertion failure");
  10578. this.checkDuplicateExports(node, id.name);
  10579. } else if (node.declaration.type === "VariableDeclaration") {
  10580. for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
  10581. const declaration = _node$declaration$dec[_i5];
  10582. this.checkDeclaration(declaration.id);
  10583. }
  10584. }
  10585. }
  10586. }
  10587. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10588. if (currentContextDecorators.length) {
  10589. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  10590. }
  10591. }
  10592. checkDeclaration(node) {
  10593. if (node.type === "Identifier") {
  10594. this.checkDuplicateExports(node, node.name);
  10595. } else if (node.type === "ObjectPattern") {
  10596. for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
  10597. const prop = _node$properties[_i6];
  10598. this.checkDeclaration(prop);
  10599. }
  10600. } else if (node.type === "ArrayPattern") {
  10601. for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
  10602. const elem = _node$elements[_i7];
  10603. if (elem) {
  10604. this.checkDeclaration(elem);
  10605. }
  10606. }
  10607. } else if (node.type === "ObjectProperty") {
  10608. this.checkDeclaration(node.value);
  10609. } else if (node.type === "RestElement") {
  10610. this.checkDeclaration(node.argument);
  10611. } else if (node.type === "AssignmentPattern") {
  10612. this.checkDeclaration(node.left);
  10613. }
  10614. }
  10615. checkDuplicateExports(node, name) {
  10616. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  10617. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  10618. }
  10619. this.state.exportedIdentifiers.push(name);
  10620. }
  10621. parseExportSpecifiers() {
  10622. const nodes = [];
  10623. let first = true;
  10624. this.expect(types.braceL);
  10625. while (!this.eat(types.braceR)) {
  10626. if (first) {
  10627. first = false;
  10628. } else {
  10629. this.expect(types.comma);
  10630. if (this.eat(types.braceR)) break;
  10631. }
  10632. const node = this.startNode();
  10633. node.local = this.parseModuleExportName();
  10634. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
  10635. nodes.push(this.finishNode(node, "ExportSpecifier"));
  10636. }
  10637. return nodes;
  10638. }
  10639. parseModuleExportName() {
  10640. if (this.match(types.string)) {
  10641. this.expectPlugin("moduleStringNames");
  10642. const result = this.parseLiteral(this.state.value, "StringLiteral");
  10643. const surrogate = result.value.match(loneSurrogate);
  10644. if (surrogate) {
  10645. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  10646. }
  10647. return result;
  10648. }
  10649. return this.parseIdentifier(true);
  10650. }
  10651. parseImport(node) {
  10652. node.specifiers = [];
  10653. if (!this.match(types.string)) {
  10654. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  10655. const parseNext = !hasDefault || this.eat(types.comma);
  10656. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  10657. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  10658. this.expectContextual("from");
  10659. }
  10660. node.source = this.parseImportSource();
  10661. const assertions = this.maybeParseImportAssertions();
  10662. if (assertions) {
  10663. node.assertions = assertions;
  10664. } else {
  10665. const attributes = this.maybeParseModuleAttributes();
  10666. if (attributes) {
  10667. node.attributes = attributes;
  10668. }
  10669. }
  10670. this.semicolon();
  10671. return this.finishNode(node, "ImportDeclaration");
  10672. }
  10673. parseImportSource() {
  10674. if (!this.match(types.string)) this.unexpected();
  10675. return this.parseExprAtom();
  10676. }
  10677. shouldParseDefaultImport(node) {
  10678. return this.match(types.name);
  10679. }
  10680. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  10681. specifier.local = this.parseIdentifier();
  10682. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  10683. node.specifiers.push(this.finishNode(specifier, type));
  10684. }
  10685. parseAssertEntries() {
  10686. const attrs = [];
  10687. const attrNames = new Set();
  10688. do {
  10689. if (this.match(types.braceR)) {
  10690. break;
  10691. }
  10692. const node = this.startNode();
  10693. const keyName = this.state.value;
  10694. if (this.match(types.string)) {
  10695. node.key = this.parseLiteral(keyName, "StringLiteral");
  10696. } else {
  10697. node.key = this.parseIdentifier(true);
  10698. }
  10699. this.expect(types.colon);
  10700. if (keyName !== "type") {
  10701. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName);
  10702. }
  10703. if (attrNames.has(keyName)) {
  10704. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  10705. }
  10706. attrNames.add(keyName);
  10707. if (!this.match(types.string)) {
  10708. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  10709. }
  10710. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  10711. this.finishNode(node, "ImportAttribute");
  10712. attrs.push(node);
  10713. } while (this.eat(types.comma));
  10714. return attrs;
  10715. }
  10716. maybeParseModuleAttributes() {
  10717. if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
  10718. this.expectPlugin("moduleAttributes");
  10719. this.next();
  10720. } else {
  10721. if (this.hasPlugin("moduleAttributes")) return [];
  10722. return null;
  10723. }
  10724. const attrs = [];
  10725. const attributes = new Set();
  10726. do {
  10727. const node = this.startNode();
  10728. node.key = this.parseIdentifier(true);
  10729. if (node.key.name !== "type") {
  10730. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  10731. }
  10732. if (attributes.has(node.key.name)) {
  10733. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  10734. }
  10735. attributes.add(node.key.name);
  10736. this.expect(types.colon);
  10737. if (!this.match(types.string)) {
  10738. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  10739. }
  10740. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  10741. this.finishNode(node, "ImportAttribute");
  10742. attrs.push(node);
  10743. } while (this.eat(types.comma));
  10744. return attrs;
  10745. }
  10746. maybeParseImportAssertions() {
  10747. if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) {
  10748. this.expectPlugin("importAssertions");
  10749. this.next();
  10750. } else {
  10751. if (this.hasPlugin("importAssertions")) return [];
  10752. return null;
  10753. }
  10754. this.eat(types.braceL);
  10755. const attrs = this.parseAssertEntries();
  10756. this.eat(types.braceR);
  10757. return attrs;
  10758. }
  10759. maybeParseDefaultImportSpecifier(node) {
  10760. if (this.shouldParseDefaultImport(node)) {
  10761. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  10762. return true;
  10763. }
  10764. return false;
  10765. }
  10766. maybeParseStarImportSpecifier(node) {
  10767. if (this.match(types.star)) {
  10768. const specifier = this.startNode();
  10769. this.next();
  10770. this.expectContextual("as");
  10771. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  10772. return true;
  10773. }
  10774. return false;
  10775. }
  10776. parseNamedImportSpecifiers(node) {
  10777. let first = true;
  10778. this.expect(types.braceL);
  10779. while (!this.eat(types.braceR)) {
  10780. if (first) {
  10781. first = false;
  10782. } else {
  10783. if (this.eat(types.colon)) {
  10784. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  10785. }
  10786. this.expect(types.comma);
  10787. if (this.eat(types.braceR)) break;
  10788. }
  10789. this.parseImportSpecifier(node);
  10790. }
  10791. }
  10792. parseImportSpecifier(node) {
  10793. const specifier = this.startNode();
  10794. specifier.imported = this.parseModuleExportName();
  10795. if (this.eatContextual("as")) {
  10796. specifier.local = this.parseIdentifier();
  10797. } else {
  10798. const {
  10799. imported
  10800. } = specifier;
  10801. if (imported.type === "StringLiteral") {
  10802. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  10803. }
  10804. this.checkReservedWord(imported.name, specifier.start, true, true);
  10805. specifier.local = imported.__clone();
  10806. }
  10807. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  10808. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  10809. }
  10810. }
  10811. class ClassScope {
  10812. constructor() {
  10813. this.privateNames = new Set();
  10814. this.loneAccessors = new Map();
  10815. this.undefinedPrivateNames = new Map();
  10816. }
  10817. }
  10818. class ClassScopeHandler {
  10819. constructor(raise) {
  10820. this.stack = [];
  10821. this.undefinedPrivateNames = new Map();
  10822. this.raise = raise;
  10823. }
  10824. current() {
  10825. return this.stack[this.stack.length - 1];
  10826. }
  10827. enter() {
  10828. this.stack.push(new ClassScope());
  10829. }
  10830. exit() {
  10831. const oldClassScope = this.stack.pop();
  10832. const current = this.current();
  10833. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  10834. const [name, pos] = _Array$from[_i];
  10835. if (current) {
  10836. if (!current.undefinedPrivateNames.has(name)) {
  10837. current.undefinedPrivateNames.set(name, pos);
  10838. }
  10839. } else {
  10840. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  10841. }
  10842. }
  10843. }
  10844. declarePrivateName(name, elementType, pos) {
  10845. const classScope = this.current();
  10846. let redefined = classScope.privateNames.has(name);
  10847. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  10848. const accessor = redefined && classScope.loneAccessors.get(name);
  10849. if (accessor) {
  10850. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  10851. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  10852. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  10853. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  10854. redefined = oldKind === newKind || oldStatic !== newStatic;
  10855. if (!redefined) classScope.loneAccessors.delete(name);
  10856. } else if (!redefined) {
  10857. classScope.loneAccessors.set(name, elementType);
  10858. }
  10859. }
  10860. if (redefined) {
  10861. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  10862. }
  10863. classScope.privateNames.add(name);
  10864. classScope.undefinedPrivateNames.delete(name);
  10865. }
  10866. usePrivateName(name, pos) {
  10867. let classScope;
  10868. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  10869. classScope = _this$stack[_i2];
  10870. if (classScope.privateNames.has(name)) return;
  10871. }
  10872. if (classScope) {
  10873. classScope.undefinedPrivateNames.set(name, pos);
  10874. } else {
  10875. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  10876. }
  10877. }
  10878. }
  10879. class Parser extends StatementParser {
  10880. constructor(options, input) {
  10881. options = getOptions(options);
  10882. super(options, input);
  10883. const ScopeHandler = this.getScopeHandler();
  10884. this.options = options;
  10885. this.inModule = this.options.sourceType === "module";
  10886. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  10887. this.prodParam = new ProductionParameterHandler();
  10888. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  10889. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  10890. this.plugins = pluginsMap(this.options.plugins);
  10891. this.filename = options.sourceFilename;
  10892. }
  10893. getScopeHandler() {
  10894. return ScopeHandler;
  10895. }
  10896. parse() {
  10897. let paramFlags = PARAM;
  10898. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  10899. paramFlags |= PARAM_AWAIT;
  10900. }
  10901. this.scope.enter(SCOPE_PROGRAM);
  10902. this.prodParam.enter(paramFlags);
  10903. const file = this.startNode();
  10904. const program = this.startNode();
  10905. this.nextToken();
  10906. file.errors = null;
  10907. this.parseTopLevel(file, program);
  10908. file.errors = this.state.errors;
  10909. return file;
  10910. }
  10911. }
  10912. function pluginsMap(plugins) {
  10913. const pluginMap = new Map();
  10914. for (let _i = 0; _i < plugins.length; _i++) {
  10915. const plugin = plugins[_i];
  10916. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  10917. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  10918. }
  10919. return pluginMap;
  10920. }
  10921. function parse(input, options) {
  10922. var _options;
  10923. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  10924. options = Object.assign({}, options);
  10925. try {
  10926. options.sourceType = "module";
  10927. const parser = getParser(options, input);
  10928. const ast = parser.parse();
  10929. if (parser.sawUnambiguousESM) {
  10930. return ast;
  10931. }
  10932. if (parser.ambiguousScriptDifferentAst) {
  10933. try {
  10934. options.sourceType = "script";
  10935. return getParser(options, input).parse();
  10936. } catch (_unused) {}
  10937. } else {
  10938. ast.program.sourceType = "script";
  10939. }
  10940. return ast;
  10941. } catch (moduleError) {
  10942. try {
  10943. options.sourceType = "script";
  10944. return getParser(options, input).parse();
  10945. } catch (_unused2) {}
  10946. throw moduleError;
  10947. }
  10948. } else {
  10949. return getParser(options, input).parse();
  10950. }
  10951. }
  10952. function parseExpression(input, options) {
  10953. const parser = getParser(options, input);
  10954. if (parser.options.strictMode) {
  10955. parser.state.strict = true;
  10956. }
  10957. return parser.getExpression();
  10958. }
  10959. function getParser(options, input) {
  10960. let cls = Parser;
  10961. if (options == null ? void 0 : options.plugins) {
  10962. validatePlugins(options.plugins);
  10963. cls = getParserClass(options.plugins);
  10964. }
  10965. return new cls(options, input);
  10966. }
  10967. const parserClassCache = {};
  10968. function getParserClass(pluginsFromOptions) {
  10969. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  10970. const key = pluginList.join("/");
  10971. let cls = parserClassCache[key];
  10972. if (!cls) {
  10973. cls = Parser;
  10974. for (let _i = 0; _i < pluginList.length; _i++) {
  10975. const plugin = pluginList[_i];
  10976. cls = mixinPlugins[plugin](cls);
  10977. }
  10978. parserClassCache[key] = cls;
  10979. }
  10980. return cls;
  10981. }
  10982. exports.parse = parse;
  10983. exports.parseExpression = parseExpression;
  10984. exports.tokTypes = types;
  10985. //# sourceMappingURL=index.js.map