index.js 357 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321
  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 = label;
  12. this.keyword = conf.keyword;
  13. this.beforeExpr = !!conf.beforeExpr;
  14. this.startsExpr = !!conf.startsExpr;
  15. this.rightAssociative = !!conf.rightAssociative;
  16. this.isLoop = !!conf.isLoop;
  17. this.isAssign = !!conf.isAssign;
  18. this.prefix = !!conf.prefix;
  19. this.postfix = !!conf.postfix;
  20. this.binop = conf.binop != null ? conf.binop : null;
  21. this.updateContext = null;
  22. }
  23. }
  24. const keywords = new Map();
  25. function createKeyword(name, options = {}) {
  26. options.keyword = name;
  27. const token = new TokenType(name, options);
  28. keywords.set(name, token);
  29. return token;
  30. }
  31. function createBinop(name, binop) {
  32. return new TokenType(name, {
  33. beforeExpr,
  34. binop
  35. });
  36. }
  37. const types = {
  38. num: new TokenType("num", {
  39. startsExpr
  40. }),
  41. bigint: new TokenType("bigint", {
  42. startsExpr
  43. }),
  44. regexp: new TokenType("regexp", {
  45. startsExpr
  46. }),
  47. string: new TokenType("string", {
  48. startsExpr
  49. }),
  50. name: new TokenType("name", {
  51. startsExpr
  52. }),
  53. eof: new TokenType("eof"),
  54. bracketL: new TokenType("[", {
  55. beforeExpr,
  56. startsExpr
  57. }),
  58. bracketR: new TokenType("]"),
  59. braceL: new TokenType("{", {
  60. beforeExpr,
  61. startsExpr
  62. }),
  63. braceBarL: new TokenType("{|", {
  64. beforeExpr,
  65. startsExpr
  66. }),
  67. braceR: new TokenType("}"),
  68. braceBarR: new TokenType("|}"),
  69. parenL: new TokenType("(", {
  70. beforeExpr,
  71. startsExpr
  72. }),
  73. parenR: new TokenType(")"),
  74. comma: new TokenType(",", {
  75. beforeExpr
  76. }),
  77. semi: new TokenType(";", {
  78. beforeExpr
  79. }),
  80. colon: new TokenType(":", {
  81. beforeExpr
  82. }),
  83. doubleColon: new TokenType("::", {
  84. beforeExpr
  85. }),
  86. dot: new TokenType("."),
  87. question: new TokenType("?", {
  88. beforeExpr
  89. }),
  90. questionDot: new TokenType("?."),
  91. arrow: new TokenType("=>", {
  92. beforeExpr
  93. }),
  94. template: new TokenType("template"),
  95. ellipsis: new TokenType("...", {
  96. beforeExpr
  97. }),
  98. backQuote: new TokenType("`", {
  99. startsExpr
  100. }),
  101. dollarBraceL: new TokenType("${", {
  102. beforeExpr,
  103. startsExpr
  104. }),
  105. at: new TokenType("@"),
  106. hash: new TokenType("#", {
  107. startsExpr
  108. }),
  109. interpreterDirective: new TokenType("#!..."),
  110. eq: new TokenType("=", {
  111. beforeExpr,
  112. isAssign
  113. }),
  114. assign: new TokenType("_=", {
  115. beforeExpr,
  116. isAssign
  117. }),
  118. incDec: new TokenType("++/--", {
  119. prefix,
  120. postfix,
  121. startsExpr
  122. }),
  123. bang: new TokenType("!", {
  124. beforeExpr,
  125. prefix,
  126. startsExpr
  127. }),
  128. tilde: new TokenType("~", {
  129. beforeExpr,
  130. prefix,
  131. startsExpr
  132. }),
  133. pipeline: createBinop("|>", 0),
  134. nullishCoalescing: createBinop("??", 1),
  135. logicalOR: createBinop("||", 1),
  136. logicalAND: createBinop("&&", 2),
  137. bitwiseOR: createBinop("|", 3),
  138. bitwiseXOR: createBinop("^", 4),
  139. bitwiseAND: createBinop("&", 5),
  140. equality: createBinop("==/!=/===/!==", 6),
  141. relational: createBinop("</>/<=/>=", 7),
  142. bitShift: createBinop("<</>>/>>>", 8),
  143. plusMin: new TokenType("+/-", {
  144. beforeExpr,
  145. binop: 9,
  146. prefix,
  147. startsExpr
  148. }),
  149. modulo: new TokenType("%", {
  150. beforeExpr,
  151. binop: 10,
  152. startsExpr
  153. }),
  154. star: createBinop("*", 10),
  155. slash: createBinop("/", 10),
  156. exponent: new TokenType("**", {
  157. beforeExpr,
  158. binop: 11,
  159. rightAssociative: true
  160. }),
  161. _break: createKeyword("break"),
  162. _case: createKeyword("case", {
  163. beforeExpr
  164. }),
  165. _catch: createKeyword("catch"),
  166. _continue: createKeyword("continue"),
  167. _debugger: createKeyword("debugger"),
  168. _default: createKeyword("default", {
  169. beforeExpr
  170. }),
  171. _do: createKeyword("do", {
  172. isLoop,
  173. beforeExpr
  174. }),
  175. _else: createKeyword("else", {
  176. beforeExpr
  177. }),
  178. _finally: createKeyword("finally"),
  179. _for: createKeyword("for", {
  180. isLoop
  181. }),
  182. _function: createKeyword("function", {
  183. startsExpr
  184. }),
  185. _if: createKeyword("if"),
  186. _return: createKeyword("return", {
  187. beforeExpr
  188. }),
  189. _switch: createKeyword("switch"),
  190. _throw: createKeyword("throw", {
  191. beforeExpr,
  192. prefix,
  193. startsExpr
  194. }),
  195. _try: createKeyword("try"),
  196. _var: createKeyword("var"),
  197. _const: createKeyword("const"),
  198. _while: createKeyword("while", {
  199. isLoop
  200. }),
  201. _with: createKeyword("with"),
  202. _new: createKeyword("new", {
  203. beforeExpr,
  204. startsExpr
  205. }),
  206. _this: createKeyword("this", {
  207. startsExpr
  208. }),
  209. _super: createKeyword("super", {
  210. startsExpr
  211. }),
  212. _class: createKeyword("class", {
  213. startsExpr
  214. }),
  215. _extends: createKeyword("extends", {
  216. beforeExpr
  217. }),
  218. _export: createKeyword("export"),
  219. _import: createKeyword("import", {
  220. startsExpr
  221. }),
  222. _null: createKeyword("null", {
  223. startsExpr
  224. }),
  225. _true: createKeyword("true", {
  226. startsExpr
  227. }),
  228. _false: createKeyword("false", {
  229. startsExpr
  230. }),
  231. _in: createKeyword("in", {
  232. beforeExpr,
  233. binop: 7
  234. }),
  235. _instanceof: createKeyword("instanceof", {
  236. beforeExpr,
  237. binop: 7
  238. }),
  239. _typeof: createKeyword("typeof", {
  240. beforeExpr,
  241. prefix,
  242. startsExpr
  243. }),
  244. _void: createKeyword("void", {
  245. beforeExpr,
  246. prefix,
  247. startsExpr
  248. }),
  249. _delete: createKeyword("delete", {
  250. beforeExpr,
  251. prefix,
  252. startsExpr
  253. })
  254. };
  255. const SCOPE_OTHER = 0b0000000000,
  256. SCOPE_PROGRAM = 0b0000000001,
  257. SCOPE_FUNCTION = 0b0000000010,
  258. SCOPE_ASYNC = 0b0000000100,
  259. SCOPE_GENERATOR = 0b0000001000,
  260. SCOPE_ARROW = 0b0000010000,
  261. SCOPE_SIMPLE_CATCH = 0b0000100000,
  262. SCOPE_SUPER = 0b0001000000,
  263. SCOPE_DIRECT_SUPER = 0b0010000000,
  264. SCOPE_CLASS = 0b0100000000,
  265. SCOPE_TS_MODULE = 0b1000000000,
  266. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  267. function functionFlags(isAsync, isGenerator) {
  268. return SCOPE_FUNCTION | (isAsync ? SCOPE_ASYNC : 0) | (isGenerator ? SCOPE_GENERATOR : 0);
  269. }
  270. const BIND_KIND_VALUE = 0b00000000001,
  271. BIND_KIND_TYPE = 0b00000000010,
  272. BIND_SCOPE_VAR = 0b00000000100,
  273. BIND_SCOPE_LEXICAL = 0b00000001000,
  274. BIND_SCOPE_FUNCTION = 0b00000010000,
  275. BIND_FLAGS_NONE = 0b00001000000,
  276. BIND_FLAGS_CLASS = 0b00010000000,
  277. BIND_FLAGS_TS_ENUM = 0b00100000000,
  278. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  279. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  280. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  281. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  282. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  283. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  284. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  285. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  286. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  287. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  288. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  289. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  290. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  291. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  292. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  293. CLASS_ELEMENT_KIND_GETTER = 0b010,
  294. CLASS_ELEMENT_KIND_SETTER = 0b001,
  295. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  296. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  297. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  298. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  299. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  300. CLASS_ELEMENT_OTHER = 0;
  301. function isSimpleProperty(node) {
  302. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  303. }
  304. var estree = (superClass => class extends superClass {
  305. estreeParseRegExpLiteral({
  306. pattern,
  307. flags
  308. }) {
  309. let regex = null;
  310. try {
  311. regex = new RegExp(pattern, flags);
  312. } catch (e) {}
  313. const node = this.estreeParseLiteral(regex);
  314. node.regex = {
  315. pattern,
  316. flags
  317. };
  318. return node;
  319. }
  320. estreeParseBigIntLiteral(value) {
  321. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  322. const node = this.estreeParseLiteral(bigInt);
  323. node.bigint = String(node.value || value);
  324. return node;
  325. }
  326. estreeParseLiteral(value) {
  327. return this.parseLiteral(value, "Literal");
  328. }
  329. directiveToStmt(directive) {
  330. const directiveLiteral = directive.value;
  331. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  332. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  333. expression.value = directiveLiteral.value;
  334. expression.raw = directiveLiteral.extra.raw;
  335. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  336. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  337. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  338. }
  339. initFunction(node, isAsync) {
  340. super.initFunction(node, isAsync);
  341. node.expression = false;
  342. }
  343. checkDeclaration(node) {
  344. if (isSimpleProperty(node)) {
  345. this.checkDeclaration(node.value);
  346. } else {
  347. super.checkDeclaration(node);
  348. }
  349. }
  350. checkGetterSetterParams(method) {
  351. const prop = method;
  352. const paramCount = prop.kind === "get" ? 0 : 1;
  353. const start = prop.start;
  354. if (prop.value.params.length !== paramCount) {
  355. if (prop.kind === "get") {
  356. this.raise(start, "getter must not have any formal parameters");
  357. } else {
  358. this.raise(start, "setter must have exactly one formal parameter");
  359. }
  360. } else if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
  361. this.raise(start, "setter function argument must not be a rest parameter");
  362. }
  363. }
  364. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding) {
  365. switch (expr.type) {
  366. case "ObjectPattern":
  367. expr.properties.forEach(prop => {
  368. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  369. });
  370. break;
  371. default:
  372. super.checkLVal(expr, bindingType, checkClashes, contextDescription, disallowLetBinding);
  373. }
  374. }
  375. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  376. if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) {
  377. return;
  378. }
  379. const key = prop.key;
  380. const name = key.type === "Identifier" ? key.name : String(key.value);
  381. if (name === "__proto__" && prop.kind === "init") {
  382. if (protoRef.used) {
  383. if (refExpressionErrors && refExpressionErrors.doubleProto === -1) {
  384. refExpressionErrors.doubleProto = key.start;
  385. } else {
  386. this.raise(key.start, "Redefinition of __proto__ property");
  387. }
  388. }
  389. protoRef.used = true;
  390. }
  391. }
  392. isValidDirective(stmt) {
  393. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized);
  394. }
  395. stmtToDirective(stmt) {
  396. const directive = super.stmtToDirective(stmt);
  397. const value = stmt.expression.value;
  398. directive.value.value = value;
  399. return directive;
  400. }
  401. parseBlockBody(node, allowDirectives, topLevel, end) {
  402. super.parseBlockBody(node, allowDirectives, topLevel, end);
  403. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  404. node.body = directiveStatements.concat(node.body);
  405. delete node.directives;
  406. }
  407. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  408. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  409. if (method.typeParameters) {
  410. method.value.typeParameters = method.typeParameters;
  411. delete method.typeParameters;
  412. }
  413. classBody.body.push(method);
  414. }
  415. parseExprAtom(refExpressionErrors) {
  416. switch (this.state.type) {
  417. case types.num:
  418. case types.string:
  419. return this.estreeParseLiteral(this.state.value);
  420. case types.regexp:
  421. return this.estreeParseRegExpLiteral(this.state.value);
  422. case types.bigint:
  423. return this.estreeParseBigIntLiteral(this.state.value);
  424. case types._null:
  425. return this.estreeParseLiteral(null);
  426. case types._true:
  427. return this.estreeParseLiteral(true);
  428. case types._false:
  429. return this.estreeParseLiteral(false);
  430. default:
  431. return super.parseExprAtom(refExpressionErrors);
  432. }
  433. }
  434. parseLiteral(value, type, startPos, startLoc) {
  435. const node = super.parseLiteral(value, type, startPos, startLoc);
  436. node.raw = node.extra.raw;
  437. delete node.extra;
  438. return node;
  439. }
  440. parseFunctionBody(node, allowExpression, isMethod = false) {
  441. super.parseFunctionBody(node, allowExpression, isMethod);
  442. node.expression = node.body.type !== "BlockStatement";
  443. }
  444. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  445. let funcNode = this.startNode();
  446. funcNode.kind = node.kind;
  447. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  448. funcNode.type = "FunctionExpression";
  449. delete funcNode.kind;
  450. node.value = funcNode;
  451. type = type === "ClassMethod" ? "MethodDefinition" : type;
  452. return this.finishNode(node, type);
  453. }
  454. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  455. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc);
  456. if (node) {
  457. node.type = "Property";
  458. if (node.kind === "method") node.kind = "init";
  459. node.shorthand = false;
  460. }
  461. return node;
  462. }
  463. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  464. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  465. if (node) {
  466. node.kind = "init";
  467. node.type = "Property";
  468. }
  469. return node;
  470. }
  471. toAssignable(node) {
  472. if (isSimpleProperty(node)) {
  473. this.toAssignable(node.value);
  474. return node;
  475. }
  476. return super.toAssignable(node);
  477. }
  478. toAssignableObjectExpressionProp(prop, isLast) {
  479. if (prop.kind === "get" || prop.kind === "set") {
  480. throw this.raise(prop.key.start, "Object pattern can't contain getter or setter");
  481. } else if (prop.method) {
  482. throw this.raise(prop.key.start, "Object pattern can't contain methods");
  483. } else {
  484. super.toAssignableObjectExpressionProp(prop, isLast);
  485. }
  486. }
  487. finishCallExpression(node, optional) {
  488. super.finishCallExpression(node, optional);
  489. if (node.callee.type === "Import") {
  490. node.type = "ImportExpression";
  491. node.source = node.arguments[0];
  492. delete node.arguments;
  493. delete node.callee;
  494. }
  495. return node;
  496. }
  497. toReferencedListDeep(exprList, isParenthesizedExpr) {
  498. if (!exprList) {
  499. return;
  500. }
  501. super.toReferencedListDeep(exprList, isParenthesizedExpr);
  502. }
  503. });
  504. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  505. const lineBreakG = new RegExp(lineBreak.source, "g");
  506. function isNewLine(code) {
  507. switch (code) {
  508. case 10:
  509. case 13:
  510. case 8232:
  511. case 8233:
  512. return true;
  513. default:
  514. return false;
  515. }
  516. }
  517. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  518. function isWhitespace(code) {
  519. switch (code) {
  520. case 0x0009:
  521. case 0x000b:
  522. case 0x000c:
  523. case 32:
  524. case 160:
  525. case 5760:
  526. case 0x2000:
  527. case 0x2001:
  528. case 0x2002:
  529. case 0x2003:
  530. case 0x2004:
  531. case 0x2005:
  532. case 0x2006:
  533. case 0x2007:
  534. case 0x2008:
  535. case 0x2009:
  536. case 0x200a:
  537. case 0x202f:
  538. case 0x205f:
  539. case 0x3000:
  540. case 0xfeff:
  541. return true;
  542. default:
  543. return false;
  544. }
  545. }
  546. class TokContext {
  547. constructor(token, isExpr, preserveSpace, override) {
  548. this.token = token;
  549. this.isExpr = !!isExpr;
  550. this.preserveSpace = !!preserveSpace;
  551. this.override = override;
  552. }
  553. }
  554. const types$1 = {
  555. braceStatement: new TokContext("{", false),
  556. braceExpression: new TokContext("{", true),
  557. templateQuasi: new TokContext("${", false),
  558. parenStatement: new TokContext("(", false),
  559. parenExpression: new TokContext("(", true),
  560. template: new TokContext("`", true, true, p => p.readTmplToken()),
  561. functionExpression: new TokContext("function", true),
  562. functionStatement: new TokContext("function", false)
  563. };
  564. types.parenR.updateContext = types.braceR.updateContext = function () {
  565. if (this.state.context.length === 1) {
  566. this.state.exprAllowed = true;
  567. return;
  568. }
  569. let out = this.state.context.pop();
  570. if (out === types$1.braceStatement && this.curContext().token === "function") {
  571. out = this.state.context.pop();
  572. }
  573. this.state.exprAllowed = !out.isExpr;
  574. };
  575. types.name.updateContext = function (prevType) {
  576. let allowed = false;
  577. if (prevType !== types.dot) {
  578. if (this.state.value === "of" && !this.state.exprAllowed || this.state.value === "yield" && this.scope.inGenerator) {
  579. allowed = true;
  580. }
  581. }
  582. this.state.exprAllowed = allowed;
  583. if (this.state.isIterator) {
  584. this.state.isIterator = false;
  585. }
  586. };
  587. types.braceL.updateContext = function (prevType) {
  588. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  589. this.state.exprAllowed = true;
  590. };
  591. types.dollarBraceL.updateContext = function () {
  592. this.state.context.push(types$1.templateQuasi);
  593. this.state.exprAllowed = true;
  594. };
  595. types.parenL.updateContext = function (prevType) {
  596. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  597. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  598. this.state.exprAllowed = true;
  599. };
  600. types.incDec.updateContext = function () {};
  601. types._function.updateContext = types._class.updateContext = function (prevType) {
  602. if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
  603. this.state.context.push(types$1.functionExpression);
  604. } else {
  605. this.state.context.push(types$1.functionStatement);
  606. }
  607. this.state.exprAllowed = false;
  608. };
  609. types.backQuote.updateContext = function () {
  610. if (this.curContext() === types$1.template) {
  611. this.state.context.pop();
  612. } else {
  613. this.state.context.push(types$1.template);
  614. }
  615. this.state.exprAllowed = false;
  616. };
  617. const reservedWords = {
  618. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  619. strictBind: ["eval", "arguments"]
  620. };
  621. const reservedWordsStrictSet = new Set(reservedWords.strict);
  622. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  623. const isReservedWord = (word, inModule) => {
  624. return inModule && word === "await" || word === "enum";
  625. };
  626. function isStrictReservedWord(word, inModule) {
  627. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  628. }
  629. function isStrictBindOnlyReservedWord(word) {
  630. return reservedWordsStrictBindSet.has(word);
  631. }
  632. function isStrictBindReservedWord(word, inModule) {
  633. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  634. }
  635. function isKeyword(word) {
  636. return keywords.has(word);
  637. }
  638. const keywordRelationalOperator = /^in(stanceof)?$/;
  639. 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-\u08bd\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\u0d05-\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-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\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-\uab67\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";
  640. 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\u0b56\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\u0d82\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\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\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";
  641. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  642. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  643. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  644. 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, 477, 28, 11, 0, 9, 21, 155, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 12, 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, 0, 33, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 0, 161, 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, 270, 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, 754, 9486, 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, 42710, 42, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541];
  645. 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, 525, 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, 4, 9, 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, 232, 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, 19723, 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, 792487, 239];
  646. function isInAstralSet(code, set) {
  647. let pos = 0x10000;
  648. for (let i = 0, length = set.length; i < length; i += 2) {
  649. pos += set[i];
  650. if (pos > code) return false;
  651. pos += set[i + 1];
  652. if (pos >= code) return true;
  653. }
  654. return false;
  655. }
  656. function isIdentifierStart(code) {
  657. if (code < 65) return code === 36;
  658. if (code <= 90) return true;
  659. if (code < 97) return code === 95;
  660. if (code <= 122) return true;
  661. if (code <= 0xffff) {
  662. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  663. }
  664. return isInAstralSet(code, astralIdentifierStartCodes);
  665. }
  666. function isIteratorStart(current, next) {
  667. return current === 64 && next === 64;
  668. }
  669. function isIdentifierChar(code) {
  670. if (code < 48) return code === 36;
  671. if (code < 58) return true;
  672. if (code < 65) return false;
  673. if (code <= 90) return true;
  674. if (code < 97) return code === 95;
  675. if (code <= 122) return true;
  676. if (code <= 0xffff) {
  677. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  678. }
  679. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  680. }
  681. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  682. function isEsModuleType(bodyElement) {
  683. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  684. }
  685. function hasTypeImportKind(node) {
  686. return node.importKind === "type" || node.importKind === "typeof";
  687. }
  688. function isMaybeDefaultImport(state) {
  689. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  690. }
  691. const exportSuggestions = {
  692. const: "declare export var",
  693. let: "declare export var",
  694. type: "export type",
  695. interface: "export interface"
  696. };
  697. function partition(list, test) {
  698. const list1 = [];
  699. const list2 = [];
  700. for (let i = 0; i < list.length; i++) {
  701. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  702. }
  703. return [list1, list2];
  704. }
  705. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  706. var flow = (superClass => class extends superClass {
  707. constructor(options, input) {
  708. super(options, input);
  709. this.flowPragma = undefined;
  710. }
  711. shouldParseTypes() {
  712. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  713. }
  714. shouldParseEnums() {
  715. return !!this.getPluginOption("flow", "enums");
  716. }
  717. finishToken(type, val) {
  718. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  719. if (this.flowPragma === undefined) {
  720. this.flowPragma = null;
  721. }
  722. }
  723. return super.finishToken(type, val);
  724. }
  725. addComment(comment) {
  726. if (this.flowPragma === undefined) {
  727. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  728. if (!matches) ; else if (matches[1] === "flow") {
  729. this.flowPragma = "flow";
  730. } else if (matches[1] === "noflow") {
  731. this.flowPragma = "noflow";
  732. } else {
  733. throw new Error("Unexpected flow pragma");
  734. }
  735. }
  736. return super.addComment(comment);
  737. }
  738. flowParseTypeInitialiser(tok) {
  739. const oldInType = this.state.inType;
  740. this.state.inType = true;
  741. this.expect(tok || types.colon);
  742. const type = this.flowParseType();
  743. this.state.inType = oldInType;
  744. return type;
  745. }
  746. flowParsePredicate() {
  747. const node = this.startNode();
  748. const moduloLoc = this.state.startLoc;
  749. const moduloPos = this.state.start;
  750. this.expect(types.modulo);
  751. const checksLoc = this.state.startLoc;
  752. this.expectContextual("checks");
  753. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  754. this.raise(moduloPos, "Spaces between ´%´ and ´checks´ are not allowed here.");
  755. }
  756. if (this.eat(types.parenL)) {
  757. node.value = this.parseExpression();
  758. this.expect(types.parenR);
  759. return this.finishNode(node, "DeclaredPredicate");
  760. } else {
  761. return this.finishNode(node, "InferredPredicate");
  762. }
  763. }
  764. flowParseTypeAndPredicateInitialiser() {
  765. const oldInType = this.state.inType;
  766. this.state.inType = true;
  767. this.expect(types.colon);
  768. let type = null;
  769. let predicate = null;
  770. if (this.match(types.modulo)) {
  771. this.state.inType = oldInType;
  772. predicate = this.flowParsePredicate();
  773. } else {
  774. type = this.flowParseType();
  775. this.state.inType = oldInType;
  776. if (this.match(types.modulo)) {
  777. predicate = this.flowParsePredicate();
  778. }
  779. }
  780. return [type, predicate];
  781. }
  782. flowParseDeclareClass(node) {
  783. this.next();
  784. this.flowParseInterfaceish(node, true);
  785. return this.finishNode(node, "DeclareClass");
  786. }
  787. flowParseDeclareFunction(node) {
  788. this.next();
  789. const id = node.id = this.parseIdentifier();
  790. const typeNode = this.startNode();
  791. const typeContainer = this.startNode();
  792. if (this.isRelational("<")) {
  793. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  794. } else {
  795. typeNode.typeParameters = null;
  796. }
  797. this.expect(types.parenL);
  798. const tmp = this.flowParseFunctionTypeParams();
  799. typeNode.params = tmp.params;
  800. typeNode.rest = tmp.rest;
  801. this.expect(types.parenR);
  802. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  803. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  804. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  805. this.resetEndLocation(id);
  806. this.semicolon();
  807. return this.finishNode(node, "DeclareFunction");
  808. }
  809. flowParseDeclare(node, insideModule) {
  810. if (this.match(types._class)) {
  811. return this.flowParseDeclareClass(node);
  812. } else if (this.match(types._function)) {
  813. return this.flowParseDeclareFunction(node);
  814. } else if (this.match(types._var)) {
  815. return this.flowParseDeclareVariable(node);
  816. } else if (this.eatContextual("module")) {
  817. if (this.match(types.dot)) {
  818. return this.flowParseDeclareModuleExports(node);
  819. } else {
  820. if (insideModule) {
  821. this.raise(this.state.lastTokStart, "`declare module` cannot be used inside another `declare module`");
  822. }
  823. return this.flowParseDeclareModule(node);
  824. }
  825. } else if (this.isContextual("type")) {
  826. return this.flowParseDeclareTypeAlias(node);
  827. } else if (this.isContextual("opaque")) {
  828. return this.flowParseDeclareOpaqueType(node);
  829. } else if (this.isContextual("interface")) {
  830. return this.flowParseDeclareInterface(node);
  831. } else if (this.match(types._export)) {
  832. return this.flowParseDeclareExportDeclaration(node, insideModule);
  833. } else {
  834. throw this.unexpected();
  835. }
  836. }
  837. flowParseDeclareVariable(node) {
  838. this.next();
  839. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  840. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  841. this.semicolon();
  842. return this.finishNode(node, "DeclareVariable");
  843. }
  844. flowParseDeclareModule(node) {
  845. this.scope.enter(SCOPE_OTHER);
  846. if (this.match(types.string)) {
  847. node.id = this.parseExprAtom();
  848. } else {
  849. node.id = this.parseIdentifier();
  850. }
  851. const bodyNode = node.body = this.startNode();
  852. const body = bodyNode.body = [];
  853. this.expect(types.braceL);
  854. while (!this.match(types.braceR)) {
  855. let bodyNode = this.startNode();
  856. if (this.match(types._import)) {
  857. this.next();
  858. if (!this.isContextual("type") && !this.match(types._typeof)) {
  859. this.raise(this.state.lastTokStart, "Imports within a `declare module` body must always be `import type` or `import typeof`");
  860. }
  861. this.parseImport(bodyNode);
  862. } else {
  863. this.expectContextual("declare", "Only declares and type imports are allowed inside declare module");
  864. bodyNode = this.flowParseDeclare(bodyNode, true);
  865. }
  866. body.push(bodyNode);
  867. }
  868. this.scope.exit();
  869. this.expect(types.braceR);
  870. this.finishNode(bodyNode, "BlockStatement");
  871. let kind = null;
  872. let hasModuleExport = false;
  873. const errorMessage = "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";
  874. body.forEach(bodyElement => {
  875. if (isEsModuleType(bodyElement)) {
  876. if (kind === "CommonJS") {
  877. this.raise(bodyElement.start, errorMessage);
  878. }
  879. kind = "ES";
  880. } else if (bodyElement.type === "DeclareModuleExports") {
  881. if (hasModuleExport) {
  882. this.raise(bodyElement.start, "Duplicate `declare module.exports` statement");
  883. }
  884. if (kind === "ES") this.raise(bodyElement.start, errorMessage);
  885. kind = "CommonJS";
  886. hasModuleExport = true;
  887. }
  888. });
  889. node.kind = kind || "CommonJS";
  890. return this.finishNode(node, "DeclareModule");
  891. }
  892. flowParseDeclareExportDeclaration(node, insideModule) {
  893. this.expect(types._export);
  894. if (this.eat(types._default)) {
  895. if (this.match(types._function) || this.match(types._class)) {
  896. node.declaration = this.flowParseDeclare(this.startNode());
  897. } else {
  898. node.declaration = this.flowParseType();
  899. this.semicolon();
  900. }
  901. node.default = true;
  902. return this.finishNode(node, "DeclareExportDeclaration");
  903. } else {
  904. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  905. const label = this.state.value;
  906. const suggestion = exportSuggestions[label];
  907. this.unexpected(this.state.start, `\`declare export ${label}\` is not supported. Use \`${suggestion}\` instead`);
  908. }
  909. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  910. node.declaration = this.flowParseDeclare(this.startNode());
  911. node.default = false;
  912. return this.finishNode(node, "DeclareExportDeclaration");
  913. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  914. node = this.parseExport(node);
  915. if (node.type === "ExportNamedDeclaration") {
  916. node.type = "ExportDeclaration";
  917. node.default = false;
  918. delete node.exportKind;
  919. }
  920. node.type = "Declare" + node.type;
  921. return node;
  922. }
  923. }
  924. throw this.unexpected();
  925. }
  926. flowParseDeclareModuleExports(node) {
  927. this.next();
  928. this.expectContextual("exports");
  929. node.typeAnnotation = this.flowParseTypeAnnotation();
  930. this.semicolon();
  931. return this.finishNode(node, "DeclareModuleExports");
  932. }
  933. flowParseDeclareTypeAlias(node) {
  934. this.next();
  935. this.flowParseTypeAlias(node);
  936. node.type = "DeclareTypeAlias";
  937. return node;
  938. }
  939. flowParseDeclareOpaqueType(node) {
  940. this.next();
  941. this.flowParseOpaqueType(node, true);
  942. node.type = "DeclareOpaqueType";
  943. return node;
  944. }
  945. flowParseDeclareInterface(node) {
  946. this.next();
  947. this.flowParseInterfaceish(node);
  948. return this.finishNode(node, "DeclareInterface");
  949. }
  950. flowParseInterfaceish(node, isClass = false) {
  951. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  952. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  953. if (this.isRelational("<")) {
  954. node.typeParameters = this.flowParseTypeParameterDeclaration();
  955. } else {
  956. node.typeParameters = null;
  957. }
  958. node.extends = [];
  959. node.implements = [];
  960. node.mixins = [];
  961. if (this.eat(types._extends)) {
  962. do {
  963. node.extends.push(this.flowParseInterfaceExtends());
  964. } while (!isClass && this.eat(types.comma));
  965. }
  966. if (this.isContextual("mixins")) {
  967. this.next();
  968. do {
  969. node.mixins.push(this.flowParseInterfaceExtends());
  970. } while (this.eat(types.comma));
  971. }
  972. if (this.isContextual("implements")) {
  973. this.next();
  974. do {
  975. node.implements.push(this.flowParseInterfaceExtends());
  976. } while (this.eat(types.comma));
  977. }
  978. node.body = this.flowParseObjectType({
  979. allowStatic: isClass,
  980. allowExact: false,
  981. allowSpread: false,
  982. allowProto: isClass,
  983. allowInexact: false
  984. });
  985. }
  986. flowParseInterfaceExtends() {
  987. const node = this.startNode();
  988. node.id = this.flowParseQualifiedTypeIdentifier();
  989. if (this.isRelational("<")) {
  990. node.typeParameters = this.flowParseTypeParameterInstantiation();
  991. } else {
  992. node.typeParameters = null;
  993. }
  994. return this.finishNode(node, "InterfaceExtends");
  995. }
  996. flowParseInterface(node) {
  997. this.flowParseInterfaceish(node);
  998. return this.finishNode(node, "InterfaceDeclaration");
  999. }
  1000. checkNotUnderscore(word) {
  1001. if (word === "_") {
  1002. this.raise(this.state.start, "`_` is only allowed as a type argument to call or new");
  1003. }
  1004. }
  1005. checkReservedType(word, startLoc, declaration) {
  1006. if (!reservedTypes.has(word)) return;
  1007. if (declaration) {
  1008. this.raise(startLoc, `Cannot overwrite reserved type ${word}`);
  1009. return;
  1010. }
  1011. this.raise(startLoc, `Unexpected reserved type ${word}`);
  1012. }
  1013. flowParseRestrictedIdentifier(liberal, declaration) {
  1014. this.checkReservedType(this.state.value, this.state.start, declaration);
  1015. return this.parseIdentifier(liberal);
  1016. }
  1017. flowParseTypeAlias(node) {
  1018. node.id = this.flowParseRestrictedIdentifier(false, true);
  1019. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1020. if (this.isRelational("<")) {
  1021. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1022. } else {
  1023. node.typeParameters = null;
  1024. }
  1025. node.right = this.flowParseTypeInitialiser(types.eq);
  1026. this.semicolon();
  1027. return this.finishNode(node, "TypeAlias");
  1028. }
  1029. flowParseOpaqueType(node, declare) {
  1030. this.expectContextual("type");
  1031. node.id = this.flowParseRestrictedIdentifier(true, true);
  1032. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1033. if (this.isRelational("<")) {
  1034. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1035. } else {
  1036. node.typeParameters = null;
  1037. }
  1038. node.supertype = null;
  1039. if (this.match(types.colon)) {
  1040. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1041. }
  1042. node.impltype = null;
  1043. if (!declare) {
  1044. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1045. }
  1046. this.semicolon();
  1047. return this.finishNode(node, "OpaqueType");
  1048. }
  1049. flowParseTypeParameter(requireDefault = false) {
  1050. const nodeStart = this.state.start;
  1051. const node = this.startNode();
  1052. const variance = this.flowParseVariance();
  1053. const ident = this.flowParseTypeAnnotatableIdentifier();
  1054. node.name = ident.name;
  1055. node.variance = variance;
  1056. node.bound = ident.typeAnnotation;
  1057. if (this.match(types.eq)) {
  1058. this.eat(types.eq);
  1059. node.default = this.flowParseType();
  1060. } else {
  1061. if (requireDefault) {
  1062. this.raise(nodeStart, "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.");
  1063. }
  1064. }
  1065. return this.finishNode(node, "TypeParameter");
  1066. }
  1067. flowParseTypeParameterDeclaration() {
  1068. const oldInType = this.state.inType;
  1069. const node = this.startNode();
  1070. node.params = [];
  1071. this.state.inType = true;
  1072. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1073. this.next();
  1074. } else {
  1075. this.unexpected();
  1076. }
  1077. let defaultRequired = false;
  1078. do {
  1079. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1080. node.params.push(typeParameter);
  1081. if (typeParameter.default) {
  1082. defaultRequired = true;
  1083. }
  1084. if (!this.isRelational(">")) {
  1085. this.expect(types.comma);
  1086. }
  1087. } while (!this.isRelational(">"));
  1088. this.expectRelational(">");
  1089. this.state.inType = oldInType;
  1090. return this.finishNode(node, "TypeParameterDeclaration");
  1091. }
  1092. flowParseTypeParameterInstantiation() {
  1093. const node = this.startNode();
  1094. const oldInType = this.state.inType;
  1095. node.params = [];
  1096. this.state.inType = true;
  1097. this.expectRelational("<");
  1098. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1099. this.state.noAnonFunctionType = false;
  1100. while (!this.isRelational(">")) {
  1101. node.params.push(this.flowParseType());
  1102. if (!this.isRelational(">")) {
  1103. this.expect(types.comma);
  1104. }
  1105. }
  1106. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1107. this.expectRelational(">");
  1108. this.state.inType = oldInType;
  1109. return this.finishNode(node, "TypeParameterInstantiation");
  1110. }
  1111. flowParseTypeParameterInstantiationCallOrNew() {
  1112. const node = this.startNode();
  1113. const oldInType = this.state.inType;
  1114. node.params = [];
  1115. this.state.inType = true;
  1116. this.expectRelational("<");
  1117. while (!this.isRelational(">")) {
  1118. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1119. if (!this.isRelational(">")) {
  1120. this.expect(types.comma);
  1121. }
  1122. }
  1123. this.expectRelational(">");
  1124. this.state.inType = oldInType;
  1125. return this.finishNode(node, "TypeParameterInstantiation");
  1126. }
  1127. flowParseInterfaceType() {
  1128. const node = this.startNode();
  1129. this.expectContextual("interface");
  1130. node.extends = [];
  1131. if (this.eat(types._extends)) {
  1132. do {
  1133. node.extends.push(this.flowParseInterfaceExtends());
  1134. } while (this.eat(types.comma));
  1135. }
  1136. node.body = this.flowParseObjectType({
  1137. allowStatic: false,
  1138. allowExact: false,
  1139. allowSpread: false,
  1140. allowProto: false,
  1141. allowInexact: false
  1142. });
  1143. return this.finishNode(node, "InterfaceTypeAnnotation");
  1144. }
  1145. flowParseObjectPropertyKey() {
  1146. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1147. }
  1148. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1149. node.static = isStatic;
  1150. if (this.lookahead().type === types.colon) {
  1151. node.id = this.flowParseObjectPropertyKey();
  1152. node.key = this.flowParseTypeInitialiser();
  1153. } else {
  1154. node.id = null;
  1155. node.key = this.flowParseType();
  1156. }
  1157. this.expect(types.bracketR);
  1158. node.value = this.flowParseTypeInitialiser();
  1159. node.variance = variance;
  1160. return this.finishNode(node, "ObjectTypeIndexer");
  1161. }
  1162. flowParseObjectTypeInternalSlot(node, isStatic) {
  1163. node.static = isStatic;
  1164. node.id = this.flowParseObjectPropertyKey();
  1165. this.expect(types.bracketR);
  1166. this.expect(types.bracketR);
  1167. if (this.isRelational("<") || this.match(types.parenL)) {
  1168. node.method = true;
  1169. node.optional = false;
  1170. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1171. } else {
  1172. node.method = false;
  1173. if (this.eat(types.question)) {
  1174. node.optional = true;
  1175. }
  1176. node.value = this.flowParseTypeInitialiser();
  1177. }
  1178. return this.finishNode(node, "ObjectTypeInternalSlot");
  1179. }
  1180. flowParseObjectTypeMethodish(node) {
  1181. node.params = [];
  1182. node.rest = null;
  1183. node.typeParameters = null;
  1184. if (this.isRelational("<")) {
  1185. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1186. }
  1187. this.expect(types.parenL);
  1188. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1189. node.params.push(this.flowParseFunctionTypeParam());
  1190. if (!this.match(types.parenR)) {
  1191. this.expect(types.comma);
  1192. }
  1193. }
  1194. if (this.eat(types.ellipsis)) {
  1195. node.rest = this.flowParseFunctionTypeParam();
  1196. }
  1197. this.expect(types.parenR);
  1198. node.returnType = this.flowParseTypeInitialiser();
  1199. return this.finishNode(node, "FunctionTypeAnnotation");
  1200. }
  1201. flowParseObjectTypeCallProperty(node, isStatic) {
  1202. const valueNode = this.startNode();
  1203. node.static = isStatic;
  1204. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1205. return this.finishNode(node, "ObjectTypeCallProperty");
  1206. }
  1207. flowParseObjectType({
  1208. allowStatic,
  1209. allowExact,
  1210. allowSpread,
  1211. allowProto,
  1212. allowInexact
  1213. }) {
  1214. const oldInType = this.state.inType;
  1215. this.state.inType = true;
  1216. const nodeStart = this.startNode();
  1217. nodeStart.callProperties = [];
  1218. nodeStart.properties = [];
  1219. nodeStart.indexers = [];
  1220. nodeStart.internalSlots = [];
  1221. let endDelim;
  1222. let exact;
  1223. let inexact = false;
  1224. if (allowExact && this.match(types.braceBarL)) {
  1225. this.expect(types.braceBarL);
  1226. endDelim = types.braceBarR;
  1227. exact = true;
  1228. } else {
  1229. this.expect(types.braceL);
  1230. endDelim = types.braceR;
  1231. exact = false;
  1232. }
  1233. nodeStart.exact = exact;
  1234. while (!this.match(endDelim)) {
  1235. let isStatic = false;
  1236. let protoStart = null;
  1237. let inexactStart = null;
  1238. const node = this.startNode();
  1239. if (allowProto && this.isContextual("proto")) {
  1240. const lookahead = this.lookahead();
  1241. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1242. this.next();
  1243. protoStart = this.state.start;
  1244. allowStatic = false;
  1245. }
  1246. }
  1247. if (allowStatic && this.isContextual("static")) {
  1248. const lookahead = this.lookahead();
  1249. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1250. this.next();
  1251. isStatic = true;
  1252. }
  1253. }
  1254. const variance = this.flowParseVariance();
  1255. if (this.eat(types.bracketL)) {
  1256. if (protoStart != null) {
  1257. this.unexpected(protoStart);
  1258. }
  1259. if (this.eat(types.bracketL)) {
  1260. if (variance) {
  1261. this.unexpected(variance.start);
  1262. }
  1263. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1264. } else {
  1265. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1266. }
  1267. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1268. if (protoStart != null) {
  1269. this.unexpected(protoStart);
  1270. }
  1271. if (variance) {
  1272. this.unexpected(variance.start);
  1273. }
  1274. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1275. } else {
  1276. let kind = "init";
  1277. if (this.isContextual("get") || this.isContextual("set")) {
  1278. const lookahead = this.lookahead();
  1279. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1280. kind = this.state.value;
  1281. this.next();
  1282. }
  1283. }
  1284. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1285. if (propOrInexact === null) {
  1286. inexact = true;
  1287. inexactStart = this.state.lastTokStart;
  1288. } else {
  1289. nodeStart.properties.push(propOrInexact);
  1290. }
  1291. }
  1292. this.flowObjectTypeSemicolon();
  1293. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1294. this.raise(inexactStart, "Explicit inexact syntax must appear at the end of an inexact object");
  1295. }
  1296. }
  1297. this.expect(endDelim);
  1298. if (allowSpread) {
  1299. nodeStart.inexact = inexact;
  1300. }
  1301. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1302. this.state.inType = oldInType;
  1303. return out;
  1304. }
  1305. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1306. if (this.eat(types.ellipsis)) {
  1307. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1308. if (isInexactToken) {
  1309. if (!allowSpread) {
  1310. this.raise(this.state.lastTokStart, "Explicit inexact syntax cannot appear in class or interface definitions");
  1311. } else if (!allowInexact) {
  1312. this.raise(this.state.lastTokStart, "Explicit inexact syntax cannot appear inside an explicit exact object type");
  1313. }
  1314. if (variance) {
  1315. this.raise(variance.start, "Explicit inexact syntax cannot have variance");
  1316. }
  1317. return null;
  1318. }
  1319. if (!allowSpread) {
  1320. this.raise(this.state.lastTokStart, "Spread operator cannot appear in class or interface definitions");
  1321. }
  1322. if (protoStart != null) {
  1323. this.unexpected(protoStart);
  1324. }
  1325. if (variance) {
  1326. this.raise(variance.start, "Spread properties cannot have variance");
  1327. }
  1328. node.argument = this.flowParseType();
  1329. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1330. } else {
  1331. node.key = this.flowParseObjectPropertyKey();
  1332. node.static = isStatic;
  1333. node.proto = protoStart != null;
  1334. node.kind = kind;
  1335. let optional = false;
  1336. if (this.isRelational("<") || this.match(types.parenL)) {
  1337. node.method = true;
  1338. if (protoStart != null) {
  1339. this.unexpected(protoStart);
  1340. }
  1341. if (variance) {
  1342. this.unexpected(variance.start);
  1343. }
  1344. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1345. if (kind === "get" || kind === "set") {
  1346. this.flowCheckGetterSetterParams(node);
  1347. }
  1348. } else {
  1349. if (kind !== "init") this.unexpected();
  1350. node.method = false;
  1351. if (this.eat(types.question)) {
  1352. optional = true;
  1353. }
  1354. node.value = this.flowParseTypeInitialiser();
  1355. node.variance = variance;
  1356. }
  1357. node.optional = optional;
  1358. return this.finishNode(node, "ObjectTypeProperty");
  1359. }
  1360. }
  1361. flowCheckGetterSetterParams(property) {
  1362. const paramCount = property.kind === "get" ? 0 : 1;
  1363. const start = property.start;
  1364. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1365. if (length !== paramCount) {
  1366. if (property.kind === "get") {
  1367. this.raise(start, "getter must not have any formal parameters");
  1368. } else {
  1369. this.raise(start, "setter must have exactly one formal parameter");
  1370. }
  1371. }
  1372. if (property.kind === "set" && property.value.rest) {
  1373. this.raise(start, "setter function argument must not be a rest parameter");
  1374. }
  1375. }
  1376. flowObjectTypeSemicolon() {
  1377. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1378. this.unexpected();
  1379. }
  1380. }
  1381. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1382. startPos = startPos || this.state.start;
  1383. startLoc = startLoc || this.state.startLoc;
  1384. let node = id || this.flowParseRestrictedIdentifier(true);
  1385. while (this.eat(types.dot)) {
  1386. const node2 = this.startNodeAt(startPos, startLoc);
  1387. node2.qualification = node;
  1388. node2.id = this.flowParseRestrictedIdentifier(true);
  1389. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1390. }
  1391. return node;
  1392. }
  1393. flowParseGenericType(startPos, startLoc, id) {
  1394. const node = this.startNodeAt(startPos, startLoc);
  1395. node.typeParameters = null;
  1396. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1397. if (this.isRelational("<")) {
  1398. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1399. }
  1400. return this.finishNode(node, "GenericTypeAnnotation");
  1401. }
  1402. flowParseTypeofType() {
  1403. const node = this.startNode();
  1404. this.expect(types._typeof);
  1405. node.argument = this.flowParsePrimaryType();
  1406. return this.finishNode(node, "TypeofTypeAnnotation");
  1407. }
  1408. flowParseTupleType() {
  1409. const node = this.startNode();
  1410. node.types = [];
  1411. this.expect(types.bracketL);
  1412. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1413. node.types.push(this.flowParseType());
  1414. if (this.match(types.bracketR)) break;
  1415. this.expect(types.comma);
  1416. }
  1417. this.expect(types.bracketR);
  1418. return this.finishNode(node, "TupleTypeAnnotation");
  1419. }
  1420. flowParseFunctionTypeParam() {
  1421. let name = null;
  1422. let optional = false;
  1423. let typeAnnotation = null;
  1424. const node = this.startNode();
  1425. const lh = this.lookahead();
  1426. if (lh.type === types.colon || lh.type === types.question) {
  1427. name = this.parseIdentifier();
  1428. if (this.eat(types.question)) {
  1429. optional = true;
  1430. }
  1431. typeAnnotation = this.flowParseTypeInitialiser();
  1432. } else {
  1433. typeAnnotation = this.flowParseType();
  1434. }
  1435. node.name = name;
  1436. node.optional = optional;
  1437. node.typeAnnotation = typeAnnotation;
  1438. return this.finishNode(node, "FunctionTypeParam");
  1439. }
  1440. reinterpretTypeAsFunctionTypeParam(type) {
  1441. const node = this.startNodeAt(type.start, type.loc.start);
  1442. node.name = null;
  1443. node.optional = false;
  1444. node.typeAnnotation = type;
  1445. return this.finishNode(node, "FunctionTypeParam");
  1446. }
  1447. flowParseFunctionTypeParams(params = []) {
  1448. let rest = null;
  1449. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1450. params.push(this.flowParseFunctionTypeParam());
  1451. if (!this.match(types.parenR)) {
  1452. this.expect(types.comma);
  1453. }
  1454. }
  1455. if (this.eat(types.ellipsis)) {
  1456. rest = this.flowParseFunctionTypeParam();
  1457. }
  1458. return {
  1459. params,
  1460. rest
  1461. };
  1462. }
  1463. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1464. switch (id.name) {
  1465. case "any":
  1466. return this.finishNode(node, "AnyTypeAnnotation");
  1467. case "bool":
  1468. case "boolean":
  1469. return this.finishNode(node, "BooleanTypeAnnotation");
  1470. case "mixed":
  1471. return this.finishNode(node, "MixedTypeAnnotation");
  1472. case "empty":
  1473. return this.finishNode(node, "EmptyTypeAnnotation");
  1474. case "number":
  1475. return this.finishNode(node, "NumberTypeAnnotation");
  1476. case "string":
  1477. return this.finishNode(node, "StringTypeAnnotation");
  1478. default:
  1479. this.checkNotUnderscore(id.name);
  1480. return this.flowParseGenericType(startPos, startLoc, id);
  1481. }
  1482. }
  1483. flowParsePrimaryType() {
  1484. const startPos = this.state.start;
  1485. const startLoc = this.state.startLoc;
  1486. const node = this.startNode();
  1487. let tmp;
  1488. let type;
  1489. let isGroupedType = false;
  1490. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1491. switch (this.state.type) {
  1492. case types.name:
  1493. if (this.isContextual("interface")) {
  1494. return this.flowParseInterfaceType();
  1495. }
  1496. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1497. case types.braceL:
  1498. return this.flowParseObjectType({
  1499. allowStatic: false,
  1500. allowExact: false,
  1501. allowSpread: true,
  1502. allowProto: false,
  1503. allowInexact: true
  1504. });
  1505. case types.braceBarL:
  1506. return this.flowParseObjectType({
  1507. allowStatic: false,
  1508. allowExact: true,
  1509. allowSpread: true,
  1510. allowProto: false,
  1511. allowInexact: false
  1512. });
  1513. case types.bracketL:
  1514. this.state.noAnonFunctionType = false;
  1515. type = this.flowParseTupleType();
  1516. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1517. return type;
  1518. case types.relational:
  1519. if (this.state.value === "<") {
  1520. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1521. this.expect(types.parenL);
  1522. tmp = this.flowParseFunctionTypeParams();
  1523. node.params = tmp.params;
  1524. node.rest = tmp.rest;
  1525. this.expect(types.parenR);
  1526. this.expect(types.arrow);
  1527. node.returnType = this.flowParseType();
  1528. return this.finishNode(node, "FunctionTypeAnnotation");
  1529. }
  1530. break;
  1531. case types.parenL:
  1532. this.next();
  1533. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1534. if (this.match(types.name)) {
  1535. const token = this.lookahead().type;
  1536. isGroupedType = token !== types.question && token !== types.colon;
  1537. } else {
  1538. isGroupedType = true;
  1539. }
  1540. }
  1541. if (isGroupedType) {
  1542. this.state.noAnonFunctionType = false;
  1543. type = this.flowParseType();
  1544. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1545. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  1546. this.expect(types.parenR);
  1547. return type;
  1548. } else {
  1549. this.eat(types.comma);
  1550. }
  1551. }
  1552. if (type) {
  1553. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  1554. } else {
  1555. tmp = this.flowParseFunctionTypeParams();
  1556. }
  1557. node.params = tmp.params;
  1558. node.rest = tmp.rest;
  1559. this.expect(types.parenR);
  1560. this.expect(types.arrow);
  1561. node.returnType = this.flowParseType();
  1562. node.typeParameters = null;
  1563. return this.finishNode(node, "FunctionTypeAnnotation");
  1564. case types.string:
  1565. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  1566. case types._true:
  1567. case types._false:
  1568. node.value = this.match(types._true);
  1569. this.next();
  1570. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  1571. case types.plusMin:
  1572. if (this.state.value === "-") {
  1573. this.next();
  1574. if (this.match(types.num)) {
  1575. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  1576. }
  1577. if (this.match(types.bigint)) {
  1578. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  1579. }
  1580. throw this.raise(this.state.start, `Unexpected token, expected "number" or "bigint"`);
  1581. }
  1582. this.unexpected();
  1583. case types.num:
  1584. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  1585. case types.bigint:
  1586. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  1587. case types._void:
  1588. this.next();
  1589. return this.finishNode(node, "VoidTypeAnnotation");
  1590. case types._null:
  1591. this.next();
  1592. return this.finishNode(node, "NullLiteralTypeAnnotation");
  1593. case types._this:
  1594. this.next();
  1595. return this.finishNode(node, "ThisTypeAnnotation");
  1596. case types.star:
  1597. this.next();
  1598. return this.finishNode(node, "ExistsTypeAnnotation");
  1599. default:
  1600. if (this.state.type.keyword === "typeof") {
  1601. return this.flowParseTypeofType();
  1602. } else if (this.state.type.keyword) {
  1603. const label = this.state.type.label;
  1604. this.next();
  1605. return super.createIdentifier(node, label);
  1606. }
  1607. }
  1608. throw this.unexpected();
  1609. }
  1610. flowParsePostfixType() {
  1611. const startPos = this.state.start,
  1612. startLoc = this.state.startLoc;
  1613. let type = this.flowParsePrimaryType();
  1614. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  1615. const node = this.startNodeAt(startPos, startLoc);
  1616. node.elementType = type;
  1617. this.expect(types.bracketL);
  1618. this.expect(types.bracketR);
  1619. type = this.finishNode(node, "ArrayTypeAnnotation");
  1620. }
  1621. return type;
  1622. }
  1623. flowParsePrefixType() {
  1624. const node = this.startNode();
  1625. if (this.eat(types.question)) {
  1626. node.typeAnnotation = this.flowParsePrefixType();
  1627. return this.finishNode(node, "NullableTypeAnnotation");
  1628. } else {
  1629. return this.flowParsePostfixType();
  1630. }
  1631. }
  1632. flowParseAnonFunctionWithoutParens() {
  1633. const param = this.flowParsePrefixType();
  1634. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  1635. const node = this.startNodeAt(param.start, param.loc.start);
  1636. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  1637. node.rest = null;
  1638. node.returnType = this.flowParseType();
  1639. node.typeParameters = null;
  1640. return this.finishNode(node, "FunctionTypeAnnotation");
  1641. }
  1642. return param;
  1643. }
  1644. flowParseIntersectionType() {
  1645. const node = this.startNode();
  1646. this.eat(types.bitwiseAND);
  1647. const type = this.flowParseAnonFunctionWithoutParens();
  1648. node.types = [type];
  1649. while (this.eat(types.bitwiseAND)) {
  1650. node.types.push(this.flowParseAnonFunctionWithoutParens());
  1651. }
  1652. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  1653. }
  1654. flowParseUnionType() {
  1655. const node = this.startNode();
  1656. this.eat(types.bitwiseOR);
  1657. const type = this.flowParseIntersectionType();
  1658. node.types = [type];
  1659. while (this.eat(types.bitwiseOR)) {
  1660. node.types.push(this.flowParseIntersectionType());
  1661. }
  1662. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  1663. }
  1664. flowParseType() {
  1665. const oldInType = this.state.inType;
  1666. this.state.inType = true;
  1667. const type = this.flowParseUnionType();
  1668. this.state.inType = oldInType;
  1669. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  1670. return type;
  1671. }
  1672. flowParseTypeOrImplicitInstantiation() {
  1673. if (this.state.type === types.name && this.state.value === "_") {
  1674. const startPos = this.state.start;
  1675. const startLoc = this.state.startLoc;
  1676. const node = this.parseIdentifier();
  1677. return this.flowParseGenericType(startPos, startLoc, node);
  1678. } else {
  1679. return this.flowParseType();
  1680. }
  1681. }
  1682. flowParseTypeAnnotation() {
  1683. const node = this.startNode();
  1684. node.typeAnnotation = this.flowParseTypeInitialiser();
  1685. return this.finishNode(node, "TypeAnnotation");
  1686. }
  1687. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  1688. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  1689. if (this.match(types.colon)) {
  1690. ident.typeAnnotation = this.flowParseTypeAnnotation();
  1691. this.resetEndLocation(ident);
  1692. }
  1693. return ident;
  1694. }
  1695. typeCastToParameter(node) {
  1696. node.expression.typeAnnotation = node.typeAnnotation;
  1697. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  1698. return node.expression;
  1699. }
  1700. flowParseVariance() {
  1701. let variance = null;
  1702. if (this.match(types.plusMin)) {
  1703. variance = this.startNode();
  1704. if (this.state.value === "+") {
  1705. variance.kind = "plus";
  1706. } else {
  1707. variance.kind = "minus";
  1708. }
  1709. this.next();
  1710. this.finishNode(variance, "Variance");
  1711. }
  1712. return variance;
  1713. }
  1714. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  1715. if (allowExpressionBody) {
  1716. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  1717. }
  1718. return super.parseFunctionBody(node, false, isMethod);
  1719. }
  1720. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  1721. if (this.match(types.colon)) {
  1722. const typeNode = this.startNode();
  1723. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1724. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  1725. }
  1726. super.parseFunctionBodyAndFinish(node, type, isMethod);
  1727. }
  1728. parseStatement(context, topLevel) {
  1729. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  1730. const node = this.startNode();
  1731. this.next();
  1732. return this.flowParseInterface(node);
  1733. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  1734. const node = this.startNode();
  1735. this.next();
  1736. return this.flowParseEnumDeclaration(node);
  1737. } else {
  1738. const stmt = super.parseStatement(context, topLevel);
  1739. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  1740. this.flowPragma = null;
  1741. }
  1742. return stmt;
  1743. }
  1744. }
  1745. parseExpressionStatement(node, expr) {
  1746. if (expr.type === "Identifier") {
  1747. if (expr.name === "declare") {
  1748. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  1749. return this.flowParseDeclare(node);
  1750. }
  1751. } else if (this.match(types.name)) {
  1752. if (expr.name === "interface") {
  1753. return this.flowParseInterface(node);
  1754. } else if (expr.name === "type") {
  1755. return this.flowParseTypeAlias(node);
  1756. } else if (expr.name === "opaque") {
  1757. return this.flowParseOpaqueType(node, false);
  1758. }
  1759. }
  1760. }
  1761. return super.parseExpressionStatement(node, expr);
  1762. }
  1763. shouldParseExportDeclaration() {
  1764. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  1765. }
  1766. isExportDefaultSpecifier() {
  1767. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  1768. return false;
  1769. }
  1770. return super.isExportDefaultSpecifier();
  1771. }
  1772. parseExportDefaultExpression() {
  1773. if (this.shouldParseEnums() && this.isContextual("enum")) {
  1774. const node = this.startNode();
  1775. this.next();
  1776. return this.flowParseEnumDeclaration(node);
  1777. }
  1778. return super.parseExportDefaultExpression();
  1779. }
  1780. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  1781. if (!this.match(types.question)) return expr;
  1782. if (refNeedsArrowPos) {
  1783. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  1784. if (!result.node) {
  1785. refNeedsArrowPos.start = result.error.pos || this.state.start;
  1786. return expr;
  1787. }
  1788. if (result.error) this.state = result.failState;
  1789. return result.node;
  1790. }
  1791. this.expect(types.question);
  1792. const state = this.state.clone();
  1793. const originalNoArrowAt = this.state.noArrowAt;
  1794. const node = this.startNodeAt(startPos, startLoc);
  1795. let {
  1796. consequent,
  1797. failed
  1798. } = this.tryParseConditionalConsequent();
  1799. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1800. if (failed || invalid.length > 0) {
  1801. const noArrowAt = [...originalNoArrowAt];
  1802. if (invalid.length > 0) {
  1803. this.state = state;
  1804. this.state.noArrowAt = noArrowAt;
  1805. for (let i = 0; i < invalid.length; i++) {
  1806. noArrowAt.push(invalid[i].start);
  1807. }
  1808. ({
  1809. consequent,
  1810. failed
  1811. } = this.tryParseConditionalConsequent());
  1812. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1813. }
  1814. if (failed && valid.length > 1) {
  1815. this.raise(state.start, "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.");
  1816. }
  1817. if (failed && valid.length === 1) {
  1818. this.state = state;
  1819. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  1820. ({
  1821. consequent,
  1822. failed
  1823. } = this.tryParseConditionalConsequent());
  1824. }
  1825. }
  1826. this.getArrowLikeExpressions(consequent, true);
  1827. this.state.noArrowAt = originalNoArrowAt;
  1828. this.expect(types.colon);
  1829. node.test = expr;
  1830. node.consequent = consequent;
  1831. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(noIn, undefined, undefined, undefined));
  1832. return this.finishNode(node, "ConditionalExpression");
  1833. }
  1834. tryParseConditionalConsequent() {
  1835. this.state.noArrowParamsConversionAt.push(this.state.start);
  1836. const consequent = this.parseMaybeAssign();
  1837. const failed = !this.match(types.colon);
  1838. this.state.noArrowParamsConversionAt.pop();
  1839. return {
  1840. consequent,
  1841. failed
  1842. };
  1843. }
  1844. getArrowLikeExpressions(node, disallowInvalid) {
  1845. const stack = [node];
  1846. const arrows = [];
  1847. while (stack.length !== 0) {
  1848. const node = stack.pop();
  1849. if (node.type === "ArrowFunctionExpression") {
  1850. if (node.typeParameters || !node.returnType) {
  1851. this.finishArrowValidation(node);
  1852. } else {
  1853. arrows.push(node);
  1854. }
  1855. stack.push(node.body);
  1856. } else if (node.type === "ConditionalExpression") {
  1857. stack.push(node.consequent);
  1858. stack.push(node.alternate);
  1859. }
  1860. }
  1861. if (disallowInvalid) {
  1862. arrows.forEach(node => this.finishArrowValidation(node));
  1863. return [arrows, []];
  1864. }
  1865. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  1866. }
  1867. finishArrowValidation(node) {
  1868. var _node$extra;
  1869. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma);
  1870. this.scope.enter(functionFlags(false, false) | SCOPE_ARROW);
  1871. super.checkParams(node, false, true);
  1872. this.scope.exit();
  1873. }
  1874. forwardNoArrowParamsConversionAt(node, parse) {
  1875. let result;
  1876. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  1877. this.state.noArrowParamsConversionAt.push(this.state.start);
  1878. result = parse();
  1879. this.state.noArrowParamsConversionAt.pop();
  1880. } else {
  1881. result = parse();
  1882. }
  1883. return result;
  1884. }
  1885. parseParenItem(node, startPos, startLoc) {
  1886. node = super.parseParenItem(node, startPos, startLoc);
  1887. if (this.eat(types.question)) {
  1888. node.optional = true;
  1889. this.resetEndLocation(node);
  1890. }
  1891. if (this.match(types.colon)) {
  1892. const typeCastNode = this.startNodeAt(startPos, startLoc);
  1893. typeCastNode.expression = node;
  1894. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  1895. return this.finishNode(typeCastNode, "TypeCastExpression");
  1896. }
  1897. return node;
  1898. }
  1899. assertModuleNodeAllowed(node) {
  1900. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  1901. return;
  1902. }
  1903. super.assertModuleNodeAllowed(node);
  1904. }
  1905. parseExport(node) {
  1906. const decl = super.parseExport(node);
  1907. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  1908. decl.exportKind = decl.exportKind || "value";
  1909. }
  1910. return decl;
  1911. }
  1912. parseExportDeclaration(node) {
  1913. if (this.isContextual("type")) {
  1914. node.exportKind = "type";
  1915. const declarationNode = this.startNode();
  1916. this.next();
  1917. if (this.match(types.braceL)) {
  1918. node.specifiers = this.parseExportSpecifiers();
  1919. this.parseExportFrom(node);
  1920. return null;
  1921. } else {
  1922. return this.flowParseTypeAlias(declarationNode);
  1923. }
  1924. } else if (this.isContextual("opaque")) {
  1925. node.exportKind = "type";
  1926. const declarationNode = this.startNode();
  1927. this.next();
  1928. return this.flowParseOpaqueType(declarationNode, false);
  1929. } else if (this.isContextual("interface")) {
  1930. node.exportKind = "type";
  1931. const declarationNode = this.startNode();
  1932. this.next();
  1933. return this.flowParseInterface(declarationNode);
  1934. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  1935. node.exportKind = "value";
  1936. const declarationNode = this.startNode();
  1937. this.next();
  1938. return this.flowParseEnumDeclaration(declarationNode);
  1939. } else {
  1940. return super.parseExportDeclaration(node);
  1941. }
  1942. }
  1943. eatExportStar(node) {
  1944. if (super.eatExportStar(...arguments)) return true;
  1945. if (this.isContextual("type") && this.lookahead().type === types.star) {
  1946. node.exportKind = "type";
  1947. this.next();
  1948. this.next();
  1949. return true;
  1950. }
  1951. return false;
  1952. }
  1953. maybeParseExportNamespaceSpecifier(node) {
  1954. const pos = this.state.start;
  1955. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  1956. if (hasNamespace && node.exportKind === "type") {
  1957. this.unexpected(pos);
  1958. }
  1959. return hasNamespace;
  1960. }
  1961. parseClassId(node, isStatement, optionalId) {
  1962. super.parseClassId(node, isStatement, optionalId);
  1963. if (this.isRelational("<")) {
  1964. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1965. }
  1966. }
  1967. getTokenFromCode(code) {
  1968. const next = this.input.charCodeAt(this.state.pos + 1);
  1969. if (code === 123 && next === 124) {
  1970. return this.finishOp(types.braceBarL, 2);
  1971. } else if (this.state.inType && (code === 62 || code === 60)) {
  1972. return this.finishOp(types.relational, 1);
  1973. } else if (isIteratorStart(code, next)) {
  1974. this.state.isIterator = true;
  1975. return super.readWord();
  1976. } else {
  1977. return super.getTokenFromCode(code);
  1978. }
  1979. }
  1980. isAssignable(node, isBinding) {
  1981. switch (node.type) {
  1982. case "Identifier":
  1983. case "ObjectPattern":
  1984. case "ArrayPattern":
  1985. case "AssignmentPattern":
  1986. return true;
  1987. case "ObjectExpression":
  1988. {
  1989. const last = node.properties.length - 1;
  1990. return node.properties.every((prop, i) => {
  1991. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  1992. });
  1993. }
  1994. case "ObjectProperty":
  1995. return this.isAssignable(node.value);
  1996. case "SpreadElement":
  1997. return this.isAssignable(node.argument);
  1998. case "ArrayExpression":
  1999. return node.elements.every(element => this.isAssignable(element));
  2000. case "AssignmentExpression":
  2001. return node.operator === "=";
  2002. case "ParenthesizedExpression":
  2003. case "TypeCastExpression":
  2004. return this.isAssignable(node.expression);
  2005. case "MemberExpression":
  2006. case "OptionalMemberExpression":
  2007. return !isBinding;
  2008. default:
  2009. return false;
  2010. }
  2011. }
  2012. toAssignable(node) {
  2013. if (node.type === "TypeCastExpression") {
  2014. return super.toAssignable(this.typeCastToParameter(node));
  2015. } else {
  2016. return super.toAssignable(node);
  2017. }
  2018. }
  2019. toAssignableList(exprList, trailingCommaPos) {
  2020. for (let i = 0; i < exprList.length; i++) {
  2021. const expr = exprList[i];
  2022. if (expr && expr.type === "TypeCastExpression") {
  2023. exprList[i] = this.typeCastToParameter(expr);
  2024. }
  2025. }
  2026. return super.toAssignableList(exprList, trailingCommaPos);
  2027. }
  2028. toReferencedList(exprList, isParenthesizedExpr) {
  2029. for (let i = 0; i < exprList.length; i++) {
  2030. const expr = exprList[i];
  2031. if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2032. this.raise(expr.typeAnnotation.start, "The type cast expression is expected to be wrapped with parenthesis");
  2033. }
  2034. }
  2035. return exprList;
  2036. }
  2037. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  2038. if (expr.type !== "TypeCastExpression") {
  2039. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  2040. }
  2041. }
  2042. parseClassProperty(node) {
  2043. if (this.match(types.colon)) {
  2044. node.typeAnnotation = this.flowParseTypeAnnotation();
  2045. }
  2046. return super.parseClassProperty(node);
  2047. }
  2048. parseClassPrivateProperty(node) {
  2049. if (this.match(types.colon)) {
  2050. node.typeAnnotation = this.flowParseTypeAnnotation();
  2051. }
  2052. return super.parseClassPrivateProperty(node);
  2053. }
  2054. isClassMethod() {
  2055. return this.isRelational("<") || super.isClassMethod();
  2056. }
  2057. isClassProperty() {
  2058. return this.match(types.colon) || super.isClassProperty();
  2059. }
  2060. isNonstaticConstructor(method) {
  2061. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2062. }
  2063. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2064. if (method.variance) {
  2065. this.unexpected(method.variance.start);
  2066. }
  2067. delete method.variance;
  2068. if (this.isRelational("<")) {
  2069. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2070. }
  2071. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2072. }
  2073. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2074. if (method.variance) {
  2075. this.unexpected(method.variance.start);
  2076. }
  2077. delete method.variance;
  2078. if (this.isRelational("<")) {
  2079. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2080. }
  2081. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2082. }
  2083. parseClassSuper(node) {
  2084. super.parseClassSuper(node);
  2085. if (node.superClass && this.isRelational("<")) {
  2086. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2087. }
  2088. if (this.isContextual("implements")) {
  2089. this.next();
  2090. const implemented = node.implements = [];
  2091. do {
  2092. const node = this.startNode();
  2093. node.id = this.flowParseRestrictedIdentifier(true);
  2094. if (this.isRelational("<")) {
  2095. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2096. } else {
  2097. node.typeParameters = null;
  2098. }
  2099. implemented.push(this.finishNode(node, "ClassImplements"));
  2100. } while (this.eat(types.comma));
  2101. }
  2102. }
  2103. parsePropertyName(node, isPrivateNameAllowed) {
  2104. const variance = this.flowParseVariance();
  2105. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2106. node.variance = variance;
  2107. return key;
  2108. }
  2109. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  2110. if (prop.variance) {
  2111. this.unexpected(prop.variance.start);
  2112. }
  2113. delete prop.variance;
  2114. let typeParameters;
  2115. if (this.isRelational("<")) {
  2116. typeParameters = this.flowParseTypeParameterDeclaration();
  2117. if (!this.match(types.parenL)) this.unexpected();
  2118. }
  2119. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  2120. if (typeParameters) {
  2121. (prop.value || prop).typeParameters = typeParameters;
  2122. }
  2123. }
  2124. parseAssignableListItemTypes(param) {
  2125. if (this.eat(types.question)) {
  2126. if (param.type !== "Identifier") {
  2127. this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature.");
  2128. }
  2129. param.optional = true;
  2130. }
  2131. if (this.match(types.colon)) {
  2132. param.typeAnnotation = this.flowParseTypeAnnotation();
  2133. }
  2134. this.resetEndLocation(param);
  2135. return param;
  2136. }
  2137. parseMaybeDefault(startPos, startLoc, left) {
  2138. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2139. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2140. this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`");
  2141. }
  2142. return node;
  2143. }
  2144. shouldParseDefaultImport(node) {
  2145. if (!hasTypeImportKind(node)) {
  2146. return super.shouldParseDefaultImport(node);
  2147. }
  2148. return isMaybeDefaultImport(this.state);
  2149. }
  2150. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2151. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2152. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  2153. node.specifiers.push(this.finishNode(specifier, type));
  2154. }
  2155. maybeParseDefaultImportSpecifier(node) {
  2156. node.importKind = "value";
  2157. let kind = null;
  2158. if (this.match(types._typeof)) {
  2159. kind = "typeof";
  2160. } else if (this.isContextual("type")) {
  2161. kind = "type";
  2162. }
  2163. if (kind) {
  2164. const lh = this.lookahead();
  2165. if (kind === "type" && lh.type === types.star) {
  2166. this.unexpected(lh.start);
  2167. }
  2168. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2169. this.next();
  2170. node.importKind = kind;
  2171. }
  2172. }
  2173. return super.maybeParseDefaultImportSpecifier(node);
  2174. }
  2175. parseImportSpecifier(node) {
  2176. const specifier = this.startNode();
  2177. const firstIdentLoc = this.state.start;
  2178. const firstIdent = this.parseIdentifier(true);
  2179. let specifierTypeKind = null;
  2180. if (firstIdent.name === "type") {
  2181. specifierTypeKind = "type";
  2182. } else if (firstIdent.name === "typeof") {
  2183. specifierTypeKind = "typeof";
  2184. }
  2185. let isBinding = false;
  2186. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2187. const as_ident = this.parseIdentifier(true);
  2188. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2189. specifier.imported = as_ident;
  2190. specifier.importKind = specifierTypeKind;
  2191. specifier.local = as_ident.__clone();
  2192. } else {
  2193. specifier.imported = firstIdent;
  2194. specifier.importKind = null;
  2195. specifier.local = this.parseIdentifier();
  2196. }
  2197. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2198. specifier.imported = this.parseIdentifier(true);
  2199. specifier.importKind = specifierTypeKind;
  2200. if (this.eatContextual("as")) {
  2201. specifier.local = this.parseIdentifier();
  2202. } else {
  2203. isBinding = true;
  2204. specifier.local = specifier.imported.__clone();
  2205. }
  2206. } else {
  2207. isBinding = true;
  2208. specifier.imported = firstIdent;
  2209. specifier.importKind = null;
  2210. specifier.local = specifier.imported.__clone();
  2211. }
  2212. const nodeIsTypeImport = hasTypeImportKind(node);
  2213. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2214. if (nodeIsTypeImport && specifierIsTypeImport) {
  2215. this.raise(firstIdentLoc, "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");
  2216. }
  2217. if (nodeIsTypeImport || specifierIsTypeImport) {
  2218. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2219. }
  2220. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2221. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2222. }
  2223. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2224. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2225. }
  2226. parseFunctionParams(node, allowModifiers) {
  2227. const kind = node.kind;
  2228. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2229. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2230. }
  2231. super.parseFunctionParams(node, allowModifiers);
  2232. }
  2233. parseVarId(decl, kind) {
  2234. super.parseVarId(decl, kind);
  2235. if (this.match(types.colon)) {
  2236. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2237. this.resetEndLocation(decl.id);
  2238. }
  2239. }
  2240. parseAsyncArrowFromCallExpression(node, call) {
  2241. if (this.match(types.colon)) {
  2242. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2243. this.state.noAnonFunctionType = true;
  2244. node.returnType = this.flowParseTypeAnnotation();
  2245. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2246. }
  2247. return super.parseAsyncArrowFromCallExpression(node, call);
  2248. }
  2249. shouldParseAsyncArrow() {
  2250. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2251. }
  2252. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  2253. let state = null;
  2254. let jsx;
  2255. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2256. state = this.state.clone();
  2257. jsx = this.tryParse(() => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  2258. if (!jsx.error) return jsx.node;
  2259. const {
  2260. context
  2261. } = this.state;
  2262. if (context[context.length - 1] === types$1.j_oTag) {
  2263. context.length -= 2;
  2264. } else if (context[context.length - 1] === types$1.j_expr) {
  2265. context.length -= 1;
  2266. }
  2267. }
  2268. if (jsx && jsx.error || this.isRelational("<")) {
  2269. state = state || this.state.clone();
  2270. let typeParameters;
  2271. const arrow = this.tryParse(() => {
  2272. typeParameters = this.flowParseTypeParameterDeclaration();
  2273. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  2274. arrowExpression.typeParameters = typeParameters;
  2275. this.resetStartLocationFromNode(arrowExpression, typeParameters);
  2276. return arrowExpression;
  2277. }, state);
  2278. const arrowExpression = arrow.node && arrow.node.type === "ArrowFunctionExpression" ? arrow.node : null;
  2279. if (!arrow.error && arrowExpression) return arrowExpression;
  2280. if (jsx && jsx.node) {
  2281. this.state = jsx.failState;
  2282. return jsx.node;
  2283. }
  2284. if (arrowExpression) {
  2285. this.state = arrow.failState;
  2286. return arrowExpression;
  2287. }
  2288. if (jsx && jsx.thrown) throw jsx.error;
  2289. if (arrow.thrown) throw arrow.error;
  2290. throw this.raise(typeParameters.start, "Expected an arrow function after this type parameter declaration");
  2291. }
  2292. return super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2293. }
  2294. parseArrow(node) {
  2295. if (this.match(types.colon)) {
  2296. const result = this.tryParse(() => {
  2297. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2298. this.state.noAnonFunctionType = true;
  2299. const typeNode = this.startNode();
  2300. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2301. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2302. if (this.canInsertSemicolon()) this.unexpected();
  2303. if (!this.match(types.arrow)) this.unexpected();
  2304. return typeNode;
  2305. });
  2306. if (result.thrown) return null;
  2307. if (result.error) this.state = result.failState;
  2308. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2309. }
  2310. return super.parseArrow(node);
  2311. }
  2312. shouldParseArrow() {
  2313. return this.match(types.colon) || super.shouldParseArrow();
  2314. }
  2315. setArrowFunctionParameters(node, params) {
  2316. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2317. node.params = params;
  2318. } else {
  2319. super.setArrowFunctionParameters(node, params);
  2320. }
  2321. }
  2322. checkParams(node, allowDuplicates, isArrowFunction) {
  2323. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2324. return;
  2325. }
  2326. return super.checkParams(...arguments);
  2327. }
  2328. parseParenAndDistinguishExpression(canBeArrow) {
  2329. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2330. }
  2331. parseSubscripts(base, startPos, startLoc, noCalls) {
  2332. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2333. this.next();
  2334. const node = this.startNodeAt(startPos, startLoc);
  2335. node.callee = base;
  2336. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2337. base = this.finishNode(node, "CallExpression");
  2338. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2339. const state = this.state.clone();
  2340. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2341. if (!arrow.error && !arrow.aborted) return arrow.node;
  2342. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2343. if (result.node && !result.error) return result.node;
  2344. if (arrow.node) {
  2345. this.state = arrow.failState;
  2346. return arrow.node;
  2347. }
  2348. if (result.node) {
  2349. this.state = result.failState;
  2350. return result.node;
  2351. }
  2352. throw arrow.error || result.error;
  2353. }
  2354. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2355. }
  2356. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2357. if (this.match(types.questionDot) && this.isLookaheadRelational("<")) {
  2358. subscriptState.optionalChainMember = true;
  2359. if (noCalls) {
  2360. subscriptState.stop = true;
  2361. return base;
  2362. }
  2363. this.next();
  2364. const node = this.startNodeAt(startPos, startLoc);
  2365. node.callee = base;
  2366. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2367. this.expect(types.parenL);
  2368. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2369. node.optional = true;
  2370. return this.finishCallExpression(node, true);
  2371. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2372. const node = this.startNodeAt(startPos, startLoc);
  2373. node.callee = base;
  2374. const result = this.tryParse(() => {
  2375. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2376. this.expect(types.parenL);
  2377. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2378. if (subscriptState.optionalChainMember) node.optional = false;
  2379. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2380. });
  2381. if (result.node) {
  2382. if (result.error) this.state = result.failState;
  2383. return result.node;
  2384. }
  2385. }
  2386. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2387. }
  2388. parseNewArguments(node) {
  2389. let targs = null;
  2390. if (this.shouldParseTypes() && this.isRelational("<")) {
  2391. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2392. }
  2393. node.typeArguments = targs;
  2394. super.parseNewArguments(node);
  2395. }
  2396. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2397. const node = this.startNodeAt(startPos, startLoc);
  2398. this.parseFunctionParams(node);
  2399. if (!this.parseArrow(node)) return;
  2400. return this.parseArrowExpression(node, undefined, true);
  2401. }
  2402. readToken_mult_modulo(code) {
  2403. const next = this.input.charCodeAt(this.state.pos + 1);
  2404. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2405. this.state.hasFlowComment = false;
  2406. this.state.pos += 2;
  2407. this.nextToken();
  2408. return;
  2409. }
  2410. super.readToken_mult_modulo(code);
  2411. }
  2412. readToken_pipe_amp(code) {
  2413. const next = this.input.charCodeAt(this.state.pos + 1);
  2414. if (code === 124 && next === 125) {
  2415. this.finishOp(types.braceBarR, 2);
  2416. return;
  2417. }
  2418. super.readToken_pipe_amp(code);
  2419. }
  2420. parseTopLevel(file, program) {
  2421. const fileNode = super.parseTopLevel(file, program);
  2422. if (this.state.hasFlowComment) {
  2423. this.raise(this.state.pos, "Unterminated flow-comment");
  2424. }
  2425. return fileNode;
  2426. }
  2427. skipBlockComment() {
  2428. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2429. if (this.state.hasFlowComment) {
  2430. this.unexpected(null, "Cannot have a flow comment inside another flow comment");
  2431. }
  2432. this.hasFlowCommentCompletion();
  2433. this.state.pos += this.skipFlowComment();
  2434. this.state.hasFlowComment = true;
  2435. return;
  2436. }
  2437. if (this.state.hasFlowComment) {
  2438. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2439. if (end === -1) {
  2440. throw this.raise(this.state.pos - 2, "Unterminated comment");
  2441. }
  2442. this.state.pos = end + 3;
  2443. return;
  2444. }
  2445. super.skipBlockComment();
  2446. }
  2447. skipFlowComment() {
  2448. const {
  2449. pos
  2450. } = this.state;
  2451. let shiftToFirstNonWhiteSpace = 2;
  2452. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2453. shiftToFirstNonWhiteSpace++;
  2454. }
  2455. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2456. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2457. if (ch2 === 58 && ch3 === 58) {
  2458. return shiftToFirstNonWhiteSpace + 2;
  2459. }
  2460. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2461. return shiftToFirstNonWhiteSpace + 12;
  2462. }
  2463. if (ch2 === 58 && ch3 !== 58) {
  2464. return shiftToFirstNonWhiteSpace;
  2465. }
  2466. return false;
  2467. }
  2468. hasFlowCommentCompletion() {
  2469. const end = this.input.indexOf("*/", this.state.pos);
  2470. if (end === -1) {
  2471. throw this.raise(this.state.pos, "Unterminated comment");
  2472. }
  2473. }
  2474. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2475. enumName,
  2476. memberName
  2477. }) {
  2478. this.raise(pos, `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` ` + `or \`${memberName} = false,\` in enum \`${enumName}\`.`);
  2479. }
  2480. flowEnumErrorInvalidMemberName(pos, {
  2481. enumName,
  2482. memberName
  2483. }) {
  2484. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  2485. this.raise(pos, `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using ` + `\`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`);
  2486. }
  2487. flowEnumErrorDuplicateMemberName(pos, {
  2488. enumName,
  2489. memberName
  2490. }) {
  2491. this.raise(pos, `Enum member names need to be unique, but the name \`${memberName}\` has already been used ` + `before in enum \`${enumName}\`.`);
  2492. }
  2493. flowEnumErrorInconsistentMemberValues(pos, {
  2494. enumName
  2495. }) {
  2496. this.raise(pos, `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or ` + `consistently use literals (either booleans, numbers, or strings) for all member initializers.`);
  2497. }
  2498. flowEnumErrorInvalidExplicitType(pos, {
  2499. enumName,
  2500. suppliedType
  2501. }) {
  2502. const suggestion = `Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in ` + `enum \`${enumName}\`.`;
  2503. const message = suppliedType === null ? `Supplied enum type is not valid. ${suggestion}` : `Enum type \`${suppliedType}\` is not valid. ${suggestion}`;
  2504. return this.raise(pos, message);
  2505. }
  2506. flowEnumErrorInvalidMemberInitializer(pos, {
  2507. enumName,
  2508. explicitType,
  2509. memberName
  2510. }) {
  2511. let message = null;
  2512. switch (explicitType) {
  2513. case "boolean":
  2514. case "number":
  2515. case "string":
  2516. message = `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of ` + `\`${memberName}\` needs to be a ${explicitType} literal.`;
  2517. break;
  2518. case "symbol":
  2519. message = `Symbol enum members cannot be initialized. Use \`${memberName},\` in ` + `enum \`${enumName}\`.`;
  2520. break;
  2521. default:
  2522. message = `The enum member initializer for \`${memberName}\` needs to be a literal (either ` + `a boolean, number, or string) in enum \`${enumName}\`.`;
  2523. }
  2524. return this.raise(pos, message);
  2525. }
  2526. flowEnumErrorNumberMemberNotInitialized(pos, {
  2527. enumName,
  2528. memberName
  2529. }) {
  2530. this.raise(pos, `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`);
  2531. }
  2532. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  2533. enumName
  2534. }) {
  2535. this.raise(pos, `String enum members need to consistently either all use initializers, or use no initializers, ` + `in enum \`${enumName}\`.`);
  2536. }
  2537. flowEnumMemberInit() {
  2538. const startPos = this.state.start;
  2539. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  2540. switch (this.state.type) {
  2541. case types.num:
  2542. {
  2543. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  2544. if (endOfInit()) {
  2545. return {
  2546. type: "number",
  2547. pos: literal.start,
  2548. value: literal
  2549. };
  2550. }
  2551. return {
  2552. type: "invalid",
  2553. pos: startPos
  2554. };
  2555. }
  2556. case types.string:
  2557. {
  2558. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  2559. if (endOfInit()) {
  2560. return {
  2561. type: "string",
  2562. pos: literal.start,
  2563. value: literal
  2564. };
  2565. }
  2566. return {
  2567. type: "invalid",
  2568. pos: startPos
  2569. };
  2570. }
  2571. case types._true:
  2572. case types._false:
  2573. {
  2574. const literal = this.parseBooleanLiteral();
  2575. if (endOfInit()) {
  2576. return {
  2577. type: "boolean",
  2578. pos: literal.start,
  2579. value: literal
  2580. };
  2581. }
  2582. return {
  2583. type: "invalid",
  2584. pos: startPos
  2585. };
  2586. }
  2587. default:
  2588. return {
  2589. type: "invalid",
  2590. pos: startPos
  2591. };
  2592. }
  2593. }
  2594. flowEnumMemberRaw() {
  2595. const pos = this.state.start;
  2596. const id = this.parseIdentifier(true);
  2597. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  2598. type: "none",
  2599. pos
  2600. };
  2601. return {
  2602. id,
  2603. init
  2604. };
  2605. }
  2606. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  2607. const {
  2608. explicitType
  2609. } = context;
  2610. if (explicitType === null) {
  2611. return;
  2612. }
  2613. if (explicitType !== expectedType) {
  2614. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  2615. }
  2616. }
  2617. flowEnumMembers({
  2618. enumName,
  2619. explicitType
  2620. }) {
  2621. const seenNames = new Set();
  2622. const members = {
  2623. booleanMembers: [],
  2624. numberMembers: [],
  2625. stringMembers: [],
  2626. defaultedMembers: []
  2627. };
  2628. while (!this.match(types.braceR)) {
  2629. const memberNode = this.startNode();
  2630. const {
  2631. id,
  2632. init
  2633. } = this.flowEnumMemberRaw();
  2634. const memberName = id.name;
  2635. if (memberName === "") {
  2636. continue;
  2637. }
  2638. if (/^[a-z]/.test(memberName)) {
  2639. this.flowEnumErrorInvalidMemberName(id.start, {
  2640. enumName,
  2641. memberName
  2642. });
  2643. }
  2644. if (seenNames.has(memberName)) {
  2645. this.flowEnumErrorDuplicateMemberName(id.start, {
  2646. enumName,
  2647. memberName
  2648. });
  2649. }
  2650. seenNames.add(memberName);
  2651. const context = {
  2652. enumName,
  2653. explicitType,
  2654. memberName
  2655. };
  2656. memberNode.id = id;
  2657. switch (init.type) {
  2658. case "boolean":
  2659. {
  2660. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  2661. memberNode.init = init.value;
  2662. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  2663. break;
  2664. }
  2665. case "number":
  2666. {
  2667. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  2668. memberNode.init = init.value;
  2669. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  2670. break;
  2671. }
  2672. case "string":
  2673. {
  2674. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  2675. memberNode.init = init.value;
  2676. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  2677. break;
  2678. }
  2679. case "invalid":
  2680. {
  2681. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  2682. }
  2683. case "none":
  2684. {
  2685. switch (explicitType) {
  2686. case "boolean":
  2687. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  2688. break;
  2689. case "number":
  2690. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  2691. break;
  2692. default:
  2693. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  2694. }
  2695. }
  2696. }
  2697. if (!this.match(types.braceR)) {
  2698. this.expect(types.comma);
  2699. }
  2700. }
  2701. return members;
  2702. }
  2703. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  2704. enumName
  2705. }) {
  2706. if (initializedMembers.length === 0) {
  2707. return defaultedMembers;
  2708. } else if (defaultedMembers.length === 0) {
  2709. return initializedMembers;
  2710. } else if (defaultedMembers.length > initializedMembers.length) {
  2711. for (let _i = 0; _i < initializedMembers.length; _i++) {
  2712. const member = initializedMembers[_i];
  2713. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  2714. enumName
  2715. });
  2716. }
  2717. return defaultedMembers;
  2718. } else {
  2719. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  2720. const member = defaultedMembers[_i2];
  2721. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  2722. enumName
  2723. });
  2724. }
  2725. return initializedMembers;
  2726. }
  2727. }
  2728. flowEnumParseExplicitType({
  2729. enumName
  2730. }) {
  2731. if (this.eatContextual("of")) {
  2732. if (!this.match(types.name)) {
  2733. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  2734. enumName,
  2735. suppliedType: null
  2736. });
  2737. }
  2738. const {
  2739. value
  2740. } = this.state;
  2741. this.next();
  2742. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  2743. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  2744. enumName,
  2745. suppliedType: value
  2746. });
  2747. }
  2748. return value;
  2749. }
  2750. return null;
  2751. }
  2752. flowEnumBody(node, {
  2753. enumName,
  2754. nameLoc
  2755. }) {
  2756. const explicitType = this.flowEnumParseExplicitType({
  2757. enumName
  2758. });
  2759. this.expect(types.braceL);
  2760. const members = this.flowEnumMembers({
  2761. enumName,
  2762. explicitType
  2763. });
  2764. switch (explicitType) {
  2765. case "boolean":
  2766. node.explicitType = true;
  2767. node.members = members.booleanMembers;
  2768. this.expect(types.braceR);
  2769. return this.finishNode(node, "EnumBooleanBody");
  2770. case "number":
  2771. node.explicitType = true;
  2772. node.members = members.numberMembers;
  2773. this.expect(types.braceR);
  2774. return this.finishNode(node, "EnumNumberBody");
  2775. case "string":
  2776. node.explicitType = true;
  2777. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  2778. enumName
  2779. });
  2780. this.expect(types.braceR);
  2781. return this.finishNode(node, "EnumStringBody");
  2782. case "symbol":
  2783. node.members = members.defaultedMembers;
  2784. this.expect(types.braceR);
  2785. return this.finishNode(node, "EnumSymbolBody");
  2786. default:
  2787. {
  2788. const empty = () => {
  2789. node.members = [];
  2790. this.expect(types.braceR);
  2791. return this.finishNode(node, "EnumStringBody");
  2792. };
  2793. node.explicitType = false;
  2794. const boolsLen = members.booleanMembers.length;
  2795. const numsLen = members.numberMembers.length;
  2796. const strsLen = members.stringMembers.length;
  2797. const defaultedLen = members.defaultedMembers.length;
  2798. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  2799. return empty();
  2800. } else if (!boolsLen && !numsLen) {
  2801. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  2802. enumName
  2803. });
  2804. this.expect(types.braceR);
  2805. return this.finishNode(node, "EnumStringBody");
  2806. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  2807. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  2808. const member = _members$defaultedMem[_i3];
  2809. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  2810. enumName,
  2811. memberName: member.id.name
  2812. });
  2813. }
  2814. node.members = members.booleanMembers;
  2815. this.expect(types.braceR);
  2816. return this.finishNode(node, "EnumBooleanBody");
  2817. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  2818. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  2819. const member = _members$defaultedMem2[_i4];
  2820. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  2821. enumName,
  2822. memberName: member.id.name
  2823. });
  2824. }
  2825. node.members = members.numberMembers;
  2826. this.expect(types.braceR);
  2827. return this.finishNode(node, "EnumNumberBody");
  2828. } else {
  2829. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  2830. enumName
  2831. });
  2832. return empty();
  2833. }
  2834. }
  2835. }
  2836. }
  2837. flowParseEnumDeclaration(node) {
  2838. const id = this.parseIdentifier();
  2839. node.id = id;
  2840. node.body = this.flowEnumBody(this.startNode(), {
  2841. enumName: id.name,
  2842. nameLoc: id.start
  2843. });
  2844. return this.finishNode(node, "EnumDeclaration");
  2845. }
  2846. });
  2847. const entities = {
  2848. quot: "\u0022",
  2849. amp: "&",
  2850. apos: "\u0027",
  2851. lt: "<",
  2852. gt: ">",
  2853. nbsp: "\u00A0",
  2854. iexcl: "\u00A1",
  2855. cent: "\u00A2",
  2856. pound: "\u00A3",
  2857. curren: "\u00A4",
  2858. yen: "\u00A5",
  2859. brvbar: "\u00A6",
  2860. sect: "\u00A7",
  2861. uml: "\u00A8",
  2862. copy: "\u00A9",
  2863. ordf: "\u00AA",
  2864. laquo: "\u00AB",
  2865. not: "\u00AC",
  2866. shy: "\u00AD",
  2867. reg: "\u00AE",
  2868. macr: "\u00AF",
  2869. deg: "\u00B0",
  2870. plusmn: "\u00B1",
  2871. sup2: "\u00B2",
  2872. sup3: "\u00B3",
  2873. acute: "\u00B4",
  2874. micro: "\u00B5",
  2875. para: "\u00B6",
  2876. middot: "\u00B7",
  2877. cedil: "\u00B8",
  2878. sup1: "\u00B9",
  2879. ordm: "\u00BA",
  2880. raquo: "\u00BB",
  2881. frac14: "\u00BC",
  2882. frac12: "\u00BD",
  2883. frac34: "\u00BE",
  2884. iquest: "\u00BF",
  2885. Agrave: "\u00C0",
  2886. Aacute: "\u00C1",
  2887. Acirc: "\u00C2",
  2888. Atilde: "\u00C3",
  2889. Auml: "\u00C4",
  2890. Aring: "\u00C5",
  2891. AElig: "\u00C6",
  2892. Ccedil: "\u00C7",
  2893. Egrave: "\u00C8",
  2894. Eacute: "\u00C9",
  2895. Ecirc: "\u00CA",
  2896. Euml: "\u00CB",
  2897. Igrave: "\u00CC",
  2898. Iacute: "\u00CD",
  2899. Icirc: "\u00CE",
  2900. Iuml: "\u00CF",
  2901. ETH: "\u00D0",
  2902. Ntilde: "\u00D1",
  2903. Ograve: "\u00D2",
  2904. Oacute: "\u00D3",
  2905. Ocirc: "\u00D4",
  2906. Otilde: "\u00D5",
  2907. Ouml: "\u00D6",
  2908. times: "\u00D7",
  2909. Oslash: "\u00D8",
  2910. Ugrave: "\u00D9",
  2911. Uacute: "\u00DA",
  2912. Ucirc: "\u00DB",
  2913. Uuml: "\u00DC",
  2914. Yacute: "\u00DD",
  2915. THORN: "\u00DE",
  2916. szlig: "\u00DF",
  2917. agrave: "\u00E0",
  2918. aacute: "\u00E1",
  2919. acirc: "\u00E2",
  2920. atilde: "\u00E3",
  2921. auml: "\u00E4",
  2922. aring: "\u00E5",
  2923. aelig: "\u00E6",
  2924. ccedil: "\u00E7",
  2925. egrave: "\u00E8",
  2926. eacute: "\u00E9",
  2927. ecirc: "\u00EA",
  2928. euml: "\u00EB",
  2929. igrave: "\u00EC",
  2930. iacute: "\u00ED",
  2931. icirc: "\u00EE",
  2932. iuml: "\u00EF",
  2933. eth: "\u00F0",
  2934. ntilde: "\u00F1",
  2935. ograve: "\u00F2",
  2936. oacute: "\u00F3",
  2937. ocirc: "\u00F4",
  2938. otilde: "\u00F5",
  2939. ouml: "\u00F6",
  2940. divide: "\u00F7",
  2941. oslash: "\u00F8",
  2942. ugrave: "\u00F9",
  2943. uacute: "\u00FA",
  2944. ucirc: "\u00FB",
  2945. uuml: "\u00FC",
  2946. yacute: "\u00FD",
  2947. thorn: "\u00FE",
  2948. yuml: "\u00FF",
  2949. OElig: "\u0152",
  2950. oelig: "\u0153",
  2951. Scaron: "\u0160",
  2952. scaron: "\u0161",
  2953. Yuml: "\u0178",
  2954. fnof: "\u0192",
  2955. circ: "\u02C6",
  2956. tilde: "\u02DC",
  2957. Alpha: "\u0391",
  2958. Beta: "\u0392",
  2959. Gamma: "\u0393",
  2960. Delta: "\u0394",
  2961. Epsilon: "\u0395",
  2962. Zeta: "\u0396",
  2963. Eta: "\u0397",
  2964. Theta: "\u0398",
  2965. Iota: "\u0399",
  2966. Kappa: "\u039A",
  2967. Lambda: "\u039B",
  2968. Mu: "\u039C",
  2969. Nu: "\u039D",
  2970. Xi: "\u039E",
  2971. Omicron: "\u039F",
  2972. Pi: "\u03A0",
  2973. Rho: "\u03A1",
  2974. Sigma: "\u03A3",
  2975. Tau: "\u03A4",
  2976. Upsilon: "\u03A5",
  2977. Phi: "\u03A6",
  2978. Chi: "\u03A7",
  2979. Psi: "\u03A8",
  2980. Omega: "\u03A9",
  2981. alpha: "\u03B1",
  2982. beta: "\u03B2",
  2983. gamma: "\u03B3",
  2984. delta: "\u03B4",
  2985. epsilon: "\u03B5",
  2986. zeta: "\u03B6",
  2987. eta: "\u03B7",
  2988. theta: "\u03B8",
  2989. iota: "\u03B9",
  2990. kappa: "\u03BA",
  2991. lambda: "\u03BB",
  2992. mu: "\u03BC",
  2993. nu: "\u03BD",
  2994. xi: "\u03BE",
  2995. omicron: "\u03BF",
  2996. pi: "\u03C0",
  2997. rho: "\u03C1",
  2998. sigmaf: "\u03C2",
  2999. sigma: "\u03C3",
  3000. tau: "\u03C4",
  3001. upsilon: "\u03C5",
  3002. phi: "\u03C6",
  3003. chi: "\u03C7",
  3004. psi: "\u03C8",
  3005. omega: "\u03C9",
  3006. thetasym: "\u03D1",
  3007. upsih: "\u03D2",
  3008. piv: "\u03D6",
  3009. ensp: "\u2002",
  3010. emsp: "\u2003",
  3011. thinsp: "\u2009",
  3012. zwnj: "\u200C",
  3013. zwj: "\u200D",
  3014. lrm: "\u200E",
  3015. rlm: "\u200F",
  3016. ndash: "\u2013",
  3017. mdash: "\u2014",
  3018. lsquo: "\u2018",
  3019. rsquo: "\u2019",
  3020. sbquo: "\u201A",
  3021. ldquo: "\u201C",
  3022. rdquo: "\u201D",
  3023. bdquo: "\u201E",
  3024. dagger: "\u2020",
  3025. Dagger: "\u2021",
  3026. bull: "\u2022",
  3027. hellip: "\u2026",
  3028. permil: "\u2030",
  3029. prime: "\u2032",
  3030. Prime: "\u2033",
  3031. lsaquo: "\u2039",
  3032. rsaquo: "\u203A",
  3033. oline: "\u203E",
  3034. frasl: "\u2044",
  3035. euro: "\u20AC",
  3036. image: "\u2111",
  3037. weierp: "\u2118",
  3038. real: "\u211C",
  3039. trade: "\u2122",
  3040. alefsym: "\u2135",
  3041. larr: "\u2190",
  3042. uarr: "\u2191",
  3043. rarr: "\u2192",
  3044. darr: "\u2193",
  3045. harr: "\u2194",
  3046. crarr: "\u21B5",
  3047. lArr: "\u21D0",
  3048. uArr: "\u21D1",
  3049. rArr: "\u21D2",
  3050. dArr: "\u21D3",
  3051. hArr: "\u21D4",
  3052. forall: "\u2200",
  3053. part: "\u2202",
  3054. exist: "\u2203",
  3055. empty: "\u2205",
  3056. nabla: "\u2207",
  3057. isin: "\u2208",
  3058. notin: "\u2209",
  3059. ni: "\u220B",
  3060. prod: "\u220F",
  3061. sum: "\u2211",
  3062. minus: "\u2212",
  3063. lowast: "\u2217",
  3064. radic: "\u221A",
  3065. prop: "\u221D",
  3066. infin: "\u221E",
  3067. ang: "\u2220",
  3068. and: "\u2227",
  3069. or: "\u2228",
  3070. cap: "\u2229",
  3071. cup: "\u222A",
  3072. int: "\u222B",
  3073. there4: "\u2234",
  3074. sim: "\u223C",
  3075. cong: "\u2245",
  3076. asymp: "\u2248",
  3077. ne: "\u2260",
  3078. equiv: "\u2261",
  3079. le: "\u2264",
  3080. ge: "\u2265",
  3081. sub: "\u2282",
  3082. sup: "\u2283",
  3083. nsub: "\u2284",
  3084. sube: "\u2286",
  3085. supe: "\u2287",
  3086. oplus: "\u2295",
  3087. otimes: "\u2297",
  3088. perp: "\u22A5",
  3089. sdot: "\u22C5",
  3090. lceil: "\u2308",
  3091. rceil: "\u2309",
  3092. lfloor: "\u230A",
  3093. rfloor: "\u230B",
  3094. lang: "\u2329",
  3095. rang: "\u232A",
  3096. loz: "\u25CA",
  3097. spades: "\u2660",
  3098. clubs: "\u2663",
  3099. hearts: "\u2665",
  3100. diams: "\u2666"
  3101. };
  3102. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3103. const DECIMAL_NUMBER = /^\d+$/;
  3104. types$1.j_oTag = new TokContext("<tag", false);
  3105. types$1.j_cTag = new TokContext("</tag", false);
  3106. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3107. types.jsxName = new TokenType("jsxName");
  3108. types.jsxText = new TokenType("jsxText", {
  3109. beforeExpr: true
  3110. });
  3111. types.jsxTagStart = new TokenType("jsxTagStart", {
  3112. startsExpr: true
  3113. });
  3114. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3115. types.jsxTagStart.updateContext = function () {
  3116. this.state.context.push(types$1.j_expr);
  3117. this.state.context.push(types$1.j_oTag);
  3118. this.state.exprAllowed = false;
  3119. };
  3120. types.jsxTagEnd.updateContext = function (prevType) {
  3121. const out = this.state.context.pop();
  3122. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3123. this.state.context.pop();
  3124. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3125. } else {
  3126. this.state.exprAllowed = true;
  3127. }
  3128. };
  3129. function isFragment(object) {
  3130. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3131. }
  3132. function getQualifiedJSXName(object) {
  3133. if (object.type === "JSXIdentifier") {
  3134. return object.name;
  3135. }
  3136. if (object.type === "JSXNamespacedName") {
  3137. return object.namespace.name + ":" + object.name.name;
  3138. }
  3139. if (object.type === "JSXMemberExpression") {
  3140. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3141. }
  3142. throw new Error("Node had unexpected type: " + object.type);
  3143. }
  3144. var jsx = (superClass => class extends superClass {
  3145. jsxReadToken() {
  3146. let out = "";
  3147. let chunkStart = this.state.pos;
  3148. for (;;) {
  3149. if (this.state.pos >= this.length) {
  3150. throw this.raise(this.state.start, "Unterminated JSX contents");
  3151. }
  3152. const ch = this.input.charCodeAt(this.state.pos);
  3153. switch (ch) {
  3154. case 60:
  3155. case 123:
  3156. if (this.state.pos === this.state.start) {
  3157. if (ch === 60 && this.state.exprAllowed) {
  3158. ++this.state.pos;
  3159. return this.finishToken(types.jsxTagStart);
  3160. }
  3161. return super.getTokenFromCode(ch);
  3162. }
  3163. out += this.input.slice(chunkStart, this.state.pos);
  3164. return this.finishToken(types.jsxText, out);
  3165. case 38:
  3166. out += this.input.slice(chunkStart, this.state.pos);
  3167. out += this.jsxReadEntity();
  3168. chunkStart = this.state.pos;
  3169. break;
  3170. default:
  3171. if (isNewLine(ch)) {
  3172. out += this.input.slice(chunkStart, this.state.pos);
  3173. out += this.jsxReadNewLine(true);
  3174. chunkStart = this.state.pos;
  3175. } else {
  3176. ++this.state.pos;
  3177. }
  3178. }
  3179. }
  3180. }
  3181. jsxReadNewLine(normalizeCRLF) {
  3182. const ch = this.input.charCodeAt(this.state.pos);
  3183. let out;
  3184. ++this.state.pos;
  3185. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3186. ++this.state.pos;
  3187. out = normalizeCRLF ? "\n" : "\r\n";
  3188. } else {
  3189. out = String.fromCharCode(ch);
  3190. }
  3191. ++this.state.curLine;
  3192. this.state.lineStart = this.state.pos;
  3193. return out;
  3194. }
  3195. jsxReadString(quote) {
  3196. let out = "";
  3197. let chunkStart = ++this.state.pos;
  3198. for (;;) {
  3199. if (this.state.pos >= this.length) {
  3200. throw this.raise(this.state.start, "Unterminated string constant");
  3201. }
  3202. const ch = this.input.charCodeAt(this.state.pos);
  3203. if (ch === quote) break;
  3204. if (ch === 38) {
  3205. out += this.input.slice(chunkStart, this.state.pos);
  3206. out += this.jsxReadEntity();
  3207. chunkStart = this.state.pos;
  3208. } else if (isNewLine(ch)) {
  3209. out += this.input.slice(chunkStart, this.state.pos);
  3210. out += this.jsxReadNewLine(false);
  3211. chunkStart = this.state.pos;
  3212. } else {
  3213. ++this.state.pos;
  3214. }
  3215. }
  3216. out += this.input.slice(chunkStart, this.state.pos++);
  3217. return this.finishToken(types.string, out);
  3218. }
  3219. jsxReadEntity() {
  3220. let str = "";
  3221. let count = 0;
  3222. let entity;
  3223. let ch = this.input[this.state.pos];
  3224. const startPos = ++this.state.pos;
  3225. while (this.state.pos < this.length && count++ < 10) {
  3226. ch = this.input[this.state.pos++];
  3227. if (ch === ";") {
  3228. if (str[0] === "#") {
  3229. if (str[1] === "x") {
  3230. str = str.substr(2);
  3231. if (HEX_NUMBER.test(str)) {
  3232. entity = String.fromCodePoint(parseInt(str, 16));
  3233. }
  3234. } else {
  3235. str = str.substr(1);
  3236. if (DECIMAL_NUMBER.test(str)) {
  3237. entity = String.fromCodePoint(parseInt(str, 10));
  3238. }
  3239. }
  3240. } else {
  3241. entity = entities[str];
  3242. }
  3243. break;
  3244. }
  3245. str += ch;
  3246. }
  3247. if (!entity) {
  3248. this.state.pos = startPos;
  3249. return "&";
  3250. }
  3251. return entity;
  3252. }
  3253. jsxReadWord() {
  3254. let ch;
  3255. const start = this.state.pos;
  3256. do {
  3257. ch = this.input.charCodeAt(++this.state.pos);
  3258. } while (isIdentifierChar(ch) || ch === 45);
  3259. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3260. }
  3261. jsxParseIdentifier() {
  3262. const node = this.startNode();
  3263. if (this.match(types.jsxName)) {
  3264. node.name = this.state.value;
  3265. } else if (this.state.type.keyword) {
  3266. node.name = this.state.type.keyword;
  3267. } else {
  3268. this.unexpected();
  3269. }
  3270. this.next();
  3271. return this.finishNode(node, "JSXIdentifier");
  3272. }
  3273. jsxParseNamespacedName() {
  3274. const startPos = this.state.start;
  3275. const startLoc = this.state.startLoc;
  3276. const name = this.jsxParseIdentifier();
  3277. if (!this.eat(types.colon)) return name;
  3278. const node = this.startNodeAt(startPos, startLoc);
  3279. node.namespace = name;
  3280. node.name = this.jsxParseIdentifier();
  3281. return this.finishNode(node, "JSXNamespacedName");
  3282. }
  3283. jsxParseElementName() {
  3284. const startPos = this.state.start;
  3285. const startLoc = this.state.startLoc;
  3286. let node = this.jsxParseNamespacedName();
  3287. if (node.type === "JSXNamespacedName") {
  3288. return node;
  3289. }
  3290. while (this.eat(types.dot)) {
  3291. const newNode = this.startNodeAt(startPos, startLoc);
  3292. newNode.object = node;
  3293. newNode.property = this.jsxParseIdentifier();
  3294. node = this.finishNode(newNode, "JSXMemberExpression");
  3295. }
  3296. return node;
  3297. }
  3298. jsxParseAttributeValue() {
  3299. let node;
  3300. switch (this.state.type) {
  3301. case types.braceL:
  3302. node = this.startNode();
  3303. this.next();
  3304. node = this.jsxParseExpressionContainer(node);
  3305. if (node.expression.type === "JSXEmptyExpression") {
  3306. this.raise(node.start, "JSX attributes must only be assigned a non-empty expression");
  3307. }
  3308. return node;
  3309. case types.jsxTagStart:
  3310. case types.string:
  3311. return this.parseExprAtom();
  3312. default:
  3313. throw this.raise(this.state.start, "JSX value should be either an expression or a quoted JSX text");
  3314. }
  3315. }
  3316. jsxParseEmptyExpression() {
  3317. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3318. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3319. }
  3320. jsxParseSpreadChild(node) {
  3321. this.next();
  3322. node.expression = this.parseExpression();
  3323. this.expect(types.braceR);
  3324. return this.finishNode(node, "JSXSpreadChild");
  3325. }
  3326. jsxParseExpressionContainer(node) {
  3327. if (this.match(types.braceR)) {
  3328. node.expression = this.jsxParseEmptyExpression();
  3329. } else {
  3330. node.expression = this.parseExpression();
  3331. }
  3332. this.expect(types.braceR);
  3333. return this.finishNode(node, "JSXExpressionContainer");
  3334. }
  3335. jsxParseAttribute() {
  3336. const node = this.startNode();
  3337. if (this.eat(types.braceL)) {
  3338. this.expect(types.ellipsis);
  3339. node.argument = this.parseMaybeAssign();
  3340. this.expect(types.braceR);
  3341. return this.finishNode(node, "JSXSpreadAttribute");
  3342. }
  3343. node.name = this.jsxParseNamespacedName();
  3344. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3345. return this.finishNode(node, "JSXAttribute");
  3346. }
  3347. jsxParseOpeningElementAt(startPos, startLoc) {
  3348. const node = this.startNodeAt(startPos, startLoc);
  3349. if (this.match(types.jsxTagEnd)) {
  3350. this.expect(types.jsxTagEnd);
  3351. return this.finishNode(node, "JSXOpeningFragment");
  3352. }
  3353. node.name = this.jsxParseElementName();
  3354. return this.jsxParseOpeningElementAfterName(node);
  3355. }
  3356. jsxParseOpeningElementAfterName(node) {
  3357. const attributes = [];
  3358. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3359. attributes.push(this.jsxParseAttribute());
  3360. }
  3361. node.attributes = attributes;
  3362. node.selfClosing = this.eat(types.slash);
  3363. this.expect(types.jsxTagEnd);
  3364. return this.finishNode(node, "JSXOpeningElement");
  3365. }
  3366. jsxParseClosingElementAt(startPos, startLoc) {
  3367. const node = this.startNodeAt(startPos, startLoc);
  3368. if (this.match(types.jsxTagEnd)) {
  3369. this.expect(types.jsxTagEnd);
  3370. return this.finishNode(node, "JSXClosingFragment");
  3371. }
  3372. node.name = this.jsxParseElementName();
  3373. this.expect(types.jsxTagEnd);
  3374. return this.finishNode(node, "JSXClosingElement");
  3375. }
  3376. jsxParseElementAt(startPos, startLoc) {
  3377. const node = this.startNodeAt(startPos, startLoc);
  3378. const children = [];
  3379. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3380. let closingElement = null;
  3381. if (!openingElement.selfClosing) {
  3382. contents: for (;;) {
  3383. switch (this.state.type) {
  3384. case types.jsxTagStart:
  3385. startPos = this.state.start;
  3386. startLoc = this.state.startLoc;
  3387. this.next();
  3388. if (this.eat(types.slash)) {
  3389. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3390. break contents;
  3391. }
  3392. children.push(this.jsxParseElementAt(startPos, startLoc));
  3393. break;
  3394. case types.jsxText:
  3395. children.push(this.parseExprAtom());
  3396. break;
  3397. case types.braceL:
  3398. {
  3399. const node = this.startNode();
  3400. this.next();
  3401. if (this.match(types.ellipsis)) {
  3402. children.push(this.jsxParseSpreadChild(node));
  3403. } else {
  3404. children.push(this.jsxParseExpressionContainer(node));
  3405. }
  3406. break;
  3407. }
  3408. default:
  3409. throw this.unexpected();
  3410. }
  3411. }
  3412. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3413. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <>");
  3414. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3415. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
  3416. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3417. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3418. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
  3419. }
  3420. }
  3421. }
  3422. if (isFragment(openingElement)) {
  3423. node.openingFragment = openingElement;
  3424. node.closingFragment = closingElement;
  3425. } else {
  3426. node.openingElement = openingElement;
  3427. node.closingElement = closingElement;
  3428. }
  3429. node.children = children;
  3430. if (this.isRelational("<")) {
  3431. throw this.raise(this.state.start, "Adjacent JSX elements must be wrapped in an enclosing tag. " + "Did you want a JSX fragment <>...</>?");
  3432. }
  3433. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3434. }
  3435. jsxParseElement() {
  3436. const startPos = this.state.start;
  3437. const startLoc = this.state.startLoc;
  3438. this.next();
  3439. return this.jsxParseElementAt(startPos, startLoc);
  3440. }
  3441. parseExprAtom(refExpressionErrors) {
  3442. if (this.match(types.jsxText)) {
  3443. return this.parseLiteral(this.state.value, "JSXText");
  3444. } else if (this.match(types.jsxTagStart)) {
  3445. return this.jsxParseElement();
  3446. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3447. this.finishToken(types.jsxTagStart);
  3448. return this.jsxParseElement();
  3449. } else {
  3450. return super.parseExprAtom(refExpressionErrors);
  3451. }
  3452. }
  3453. getTokenFromCode(code) {
  3454. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  3455. const context = this.curContext();
  3456. if (context === types$1.j_expr) {
  3457. return this.jsxReadToken();
  3458. }
  3459. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  3460. if (isIdentifierStart(code)) {
  3461. return this.jsxReadWord();
  3462. }
  3463. if (code === 62) {
  3464. ++this.state.pos;
  3465. return this.finishToken(types.jsxTagEnd);
  3466. }
  3467. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  3468. return this.jsxReadString(code);
  3469. }
  3470. }
  3471. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  3472. ++this.state.pos;
  3473. return this.finishToken(types.jsxTagStart);
  3474. }
  3475. return super.getTokenFromCode(code);
  3476. }
  3477. updateContext(prevType) {
  3478. if (this.match(types.braceL)) {
  3479. const curContext = this.curContext();
  3480. if (curContext === types$1.j_oTag) {
  3481. this.state.context.push(types$1.braceExpression);
  3482. } else if (curContext === types$1.j_expr) {
  3483. this.state.context.push(types$1.templateQuasi);
  3484. } else {
  3485. super.updateContext(prevType);
  3486. }
  3487. this.state.exprAllowed = true;
  3488. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  3489. this.state.context.length -= 2;
  3490. this.state.context.push(types$1.j_cTag);
  3491. this.state.exprAllowed = false;
  3492. } else {
  3493. return super.updateContext(prevType);
  3494. }
  3495. }
  3496. });
  3497. class Scope {
  3498. constructor(flags) {
  3499. this.var = [];
  3500. this.lexical = [];
  3501. this.functions = [];
  3502. this.flags = flags;
  3503. }
  3504. }
  3505. class ScopeHandler {
  3506. constructor(raise, inModule) {
  3507. this.scopeStack = [];
  3508. this.undefinedExports = new Map();
  3509. this.undefinedPrivateNames = new Map();
  3510. this.raise = raise;
  3511. this.inModule = inModule;
  3512. }
  3513. get inFunction() {
  3514. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  3515. }
  3516. get inGenerator() {
  3517. return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
  3518. }
  3519. get inAsync() {
  3520. for (let i = this.scopeStack.length - 1;; i--) {
  3521. const scope = this.scopeStack[i];
  3522. const isVarScope = scope.flags & SCOPE_VAR;
  3523. const isClassScope = scope.flags & SCOPE_CLASS;
  3524. if (isClassScope && !isVarScope) {
  3525. return false;
  3526. } else if (isVarScope) {
  3527. return (scope.flags & SCOPE_ASYNC) > 0;
  3528. }
  3529. }
  3530. }
  3531. get allowSuper() {
  3532. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  3533. }
  3534. get allowDirectSuper() {
  3535. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  3536. }
  3537. get inClass() {
  3538. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  3539. }
  3540. get inNonArrowFunction() {
  3541. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  3542. }
  3543. get treatFunctionsAsVar() {
  3544. return this.treatFunctionsAsVarInScope(this.currentScope());
  3545. }
  3546. createScope(flags) {
  3547. return new Scope(flags);
  3548. }
  3549. enter(flags) {
  3550. this.scopeStack.push(this.createScope(flags));
  3551. }
  3552. exit() {
  3553. this.scopeStack.pop();
  3554. }
  3555. treatFunctionsAsVarInScope(scope) {
  3556. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  3557. }
  3558. declareName(name, bindingType, pos) {
  3559. let scope = this.currentScope();
  3560. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  3561. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3562. if (bindingType & BIND_SCOPE_FUNCTION) {
  3563. scope.functions.push(name);
  3564. } else {
  3565. scope.lexical.push(name);
  3566. }
  3567. if (bindingType & BIND_SCOPE_LEXICAL) {
  3568. this.maybeExportDefined(scope, name);
  3569. }
  3570. } else if (bindingType & BIND_SCOPE_VAR) {
  3571. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  3572. scope = this.scopeStack[i];
  3573. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3574. scope.var.push(name);
  3575. this.maybeExportDefined(scope, name);
  3576. if (scope.flags & SCOPE_VAR) break;
  3577. }
  3578. }
  3579. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  3580. this.undefinedExports.delete(name);
  3581. }
  3582. }
  3583. maybeExportDefined(scope, name) {
  3584. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  3585. this.undefinedExports.delete(name);
  3586. }
  3587. }
  3588. checkRedeclarationInScope(scope, name, bindingType, pos) {
  3589. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  3590. this.raise(pos, `Identifier '${name}' has already been declared`);
  3591. }
  3592. }
  3593. isRedeclaredInScope(scope, name, bindingType) {
  3594. if (!(bindingType & BIND_KIND_VALUE)) return false;
  3595. if (bindingType & BIND_SCOPE_LEXICAL) {
  3596. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  3597. }
  3598. if (bindingType & BIND_SCOPE_FUNCTION) {
  3599. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  3600. }
  3601. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  3602. }
  3603. checkLocalExport(id) {
  3604. 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) {
  3605. this.undefinedExports.set(id.name, id.start);
  3606. }
  3607. }
  3608. currentScope() {
  3609. return this.scopeStack[this.scopeStack.length - 1];
  3610. }
  3611. currentVarScope() {
  3612. for (let i = this.scopeStack.length - 1;; i--) {
  3613. const scope = this.scopeStack[i];
  3614. if (scope.flags & SCOPE_VAR) {
  3615. return scope;
  3616. }
  3617. }
  3618. }
  3619. currentThisScope() {
  3620. for (let i = this.scopeStack.length - 1;; i--) {
  3621. const scope = this.scopeStack[i];
  3622. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  3623. return scope;
  3624. }
  3625. }
  3626. }
  3627. }
  3628. class TypeScriptScope extends Scope {
  3629. constructor(...args) {
  3630. super(...args);
  3631. this.types = [];
  3632. this.enums = [];
  3633. this.constEnums = [];
  3634. this.classes = [];
  3635. this.exportOnlyBindings = [];
  3636. }
  3637. }
  3638. class TypeScriptScopeHandler extends ScopeHandler {
  3639. createScope(flags) {
  3640. return new TypeScriptScope(flags);
  3641. }
  3642. declareName(name, bindingType, pos) {
  3643. const scope = this.currentScope();
  3644. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  3645. this.maybeExportDefined(scope, name);
  3646. scope.exportOnlyBindings.push(name);
  3647. return;
  3648. }
  3649. super.declareName(...arguments);
  3650. if (bindingType & BIND_KIND_TYPE) {
  3651. if (!(bindingType & BIND_KIND_VALUE)) {
  3652. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3653. this.maybeExportDefined(scope, name);
  3654. }
  3655. scope.types.push(name);
  3656. }
  3657. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  3658. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  3659. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  3660. }
  3661. isRedeclaredInScope(scope, name, bindingType) {
  3662. if (scope.enums.indexOf(name) > -1) {
  3663. if (bindingType & BIND_FLAGS_TS_ENUM) {
  3664. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  3665. const wasConst = scope.constEnums.indexOf(name) > -1;
  3666. return isConst !== wasConst;
  3667. }
  3668. return true;
  3669. }
  3670. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  3671. if (scope.lexical.indexOf(name) > -1) {
  3672. return !!(bindingType & BIND_KIND_VALUE);
  3673. } else {
  3674. return false;
  3675. }
  3676. }
  3677. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  3678. return true;
  3679. }
  3680. return super.isRedeclaredInScope(...arguments);
  3681. }
  3682. checkLocalExport(id) {
  3683. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  3684. super.checkLocalExport(id);
  3685. }
  3686. }
  3687. }
  3688. function nonNull(x) {
  3689. if (x == null) {
  3690. throw new Error(`Unexpected ${x} value.`);
  3691. }
  3692. return x;
  3693. }
  3694. function assert(x) {
  3695. if (!x) {
  3696. throw new Error("Assert fail");
  3697. }
  3698. }
  3699. function keywordTypeFromName(value) {
  3700. switch (value) {
  3701. case "any":
  3702. return "TSAnyKeyword";
  3703. case "boolean":
  3704. return "TSBooleanKeyword";
  3705. case "bigint":
  3706. return "TSBigIntKeyword";
  3707. case "never":
  3708. return "TSNeverKeyword";
  3709. case "number":
  3710. return "TSNumberKeyword";
  3711. case "object":
  3712. return "TSObjectKeyword";
  3713. case "string":
  3714. return "TSStringKeyword";
  3715. case "symbol":
  3716. return "TSSymbolKeyword";
  3717. case "undefined":
  3718. return "TSUndefinedKeyword";
  3719. case "unknown":
  3720. return "TSUnknownKeyword";
  3721. default:
  3722. return undefined;
  3723. }
  3724. }
  3725. var typescript = (superClass => class extends superClass {
  3726. getScopeHandler() {
  3727. return TypeScriptScopeHandler;
  3728. }
  3729. tsIsIdentifier() {
  3730. return this.match(types.name);
  3731. }
  3732. tsNextTokenCanFollowModifier() {
  3733. this.next();
  3734. 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);
  3735. }
  3736. tsParseModifier(allowedModifiers) {
  3737. if (!this.match(types.name)) {
  3738. return undefined;
  3739. }
  3740. const modifier = this.state.value;
  3741. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  3742. return modifier;
  3743. }
  3744. return undefined;
  3745. }
  3746. tsParseModifiers(allowedModifiers) {
  3747. const modifiers = Object.create(null);
  3748. while (true) {
  3749. const startPos = this.state.start;
  3750. const modifier = this.tsParseModifier(allowedModifiers);
  3751. if (!modifier) break;
  3752. if (Object.hasOwnProperty.call(modifiers, modifier)) {
  3753. this.raise(startPos, `Duplicate modifier: '${modifier}'`);
  3754. }
  3755. modifiers[modifier] = true;
  3756. }
  3757. return modifiers;
  3758. }
  3759. tsIsListTerminator(kind) {
  3760. switch (kind) {
  3761. case "EnumMembers":
  3762. case "TypeMembers":
  3763. return this.match(types.braceR);
  3764. case "HeritageClauseElement":
  3765. return this.match(types.braceL);
  3766. case "TupleElementTypes":
  3767. return this.match(types.bracketR);
  3768. case "TypeParametersOrArguments":
  3769. return this.isRelational(">");
  3770. }
  3771. throw new Error("Unreachable");
  3772. }
  3773. tsParseList(kind, parseElement) {
  3774. const result = [];
  3775. while (!this.tsIsListTerminator(kind)) {
  3776. result.push(parseElement());
  3777. }
  3778. return result;
  3779. }
  3780. tsParseDelimitedList(kind, parseElement) {
  3781. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  3782. }
  3783. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  3784. const result = [];
  3785. while (true) {
  3786. if (this.tsIsListTerminator(kind)) {
  3787. break;
  3788. }
  3789. const element = parseElement();
  3790. if (element == null) {
  3791. return undefined;
  3792. }
  3793. result.push(element);
  3794. if (this.eat(types.comma)) {
  3795. continue;
  3796. }
  3797. if (this.tsIsListTerminator(kind)) {
  3798. break;
  3799. }
  3800. if (expectSuccess) {
  3801. this.expect(types.comma);
  3802. }
  3803. return undefined;
  3804. }
  3805. return result;
  3806. }
  3807. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  3808. if (!skipFirstToken) {
  3809. if (bracket) {
  3810. this.expect(types.bracketL);
  3811. } else {
  3812. this.expectRelational("<");
  3813. }
  3814. }
  3815. const result = this.tsParseDelimitedList(kind, parseElement);
  3816. if (bracket) {
  3817. this.expect(types.bracketR);
  3818. } else {
  3819. this.expectRelational(">");
  3820. }
  3821. return result;
  3822. }
  3823. tsParseImportType() {
  3824. const node = this.startNode();
  3825. this.expect(types._import);
  3826. this.expect(types.parenL);
  3827. if (!this.match(types.string)) {
  3828. this.raise(this.state.start, "Argument in a type import must be a string literal");
  3829. }
  3830. node.argument = this.parseExprAtom();
  3831. this.expect(types.parenR);
  3832. if (this.eat(types.dot)) {
  3833. node.qualifier = this.tsParseEntityName(true);
  3834. }
  3835. if (this.isRelational("<")) {
  3836. node.typeParameters = this.tsParseTypeArguments();
  3837. }
  3838. return this.finishNode(node, "TSImportType");
  3839. }
  3840. tsParseEntityName(allowReservedWords) {
  3841. let entity = this.parseIdentifier();
  3842. while (this.eat(types.dot)) {
  3843. const node = this.startNodeAtNode(entity);
  3844. node.left = entity;
  3845. node.right = this.parseIdentifier(allowReservedWords);
  3846. entity = this.finishNode(node, "TSQualifiedName");
  3847. }
  3848. return entity;
  3849. }
  3850. tsParseTypeReference() {
  3851. const node = this.startNode();
  3852. node.typeName = this.tsParseEntityName(false);
  3853. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  3854. node.typeParameters = this.tsParseTypeArguments();
  3855. }
  3856. return this.finishNode(node, "TSTypeReference");
  3857. }
  3858. tsParseThisTypePredicate(lhs) {
  3859. this.next();
  3860. const node = this.startNodeAtNode(lhs);
  3861. node.parameterName = lhs;
  3862. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  3863. return this.finishNode(node, "TSTypePredicate");
  3864. }
  3865. tsParseThisTypeNode() {
  3866. const node = this.startNode();
  3867. this.next();
  3868. return this.finishNode(node, "TSThisType");
  3869. }
  3870. tsParseTypeQuery() {
  3871. const node = this.startNode();
  3872. this.expect(types._typeof);
  3873. if (this.match(types._import)) {
  3874. node.exprName = this.tsParseImportType();
  3875. } else {
  3876. node.exprName = this.tsParseEntityName(true);
  3877. }
  3878. return this.finishNode(node, "TSTypeQuery");
  3879. }
  3880. tsParseTypeParameter() {
  3881. const node = this.startNode();
  3882. node.name = this.parseIdentifierName(node.start);
  3883. node.constraint = this.tsEatThenParseType(types._extends);
  3884. node.default = this.tsEatThenParseType(types.eq);
  3885. return this.finishNode(node, "TSTypeParameter");
  3886. }
  3887. tsTryParseTypeParameters() {
  3888. if (this.isRelational("<")) {
  3889. return this.tsParseTypeParameters();
  3890. }
  3891. }
  3892. tsParseTypeParameters() {
  3893. const node = this.startNode();
  3894. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  3895. this.next();
  3896. } else {
  3897. this.unexpected();
  3898. }
  3899. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  3900. return this.finishNode(node, "TSTypeParameterDeclaration");
  3901. }
  3902. tsTryNextParseConstantContext() {
  3903. if (this.lookahead().type === types._const) {
  3904. this.next();
  3905. return this.tsParseTypeReference();
  3906. }
  3907. return null;
  3908. }
  3909. tsFillSignature(returnToken, signature) {
  3910. const returnTokenRequired = returnToken === types.arrow;
  3911. signature.typeParameters = this.tsTryParseTypeParameters();
  3912. this.expect(types.parenL);
  3913. signature.parameters = this.tsParseBindingListForSignature();
  3914. if (returnTokenRequired) {
  3915. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  3916. } else if (this.match(returnToken)) {
  3917. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  3918. }
  3919. }
  3920. tsParseBindingListForSignature() {
  3921. return this.parseBindingList(types.parenR, 41).map(pattern => {
  3922. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  3923. this.raise(pattern.start, "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern," + `instead got ${pattern.type}`);
  3924. }
  3925. return pattern;
  3926. });
  3927. }
  3928. tsParseTypeMemberSemicolon() {
  3929. if (!this.eat(types.comma)) {
  3930. this.semicolon();
  3931. }
  3932. }
  3933. tsParseSignatureMember(kind, node) {
  3934. this.tsFillSignature(types.colon, node);
  3935. this.tsParseTypeMemberSemicolon();
  3936. return this.finishNode(node, kind);
  3937. }
  3938. tsIsUnambiguouslyIndexSignature() {
  3939. this.next();
  3940. return this.eat(types.name) && this.match(types.colon);
  3941. }
  3942. tsTryParseIndexSignature(node) {
  3943. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  3944. return undefined;
  3945. }
  3946. this.expect(types.bracketL);
  3947. const id = this.parseIdentifier();
  3948. id.typeAnnotation = this.tsParseTypeAnnotation();
  3949. this.resetEndLocation(id);
  3950. this.expect(types.bracketR);
  3951. node.parameters = [id];
  3952. const type = this.tsTryParseTypeAnnotation();
  3953. if (type) node.typeAnnotation = type;
  3954. this.tsParseTypeMemberSemicolon();
  3955. return this.finishNode(node, "TSIndexSignature");
  3956. }
  3957. tsParsePropertyOrMethodSignature(node, readonly) {
  3958. if (this.eat(types.question)) node.optional = true;
  3959. const nodeAny = node;
  3960. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  3961. const method = nodeAny;
  3962. this.tsFillSignature(types.colon, method);
  3963. this.tsParseTypeMemberSemicolon();
  3964. return this.finishNode(method, "TSMethodSignature");
  3965. } else {
  3966. const property = nodeAny;
  3967. if (readonly) property.readonly = true;
  3968. const type = this.tsTryParseTypeAnnotation();
  3969. if (type) property.typeAnnotation = type;
  3970. this.tsParseTypeMemberSemicolon();
  3971. return this.finishNode(property, "TSPropertySignature");
  3972. }
  3973. }
  3974. tsParseTypeMember() {
  3975. const node = this.startNode();
  3976. if (this.match(types.parenL) || this.isRelational("<")) {
  3977. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  3978. }
  3979. if (this.match(types._new)) {
  3980. const id = this.startNode();
  3981. this.next();
  3982. if (this.match(types.parenL) || this.isRelational("<")) {
  3983. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  3984. } else {
  3985. node.key = this.createIdentifier(id, "new");
  3986. return this.tsParsePropertyOrMethodSignature(node, false);
  3987. }
  3988. }
  3989. const readonly = !!this.tsParseModifier(["readonly"]);
  3990. const idx = this.tsTryParseIndexSignature(node);
  3991. if (idx) {
  3992. if (readonly) node.readonly = true;
  3993. return idx;
  3994. }
  3995. this.parsePropertyName(node, false);
  3996. return this.tsParsePropertyOrMethodSignature(node, readonly);
  3997. }
  3998. tsParseTypeLiteral() {
  3999. const node = this.startNode();
  4000. node.members = this.tsParseObjectTypeMembers();
  4001. return this.finishNode(node, "TSTypeLiteral");
  4002. }
  4003. tsParseObjectTypeMembers() {
  4004. this.expect(types.braceL);
  4005. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4006. this.expect(types.braceR);
  4007. return members;
  4008. }
  4009. tsIsStartOfMappedType() {
  4010. this.next();
  4011. if (this.eat(types.plusMin)) {
  4012. return this.isContextual("readonly");
  4013. }
  4014. if (this.isContextual("readonly")) {
  4015. this.next();
  4016. }
  4017. if (!this.match(types.bracketL)) {
  4018. return false;
  4019. }
  4020. this.next();
  4021. if (!this.tsIsIdentifier()) {
  4022. return false;
  4023. }
  4024. this.next();
  4025. return this.match(types._in);
  4026. }
  4027. tsParseMappedTypeParameter() {
  4028. const node = this.startNode();
  4029. node.name = this.parseIdentifierName(node.start);
  4030. node.constraint = this.tsExpectThenParseType(types._in);
  4031. return this.finishNode(node, "TSTypeParameter");
  4032. }
  4033. tsParseMappedType() {
  4034. const node = this.startNode();
  4035. this.expect(types.braceL);
  4036. if (this.match(types.plusMin)) {
  4037. node.readonly = this.state.value;
  4038. this.next();
  4039. this.expectContextual("readonly");
  4040. } else if (this.eatContextual("readonly")) {
  4041. node.readonly = true;
  4042. }
  4043. this.expect(types.bracketL);
  4044. node.typeParameter = this.tsParseMappedTypeParameter();
  4045. this.expect(types.bracketR);
  4046. if (this.match(types.plusMin)) {
  4047. node.optional = this.state.value;
  4048. this.next();
  4049. this.expect(types.question);
  4050. } else if (this.eat(types.question)) {
  4051. node.optional = true;
  4052. }
  4053. node.typeAnnotation = this.tsTryParseType();
  4054. this.semicolon();
  4055. this.expect(types.braceR);
  4056. return this.finishNode(node, "TSMappedType");
  4057. }
  4058. tsParseTupleType() {
  4059. const node = this.startNode();
  4060. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4061. let seenOptionalElement = false;
  4062. node.elementTypes.forEach(elementNode => {
  4063. if (elementNode.type === "TSOptionalType") {
  4064. seenOptionalElement = true;
  4065. } else if (seenOptionalElement && elementNode.type !== "TSRestType") {
  4066. this.raise(elementNode.start, "A required element cannot follow an optional element.");
  4067. }
  4068. });
  4069. return this.finishNode(node, "TSTupleType");
  4070. }
  4071. tsParseTupleElementType() {
  4072. if (this.match(types.ellipsis)) {
  4073. const restNode = this.startNode();
  4074. this.next();
  4075. restNode.typeAnnotation = this.tsParseType();
  4076. if (this.match(types.comma) && this.lookaheadCharCode() !== 93) {
  4077. this.raiseRestNotLast(this.state.start);
  4078. }
  4079. return this.finishNode(restNode, "TSRestType");
  4080. }
  4081. const type = this.tsParseType();
  4082. if (this.eat(types.question)) {
  4083. const optionalTypeNode = this.startNodeAtNode(type);
  4084. optionalTypeNode.typeAnnotation = type;
  4085. return this.finishNode(optionalTypeNode, "TSOptionalType");
  4086. }
  4087. return type;
  4088. }
  4089. tsParseParenthesizedType() {
  4090. const node = this.startNode();
  4091. this.expect(types.parenL);
  4092. node.typeAnnotation = this.tsParseType();
  4093. this.expect(types.parenR);
  4094. return this.finishNode(node, "TSParenthesizedType");
  4095. }
  4096. tsParseFunctionOrConstructorType(type) {
  4097. const node = this.startNode();
  4098. if (type === "TSConstructorType") {
  4099. this.expect(types._new);
  4100. }
  4101. this.tsFillSignature(types.arrow, node);
  4102. return this.finishNode(node, type);
  4103. }
  4104. tsParseLiteralTypeNode() {
  4105. const node = this.startNode();
  4106. node.literal = (() => {
  4107. switch (this.state.type) {
  4108. case types.num:
  4109. case types.string:
  4110. case types._true:
  4111. case types._false:
  4112. return this.parseExprAtom();
  4113. default:
  4114. throw this.unexpected();
  4115. }
  4116. })();
  4117. return this.finishNode(node, "TSLiteralType");
  4118. }
  4119. tsParseTemplateLiteralType() {
  4120. const node = this.startNode();
  4121. const templateNode = this.parseTemplate(false);
  4122. if (templateNode.expressions.length > 0) {
  4123. this.raise(templateNode.expressions[0].start, "Template literal types cannot have any substitution");
  4124. }
  4125. node.literal = templateNode;
  4126. return this.finishNode(node, "TSLiteralType");
  4127. }
  4128. tsParseThisTypeOrThisTypePredicate() {
  4129. const thisKeyword = this.tsParseThisTypeNode();
  4130. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4131. return this.tsParseThisTypePredicate(thisKeyword);
  4132. } else {
  4133. return thisKeyword;
  4134. }
  4135. }
  4136. tsParseNonArrayType() {
  4137. switch (this.state.type) {
  4138. case types.name:
  4139. case types._void:
  4140. case types._null:
  4141. {
  4142. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4143. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4144. const node = this.startNode();
  4145. this.next();
  4146. return this.finishNode(node, type);
  4147. }
  4148. return this.tsParseTypeReference();
  4149. }
  4150. case types.string:
  4151. case types.num:
  4152. case types._true:
  4153. case types._false:
  4154. return this.tsParseLiteralTypeNode();
  4155. case types.plusMin:
  4156. if (this.state.value === "-") {
  4157. const node = this.startNode();
  4158. if (this.lookahead().type !== types.num) {
  4159. throw this.unexpected();
  4160. }
  4161. node.literal = this.parseMaybeUnary();
  4162. return this.finishNode(node, "TSLiteralType");
  4163. }
  4164. break;
  4165. case types._this:
  4166. return this.tsParseThisTypeOrThisTypePredicate();
  4167. case types._typeof:
  4168. return this.tsParseTypeQuery();
  4169. case types._import:
  4170. return this.tsParseImportType();
  4171. case types.braceL:
  4172. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4173. case types.bracketL:
  4174. return this.tsParseTupleType();
  4175. case types.parenL:
  4176. return this.tsParseParenthesizedType();
  4177. case types.backQuote:
  4178. return this.tsParseTemplateLiteralType();
  4179. }
  4180. throw this.unexpected();
  4181. }
  4182. tsParseArrayTypeOrHigher() {
  4183. let type = this.tsParseNonArrayType();
  4184. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4185. if (this.match(types.bracketR)) {
  4186. const node = this.startNodeAtNode(type);
  4187. node.elementType = type;
  4188. this.expect(types.bracketR);
  4189. type = this.finishNode(node, "TSArrayType");
  4190. } else {
  4191. const node = this.startNodeAtNode(type);
  4192. node.objectType = type;
  4193. node.indexType = this.tsParseType();
  4194. this.expect(types.bracketR);
  4195. type = this.finishNode(node, "TSIndexedAccessType");
  4196. }
  4197. }
  4198. return type;
  4199. }
  4200. tsParseTypeOperator(operator) {
  4201. const node = this.startNode();
  4202. this.expectContextual(operator);
  4203. node.operator = operator;
  4204. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4205. if (operator === "readonly") {
  4206. this.tsCheckTypeAnnotationForReadOnly(node);
  4207. }
  4208. return this.finishNode(node, "TSTypeOperator");
  4209. }
  4210. tsCheckTypeAnnotationForReadOnly(node) {
  4211. switch (node.typeAnnotation.type) {
  4212. case "TSTupleType":
  4213. case "TSArrayType":
  4214. return;
  4215. default:
  4216. this.raise(node.start, "'readonly' type modifier is only permitted on array and tuple literal types.");
  4217. }
  4218. }
  4219. tsParseInferType() {
  4220. const node = this.startNode();
  4221. this.expectContextual("infer");
  4222. const typeParameter = this.startNode();
  4223. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4224. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4225. return this.finishNode(node, "TSInferType");
  4226. }
  4227. tsParseTypeOperatorOrHigher() {
  4228. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4229. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4230. }
  4231. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4232. this.eat(operator);
  4233. let type = parseConstituentType();
  4234. if (this.match(operator)) {
  4235. const types = [type];
  4236. while (this.eat(operator)) {
  4237. types.push(parseConstituentType());
  4238. }
  4239. const node = this.startNodeAtNode(type);
  4240. node.types = types;
  4241. type = this.finishNode(node, kind);
  4242. }
  4243. return type;
  4244. }
  4245. tsParseIntersectionTypeOrHigher() {
  4246. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4247. }
  4248. tsParseUnionTypeOrHigher() {
  4249. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4250. }
  4251. tsIsStartOfFunctionType() {
  4252. if (this.isRelational("<")) {
  4253. return true;
  4254. }
  4255. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4256. }
  4257. tsSkipParameterStart() {
  4258. if (this.match(types.name) || this.match(types._this)) {
  4259. this.next();
  4260. return true;
  4261. }
  4262. if (this.match(types.braceL)) {
  4263. let braceStackCounter = 1;
  4264. this.next();
  4265. while (braceStackCounter > 0) {
  4266. if (this.match(types.braceL)) {
  4267. ++braceStackCounter;
  4268. } else if (this.match(types.braceR)) {
  4269. --braceStackCounter;
  4270. }
  4271. this.next();
  4272. }
  4273. return true;
  4274. }
  4275. if (this.match(types.bracketL)) {
  4276. let braceStackCounter = 1;
  4277. this.next();
  4278. while (braceStackCounter > 0) {
  4279. if (this.match(types.bracketL)) {
  4280. ++braceStackCounter;
  4281. } else if (this.match(types.bracketR)) {
  4282. --braceStackCounter;
  4283. }
  4284. this.next();
  4285. }
  4286. return true;
  4287. }
  4288. return false;
  4289. }
  4290. tsIsUnambiguouslyStartOfFunctionType() {
  4291. this.next();
  4292. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4293. return true;
  4294. }
  4295. if (this.tsSkipParameterStart()) {
  4296. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4297. return true;
  4298. }
  4299. if (this.match(types.parenR)) {
  4300. this.next();
  4301. if (this.match(types.arrow)) {
  4302. return true;
  4303. }
  4304. }
  4305. }
  4306. return false;
  4307. }
  4308. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4309. return this.tsInType(() => {
  4310. const t = this.startNode();
  4311. this.expect(returnToken);
  4312. const asserts = this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4313. if (asserts && this.match(types._this)) {
  4314. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4315. if (thisTypePredicate.type === "TSThisType") {
  4316. const node = this.startNodeAtNode(t);
  4317. node.parameterName = thisTypePredicate;
  4318. node.asserts = true;
  4319. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4320. } else {
  4321. thisTypePredicate.asserts = true;
  4322. }
  4323. t.typeAnnotation = thisTypePredicate;
  4324. return this.finishNode(t, "TSTypeAnnotation");
  4325. }
  4326. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4327. if (!typePredicateVariable) {
  4328. if (!asserts) {
  4329. return this.tsParseTypeAnnotation(false, t);
  4330. }
  4331. const node = this.startNodeAtNode(t);
  4332. node.parameterName = this.parseIdentifier();
  4333. node.asserts = asserts;
  4334. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4335. return this.finishNode(t, "TSTypeAnnotation");
  4336. }
  4337. const type = this.tsParseTypeAnnotation(false);
  4338. const node = this.startNodeAtNode(t);
  4339. node.parameterName = typePredicateVariable;
  4340. node.typeAnnotation = type;
  4341. node.asserts = asserts;
  4342. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4343. return this.finishNode(t, "TSTypeAnnotation");
  4344. });
  4345. }
  4346. tsTryParseTypeOrTypePredicateAnnotation() {
  4347. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4348. }
  4349. tsTryParseTypeAnnotation() {
  4350. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4351. }
  4352. tsTryParseType() {
  4353. return this.tsEatThenParseType(types.colon);
  4354. }
  4355. tsParseTypePredicatePrefix() {
  4356. const id = this.parseIdentifier();
  4357. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4358. this.next();
  4359. return id;
  4360. }
  4361. }
  4362. tsParseTypePredicateAsserts() {
  4363. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4364. return false;
  4365. }
  4366. const containsEsc = this.state.containsEsc;
  4367. this.next();
  4368. if (!this.match(types.name) && !this.match(types._this)) {
  4369. return false;
  4370. }
  4371. if (containsEsc) {
  4372. this.raise(this.state.lastTokStart, "Escape sequence in keyword asserts");
  4373. }
  4374. return true;
  4375. }
  4376. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  4377. this.tsInType(() => {
  4378. if (eatColon) this.expect(types.colon);
  4379. t.typeAnnotation = this.tsParseType();
  4380. });
  4381. return this.finishNode(t, "TSTypeAnnotation");
  4382. }
  4383. tsParseType() {
  4384. assert(this.state.inType);
  4385. const type = this.tsParseNonConditionalType();
  4386. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  4387. return type;
  4388. }
  4389. const node = this.startNodeAtNode(type);
  4390. node.checkType = type;
  4391. node.extendsType = this.tsParseNonConditionalType();
  4392. this.expect(types.question);
  4393. node.trueType = this.tsParseType();
  4394. this.expect(types.colon);
  4395. node.falseType = this.tsParseType();
  4396. return this.finishNode(node, "TSConditionalType");
  4397. }
  4398. tsParseNonConditionalType() {
  4399. if (this.tsIsStartOfFunctionType()) {
  4400. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  4401. }
  4402. if (this.match(types._new)) {
  4403. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  4404. }
  4405. return this.tsParseUnionTypeOrHigher();
  4406. }
  4407. tsParseTypeAssertion() {
  4408. const node = this.startNode();
  4409. const _const = this.tsTryNextParseConstantContext();
  4410. node.typeAnnotation = _const || this.tsNextThenParseType();
  4411. this.expectRelational(">");
  4412. node.expression = this.parseMaybeUnary();
  4413. return this.finishNode(node, "TSTypeAssertion");
  4414. }
  4415. tsParseHeritageClause(descriptor) {
  4416. const originalStart = this.state.start;
  4417. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  4418. if (!delimitedList.length) {
  4419. this.raise(originalStart, `'${descriptor}' list cannot be empty.`);
  4420. }
  4421. return delimitedList;
  4422. }
  4423. tsParseExpressionWithTypeArguments() {
  4424. const node = this.startNode();
  4425. node.expression = this.tsParseEntityName(false);
  4426. if (this.isRelational("<")) {
  4427. node.typeParameters = this.tsParseTypeArguments();
  4428. }
  4429. return this.finishNode(node, "TSExpressionWithTypeArguments");
  4430. }
  4431. tsParseInterfaceDeclaration(node) {
  4432. node.id = this.parseIdentifier();
  4433. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  4434. node.typeParameters = this.tsTryParseTypeParameters();
  4435. if (this.eat(types._extends)) {
  4436. node.extends = this.tsParseHeritageClause("extends");
  4437. }
  4438. const body = this.startNode();
  4439. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  4440. node.body = this.finishNode(body, "TSInterfaceBody");
  4441. return this.finishNode(node, "TSInterfaceDeclaration");
  4442. }
  4443. tsParseTypeAliasDeclaration(node) {
  4444. node.id = this.parseIdentifier();
  4445. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  4446. node.typeParameters = this.tsTryParseTypeParameters();
  4447. node.typeAnnotation = this.tsExpectThenParseType(types.eq);
  4448. this.semicolon();
  4449. return this.finishNode(node, "TSTypeAliasDeclaration");
  4450. }
  4451. tsInNoContext(cb) {
  4452. const oldContext = this.state.context;
  4453. this.state.context = [oldContext[0]];
  4454. try {
  4455. return cb();
  4456. } finally {
  4457. this.state.context = oldContext;
  4458. }
  4459. }
  4460. tsInType(cb) {
  4461. const oldInType = this.state.inType;
  4462. this.state.inType = true;
  4463. try {
  4464. return cb();
  4465. } finally {
  4466. this.state.inType = oldInType;
  4467. }
  4468. }
  4469. tsEatThenParseType(token) {
  4470. return !this.match(token) ? undefined : this.tsNextThenParseType();
  4471. }
  4472. tsExpectThenParseType(token) {
  4473. return this.tsDoThenParseType(() => this.expect(token));
  4474. }
  4475. tsNextThenParseType() {
  4476. return this.tsDoThenParseType(() => this.next());
  4477. }
  4478. tsDoThenParseType(cb) {
  4479. return this.tsInType(() => {
  4480. cb();
  4481. return this.tsParseType();
  4482. });
  4483. }
  4484. tsParseEnumMember() {
  4485. const node = this.startNode();
  4486. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  4487. if (this.eat(types.eq)) {
  4488. node.initializer = this.parseMaybeAssign();
  4489. }
  4490. return this.finishNode(node, "TSEnumMember");
  4491. }
  4492. tsParseEnumDeclaration(node, isConst) {
  4493. if (isConst) node.const = true;
  4494. node.id = this.parseIdentifier();
  4495. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  4496. this.expect(types.braceL);
  4497. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  4498. this.expect(types.braceR);
  4499. return this.finishNode(node, "TSEnumDeclaration");
  4500. }
  4501. tsParseModuleBlock() {
  4502. const node = this.startNode();
  4503. this.scope.enter(SCOPE_OTHER);
  4504. this.expect(types.braceL);
  4505. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  4506. this.scope.exit();
  4507. return this.finishNode(node, "TSModuleBlock");
  4508. }
  4509. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  4510. node.id = this.parseIdentifier();
  4511. if (!nested) {
  4512. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  4513. }
  4514. if (this.eat(types.dot)) {
  4515. const inner = this.startNode();
  4516. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  4517. node.body = inner;
  4518. } else {
  4519. this.scope.enter(SCOPE_TS_MODULE);
  4520. node.body = this.tsParseModuleBlock();
  4521. this.scope.exit();
  4522. }
  4523. return this.finishNode(node, "TSModuleDeclaration");
  4524. }
  4525. tsParseAmbientExternalModuleDeclaration(node) {
  4526. if (this.isContextual("global")) {
  4527. node.global = true;
  4528. node.id = this.parseIdentifier();
  4529. } else if (this.match(types.string)) {
  4530. node.id = this.parseExprAtom();
  4531. } else {
  4532. this.unexpected();
  4533. }
  4534. if (this.match(types.braceL)) {
  4535. this.scope.enter(SCOPE_TS_MODULE);
  4536. node.body = this.tsParseModuleBlock();
  4537. this.scope.exit();
  4538. } else {
  4539. this.semicolon();
  4540. }
  4541. return this.finishNode(node, "TSModuleDeclaration");
  4542. }
  4543. tsParseImportEqualsDeclaration(node, isExport) {
  4544. node.isExport = isExport || false;
  4545. node.id = this.parseIdentifier();
  4546. this.checkLVal(node.id, BIND_LEXICAL, undefined, "import equals declaration");
  4547. this.expect(types.eq);
  4548. node.moduleReference = this.tsParseModuleReference();
  4549. this.semicolon();
  4550. return this.finishNode(node, "TSImportEqualsDeclaration");
  4551. }
  4552. tsIsExternalModuleReference() {
  4553. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  4554. }
  4555. tsParseModuleReference() {
  4556. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  4557. }
  4558. tsParseExternalModuleReference() {
  4559. const node = this.startNode();
  4560. this.expectContextual("require");
  4561. this.expect(types.parenL);
  4562. if (!this.match(types.string)) {
  4563. throw this.unexpected();
  4564. }
  4565. node.expression = this.parseExprAtom();
  4566. this.expect(types.parenR);
  4567. return this.finishNode(node, "TSExternalModuleReference");
  4568. }
  4569. tsLookAhead(f) {
  4570. const state = this.state.clone();
  4571. const res = f();
  4572. this.state = state;
  4573. return res;
  4574. }
  4575. tsTryParseAndCatch(f) {
  4576. const result = this.tryParse(abort => f() || abort());
  4577. if (result.aborted || !result.node) return undefined;
  4578. if (result.error) this.state = result.failState;
  4579. return result.node;
  4580. }
  4581. tsTryParse(f) {
  4582. const state = this.state.clone();
  4583. const result = f();
  4584. if (result !== undefined && result !== false) {
  4585. return result;
  4586. } else {
  4587. this.state = state;
  4588. return undefined;
  4589. }
  4590. }
  4591. tsTryParseDeclare(nany) {
  4592. if (this.isLineTerminator()) {
  4593. return;
  4594. }
  4595. let starttype = this.state.type;
  4596. let kind;
  4597. if (this.isContextual("let")) {
  4598. starttype = types._var;
  4599. kind = "let";
  4600. }
  4601. switch (starttype) {
  4602. case types._function:
  4603. return this.parseFunctionStatement(nany, false, true);
  4604. case types._class:
  4605. nany.declare = true;
  4606. return this.parseClass(nany, true, false);
  4607. case types._const:
  4608. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  4609. this.expect(types._const);
  4610. this.expectContextual("enum");
  4611. return this.tsParseEnumDeclaration(nany, true);
  4612. }
  4613. case types._var:
  4614. kind = kind || this.state.value;
  4615. return this.parseVarStatement(nany, kind);
  4616. case types.name:
  4617. {
  4618. const value = this.state.value;
  4619. if (value === "global") {
  4620. return this.tsParseAmbientExternalModuleDeclaration(nany);
  4621. } else {
  4622. return this.tsParseDeclaration(nany, value, true);
  4623. }
  4624. }
  4625. }
  4626. }
  4627. tsTryParseExportDeclaration() {
  4628. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  4629. }
  4630. tsParseExpressionStatement(node, expr) {
  4631. switch (expr.name) {
  4632. case "declare":
  4633. {
  4634. const declaration = this.tsTryParseDeclare(node);
  4635. if (declaration) {
  4636. declaration.declare = true;
  4637. return declaration;
  4638. }
  4639. break;
  4640. }
  4641. case "global":
  4642. if (this.match(types.braceL)) {
  4643. this.scope.enter(SCOPE_TS_MODULE);
  4644. const mod = node;
  4645. mod.global = true;
  4646. mod.id = expr;
  4647. mod.body = this.tsParseModuleBlock();
  4648. this.scope.exit();
  4649. return this.finishNode(mod, "TSModuleDeclaration");
  4650. }
  4651. break;
  4652. default:
  4653. return this.tsParseDeclaration(node, expr.name, false);
  4654. }
  4655. }
  4656. tsParseDeclaration(node, value, next) {
  4657. switch (value) {
  4658. case "abstract":
  4659. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  4660. const cls = node;
  4661. cls.abstract = true;
  4662. if (next) {
  4663. this.next();
  4664. if (!this.match(types._class)) {
  4665. this.unexpected(null, types._class);
  4666. }
  4667. }
  4668. return this.parseClass(cls, true, false);
  4669. }
  4670. break;
  4671. case "enum":
  4672. if (next || this.match(types.name)) {
  4673. if (next) this.next();
  4674. return this.tsParseEnumDeclaration(node, false);
  4675. }
  4676. break;
  4677. case "interface":
  4678. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4679. if (next) this.next();
  4680. return this.tsParseInterfaceDeclaration(node);
  4681. }
  4682. break;
  4683. case "module":
  4684. if (next) this.next();
  4685. if (this.match(types.string)) {
  4686. return this.tsParseAmbientExternalModuleDeclaration(node);
  4687. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4688. return this.tsParseModuleOrNamespaceDeclaration(node);
  4689. }
  4690. break;
  4691. case "namespace":
  4692. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4693. if (next) this.next();
  4694. return this.tsParseModuleOrNamespaceDeclaration(node);
  4695. }
  4696. break;
  4697. case "type":
  4698. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4699. if (next) this.next();
  4700. return this.tsParseTypeAliasDeclaration(node);
  4701. }
  4702. break;
  4703. }
  4704. }
  4705. tsCheckLineTerminatorAndMatch(tokenType, next) {
  4706. return (next || this.match(tokenType)) && !this.isLineTerminator();
  4707. }
  4708. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  4709. if (!this.isRelational("<")) {
  4710. return undefined;
  4711. }
  4712. const res = this.tsTryParseAndCatch(() => {
  4713. const node = this.startNodeAt(startPos, startLoc);
  4714. node.typeParameters = this.tsParseTypeParameters();
  4715. super.parseFunctionParams(node);
  4716. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  4717. this.expect(types.arrow);
  4718. return node;
  4719. });
  4720. if (!res) {
  4721. return undefined;
  4722. }
  4723. return this.parseArrowExpression(res, null, true);
  4724. }
  4725. tsParseTypeArguments() {
  4726. const node = this.startNode();
  4727. node.params = this.tsInType(() => this.tsInNoContext(() => {
  4728. this.expectRelational("<");
  4729. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  4730. }));
  4731. this.state.exprAllowed = false;
  4732. this.expectRelational(">");
  4733. return this.finishNode(node, "TSTypeParameterInstantiation");
  4734. }
  4735. tsIsDeclarationStart() {
  4736. if (this.match(types.name)) {
  4737. switch (this.state.value) {
  4738. case "abstract":
  4739. case "declare":
  4740. case "enum":
  4741. case "interface":
  4742. case "module":
  4743. case "namespace":
  4744. case "type":
  4745. return true;
  4746. }
  4747. }
  4748. return false;
  4749. }
  4750. isExportDefaultSpecifier() {
  4751. if (this.tsIsDeclarationStart()) return false;
  4752. return super.isExportDefaultSpecifier();
  4753. }
  4754. parseAssignableListItem(allowModifiers, decorators) {
  4755. const startPos = this.state.start;
  4756. const startLoc = this.state.startLoc;
  4757. let accessibility;
  4758. let readonly = false;
  4759. if (allowModifiers) {
  4760. accessibility = this.parseAccessModifier();
  4761. readonly = !!this.tsParseModifier(["readonly"]);
  4762. }
  4763. const left = this.parseMaybeDefault();
  4764. this.parseAssignableListItemTypes(left);
  4765. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  4766. if (accessibility || readonly) {
  4767. const pp = this.startNodeAt(startPos, startLoc);
  4768. if (decorators.length) {
  4769. pp.decorators = decorators;
  4770. }
  4771. if (accessibility) pp.accessibility = accessibility;
  4772. if (readonly) pp.readonly = readonly;
  4773. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  4774. this.raise(pp.start, "A parameter property may not be declared using a binding pattern.");
  4775. }
  4776. pp.parameter = elt;
  4777. return this.finishNode(pp, "TSParameterProperty");
  4778. }
  4779. if (decorators.length) {
  4780. left.decorators = decorators;
  4781. }
  4782. return elt;
  4783. }
  4784. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  4785. if (this.match(types.colon)) {
  4786. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  4787. }
  4788. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  4789. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  4790. this.finishNode(node, bodilessType);
  4791. return;
  4792. }
  4793. super.parseFunctionBodyAndFinish(node, type, isMethod);
  4794. }
  4795. registerFunctionStatementId(node) {
  4796. if (!node.body && node.id) {
  4797. this.checkLVal(node.id, BIND_TS_AMBIENT, null, "function name");
  4798. } else {
  4799. super.registerFunctionStatementId(...arguments);
  4800. }
  4801. }
  4802. parseSubscript(base, startPos, startLoc, noCalls, state) {
  4803. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  4804. this.state.exprAllowed = false;
  4805. this.next();
  4806. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  4807. nonNullExpression.expression = base;
  4808. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  4809. }
  4810. if (this.isRelational("<")) {
  4811. const result = this.tsTryParseAndCatch(() => {
  4812. if (!noCalls && this.atPossibleAsync(base)) {
  4813. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  4814. if (asyncArrowFn) {
  4815. return asyncArrowFn;
  4816. }
  4817. }
  4818. const node = this.startNodeAt(startPos, startLoc);
  4819. node.callee = base;
  4820. const typeArguments = this.tsParseTypeArguments();
  4821. if (typeArguments) {
  4822. if (!noCalls && this.eat(types.parenL)) {
  4823. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  4824. node.typeParameters = typeArguments;
  4825. return this.finishCallExpression(node, state.optionalChainMember);
  4826. } else if (this.match(types.backQuote)) {
  4827. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments);
  4828. }
  4829. }
  4830. this.unexpected();
  4831. });
  4832. if (result) return result;
  4833. }
  4834. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  4835. }
  4836. parseNewArguments(node) {
  4837. if (this.isRelational("<")) {
  4838. const typeParameters = this.tsTryParseAndCatch(() => {
  4839. const args = this.tsParseTypeArguments();
  4840. if (!this.match(types.parenL)) this.unexpected();
  4841. return args;
  4842. });
  4843. if (typeParameters) {
  4844. node.typeParameters = typeParameters;
  4845. }
  4846. }
  4847. super.parseNewArguments(node);
  4848. }
  4849. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  4850. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  4851. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  4852. node.expression = left;
  4853. const _const = this.tsTryNextParseConstantContext();
  4854. if (_const) {
  4855. node.typeAnnotation = _const;
  4856. } else {
  4857. node.typeAnnotation = this.tsNextThenParseType();
  4858. }
  4859. this.finishNode(node, "TSAsExpression");
  4860. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  4861. }
  4862. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn);
  4863. }
  4864. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  4865. checkDuplicateExports() {}
  4866. parseImport(node) {
  4867. if (this.match(types.name) && this.lookahead().type === types.eq) {
  4868. return this.tsParseImportEqualsDeclaration(node);
  4869. }
  4870. return super.parseImport(node);
  4871. }
  4872. parseExport(node) {
  4873. if (this.match(types._import)) {
  4874. this.expect(types._import);
  4875. return this.tsParseImportEqualsDeclaration(node, true);
  4876. } else if (this.eat(types.eq)) {
  4877. const assign = node;
  4878. assign.expression = this.parseExpression();
  4879. this.semicolon();
  4880. return this.finishNode(assign, "TSExportAssignment");
  4881. } else if (this.eatContextual("as")) {
  4882. const decl = node;
  4883. this.expectContextual("namespace");
  4884. decl.id = this.parseIdentifier();
  4885. this.semicolon();
  4886. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  4887. } else {
  4888. return super.parseExport(node);
  4889. }
  4890. }
  4891. isAbstractClass() {
  4892. return this.isContextual("abstract") && this.lookahead().type === types._class;
  4893. }
  4894. parseExportDefaultExpression() {
  4895. if (this.isAbstractClass()) {
  4896. const cls = this.startNode();
  4897. this.next();
  4898. this.parseClass(cls, true, true);
  4899. cls.abstract = true;
  4900. return cls;
  4901. }
  4902. if (this.state.value === "interface") {
  4903. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  4904. if (result) return result;
  4905. }
  4906. return super.parseExportDefaultExpression();
  4907. }
  4908. parseStatementContent(context, topLevel) {
  4909. if (this.state.type === types._const) {
  4910. const ahead = this.lookahead();
  4911. if (ahead.type === types.name && ahead.value === "enum") {
  4912. const node = this.startNode();
  4913. this.expect(types._const);
  4914. this.expectContextual("enum");
  4915. return this.tsParseEnumDeclaration(node, true);
  4916. }
  4917. }
  4918. return super.parseStatementContent(context, topLevel);
  4919. }
  4920. parseAccessModifier() {
  4921. return this.tsParseModifier(["public", "protected", "private"]);
  4922. }
  4923. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  4924. const accessibility = this.parseAccessModifier();
  4925. if (accessibility) member.accessibility = accessibility;
  4926. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  4927. }
  4928. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  4929. const modifiers = this.tsParseModifiers(["abstract", "readonly", "declare"]);
  4930. Object.assign(member, modifiers);
  4931. const idx = this.tsTryParseIndexSignature(member);
  4932. if (idx) {
  4933. classBody.body.push(idx);
  4934. if (modifiers.abstract) {
  4935. this.raise(member.start, "Index signatures cannot have the 'abstract' modifier");
  4936. }
  4937. if (isStatic) {
  4938. this.raise(member.start, "Index signatures cannot have the 'static' modifier");
  4939. }
  4940. if (member.accessibility) {
  4941. this.raise(member.start, `Index signatures cannot have an accessibility modifier ('${member.accessibility}')`);
  4942. }
  4943. return;
  4944. }
  4945. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  4946. }
  4947. parsePostMemberNameModifiers(methodOrProp) {
  4948. const optional = this.eat(types.question);
  4949. if (optional) methodOrProp.optional = true;
  4950. if (methodOrProp.readonly && this.match(types.parenL)) {
  4951. this.raise(methodOrProp.start, "Class methods cannot have the 'readonly' modifier");
  4952. }
  4953. if (methodOrProp.declare && this.match(types.parenL)) {
  4954. this.raise(methodOrProp.start, "Class methods cannot have the 'declare' modifier");
  4955. }
  4956. }
  4957. parseExpressionStatement(node, expr) {
  4958. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  4959. return decl || super.parseExpressionStatement(node, expr);
  4960. }
  4961. shouldParseExportDeclaration() {
  4962. if (this.tsIsDeclarationStart()) return true;
  4963. return super.shouldParseExportDeclaration();
  4964. }
  4965. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  4966. if (!refNeedsArrowPos || !this.match(types.question)) {
  4967. return super.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  4968. }
  4969. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  4970. if (!result.node) {
  4971. refNeedsArrowPos.start = result.error.pos || this.state.start;
  4972. return expr;
  4973. }
  4974. if (result.error) this.state = result.failState;
  4975. return result.node;
  4976. }
  4977. parseParenItem(node, startPos, startLoc) {
  4978. node = super.parseParenItem(node, startPos, startLoc);
  4979. if (this.eat(types.question)) {
  4980. node.optional = true;
  4981. this.resetEndLocation(node);
  4982. }
  4983. if (this.match(types.colon)) {
  4984. const typeCastNode = this.startNodeAt(startPos, startLoc);
  4985. typeCastNode.expression = node;
  4986. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  4987. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  4988. }
  4989. return node;
  4990. }
  4991. parseExportDeclaration(node) {
  4992. const startPos = this.state.start;
  4993. const startLoc = this.state.startLoc;
  4994. const isDeclare = this.eatContextual("declare");
  4995. let declaration;
  4996. if (this.match(types.name)) {
  4997. declaration = this.tsTryParseExportDeclaration();
  4998. }
  4999. if (!declaration) {
  5000. declaration = super.parseExportDeclaration(node);
  5001. }
  5002. if (declaration && isDeclare) {
  5003. this.resetStartLocation(declaration, startPos, startLoc);
  5004. declaration.declare = true;
  5005. }
  5006. return declaration;
  5007. }
  5008. parseClassId(node, isStatement, optionalId) {
  5009. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5010. return;
  5011. }
  5012. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5013. const typeParameters = this.tsTryParseTypeParameters();
  5014. if (typeParameters) node.typeParameters = typeParameters;
  5015. }
  5016. parseClassPropertyAnnotation(node) {
  5017. if (!node.optional && this.eat(types.bang)) {
  5018. node.definite = true;
  5019. }
  5020. const type = this.tsTryParseTypeAnnotation();
  5021. if (type) node.typeAnnotation = type;
  5022. }
  5023. parseClassProperty(node) {
  5024. this.parseClassPropertyAnnotation(node);
  5025. if (node.declare && this.match(types.equal)) {
  5026. this.raise(this.state.start, "'declare' class fields cannot have an initializer");
  5027. }
  5028. return super.parseClassProperty(node);
  5029. }
  5030. parseClassPrivateProperty(node) {
  5031. if (node.abstract) {
  5032. this.raise(node.start, "Private elements cannot have the 'abstract' modifier.");
  5033. }
  5034. if (node.accessibility) {
  5035. this.raise(node.start, `Private elements cannot have an accessibility modifier ('${node.accessibility}')`);
  5036. }
  5037. this.parseClassPropertyAnnotation(node);
  5038. return super.parseClassPrivateProperty(node);
  5039. }
  5040. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5041. const typeParameters = this.tsTryParseTypeParameters();
  5042. if (typeParameters) method.typeParameters = typeParameters;
  5043. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5044. }
  5045. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5046. const typeParameters = this.tsTryParseTypeParameters();
  5047. if (typeParameters) method.typeParameters = typeParameters;
  5048. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5049. }
  5050. parseClassSuper(node) {
  5051. super.parseClassSuper(node);
  5052. if (node.superClass && this.isRelational("<")) {
  5053. node.superTypeParameters = this.tsParseTypeArguments();
  5054. }
  5055. if (this.eatContextual("implements")) {
  5056. node.implements = this.tsParseHeritageClause("implements");
  5057. }
  5058. }
  5059. parseObjPropValue(prop, ...args) {
  5060. const typeParameters = this.tsTryParseTypeParameters();
  5061. if (typeParameters) prop.typeParameters = typeParameters;
  5062. super.parseObjPropValue(prop, ...args);
  5063. }
  5064. parseFunctionParams(node, allowModifiers) {
  5065. const typeParameters = this.tsTryParseTypeParameters();
  5066. if (typeParameters) node.typeParameters = typeParameters;
  5067. super.parseFunctionParams(node, allowModifiers);
  5068. }
  5069. parseVarId(decl, kind) {
  5070. super.parseVarId(decl, kind);
  5071. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5072. decl.definite = true;
  5073. }
  5074. const type = this.tsTryParseTypeAnnotation();
  5075. if (type) {
  5076. decl.id.typeAnnotation = type;
  5077. this.resetEndLocation(decl.id);
  5078. }
  5079. }
  5080. parseAsyncArrowFromCallExpression(node, call) {
  5081. if (this.match(types.colon)) {
  5082. node.returnType = this.tsParseTypeAnnotation();
  5083. }
  5084. return super.parseAsyncArrowFromCallExpression(node, call);
  5085. }
  5086. parseMaybeAssign(...args) {
  5087. let state;
  5088. let jsx;
  5089. let typeCast;
  5090. if (this.match(types.jsxTagStart)) {
  5091. state = this.state.clone();
  5092. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5093. if (!jsx.error) return jsx.node;
  5094. const {
  5095. context
  5096. } = this.state;
  5097. if (context[context.length - 1] === types$1.j_oTag) {
  5098. context.length -= 2;
  5099. } else if (context[context.length - 1] === types$1.j_expr) {
  5100. context.length -= 1;
  5101. }
  5102. }
  5103. if (!(jsx && jsx.error) && !this.isRelational("<")) {
  5104. return super.parseMaybeAssign(...args);
  5105. }
  5106. let typeParameters;
  5107. state = state || this.state.clone();
  5108. const arrow = this.tryParse(abort => {
  5109. typeParameters = this.tsParseTypeParameters();
  5110. const expr = super.parseMaybeAssign(...args);
  5111. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5112. abort();
  5113. }
  5114. if (typeParameters && typeParameters.params.length !== 0) {
  5115. this.resetStartLocationFromNode(expr, typeParameters);
  5116. }
  5117. expr.typeParameters = typeParameters;
  5118. return expr;
  5119. }, state);
  5120. if (!arrow.error && !arrow.aborted) return arrow.node;
  5121. if (!jsx) {
  5122. assert(!this.hasPlugin("jsx"));
  5123. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5124. if (!typeCast.error) return typeCast.node;
  5125. }
  5126. if (jsx && jsx.node) {
  5127. this.state = jsx.failState;
  5128. return jsx.node;
  5129. }
  5130. if (arrow.node) {
  5131. this.state = arrow.failState;
  5132. return arrow.node;
  5133. }
  5134. if (typeCast && typeCast.node) {
  5135. this.state = typeCast.failState;
  5136. return typeCast.node;
  5137. }
  5138. if (jsx && jsx.thrown) throw jsx.error;
  5139. if (arrow.thrown) throw arrow.error;
  5140. if (typeCast && typeCast.thrown) throw typeCast.error;
  5141. throw jsx && jsx.error || arrow.error || typeCast && typeCast.error;
  5142. }
  5143. parseMaybeUnary(refExpressionErrors) {
  5144. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5145. return this.tsParseTypeAssertion();
  5146. } else {
  5147. return super.parseMaybeUnary(refExpressionErrors);
  5148. }
  5149. }
  5150. parseArrow(node) {
  5151. if (this.match(types.colon)) {
  5152. const result = this.tryParse(abort => {
  5153. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5154. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5155. return returnType;
  5156. });
  5157. if (result.aborted) return;
  5158. if (!result.thrown) {
  5159. if (result.error) this.state = result.failState;
  5160. node.returnType = result.node;
  5161. }
  5162. }
  5163. return super.parseArrow(node);
  5164. }
  5165. parseAssignableListItemTypes(param) {
  5166. if (this.eat(types.question)) {
  5167. if (param.type !== "Identifier") {
  5168. this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature.");
  5169. }
  5170. param.optional = true;
  5171. }
  5172. const type = this.tsTryParseTypeAnnotation();
  5173. if (type) param.typeAnnotation = type;
  5174. this.resetEndLocation(param);
  5175. return param;
  5176. }
  5177. toAssignable(node) {
  5178. switch (node.type) {
  5179. case "TSTypeCastExpression":
  5180. return super.toAssignable(this.typeCastToParameter(node));
  5181. case "TSParameterProperty":
  5182. return super.toAssignable(node);
  5183. case "TSAsExpression":
  5184. case "TSNonNullExpression":
  5185. case "TSTypeAssertion":
  5186. node.expression = this.toAssignable(node.expression);
  5187. return node;
  5188. default:
  5189. return super.toAssignable(node);
  5190. }
  5191. }
  5192. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  5193. switch (expr.type) {
  5194. case "TSTypeCastExpression":
  5195. return;
  5196. case "TSParameterProperty":
  5197. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  5198. return;
  5199. case "TSAsExpression":
  5200. case "TSNonNullExpression":
  5201. case "TSTypeAssertion":
  5202. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  5203. return;
  5204. default:
  5205. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  5206. return;
  5207. }
  5208. }
  5209. parseBindingAtom() {
  5210. switch (this.state.type) {
  5211. case types._this:
  5212. return this.parseIdentifier(true);
  5213. default:
  5214. return super.parseBindingAtom();
  5215. }
  5216. }
  5217. parseMaybeDecoratorArguments(expr) {
  5218. if (this.isRelational("<")) {
  5219. const typeArguments = this.tsParseTypeArguments();
  5220. if (this.match(types.parenL)) {
  5221. const call = super.parseMaybeDecoratorArguments(expr);
  5222. call.typeParameters = typeArguments;
  5223. return call;
  5224. }
  5225. this.unexpected(this.state.start, types.parenL);
  5226. }
  5227. return super.parseMaybeDecoratorArguments(expr);
  5228. }
  5229. isClassMethod() {
  5230. return this.isRelational("<") || super.isClassMethod();
  5231. }
  5232. isClassProperty() {
  5233. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5234. }
  5235. parseMaybeDefault(...args) {
  5236. const node = super.parseMaybeDefault(...args);
  5237. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5238. this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`");
  5239. }
  5240. return node;
  5241. }
  5242. getTokenFromCode(code) {
  5243. if (this.state.inType && (code === 62 || code === 60)) {
  5244. return this.finishOp(types.relational, 1);
  5245. } else {
  5246. return super.getTokenFromCode(code);
  5247. }
  5248. }
  5249. toAssignableList(exprList) {
  5250. for (let i = 0; i < exprList.length; i++) {
  5251. const expr = exprList[i];
  5252. if (!expr) continue;
  5253. switch (expr.type) {
  5254. case "TSTypeCastExpression":
  5255. exprList[i] = this.typeCastToParameter(expr);
  5256. break;
  5257. case "TSAsExpression":
  5258. case "TSTypeAssertion":
  5259. if (!this.state.maybeInArrowParameters) {
  5260. exprList[i] = this.typeCastToParameter(expr);
  5261. } else {
  5262. this.raise(expr.start, "Unexpected type cast in parameter position.");
  5263. }
  5264. break;
  5265. }
  5266. }
  5267. return super.toAssignableList(...arguments);
  5268. }
  5269. typeCastToParameter(node) {
  5270. node.expression.typeAnnotation = node.typeAnnotation;
  5271. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5272. return node.expression;
  5273. }
  5274. toReferencedList(exprList, isInParens) {
  5275. for (let i = 0; i < exprList.length; i++) {
  5276. const expr = exprList[i];
  5277. if (expr && expr.type === "TSTypeCastExpression") {
  5278. this.raise(expr.start, "Did not expect a type annotation here.");
  5279. }
  5280. }
  5281. return exprList;
  5282. }
  5283. shouldParseArrow() {
  5284. return this.match(types.colon) || super.shouldParseArrow();
  5285. }
  5286. shouldParseAsyncArrow() {
  5287. return this.match(types.colon) || super.shouldParseAsyncArrow();
  5288. }
  5289. canHaveLeadingDecorator() {
  5290. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  5291. }
  5292. jsxParseOpeningElementAfterName(node) {
  5293. if (this.isRelational("<")) {
  5294. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  5295. if (typeArguments) node.typeParameters = typeArguments;
  5296. }
  5297. return super.jsxParseOpeningElementAfterName(node);
  5298. }
  5299. getGetterSetterExpectedParamCount(method) {
  5300. const baseCount = super.getGetterSetterExpectedParamCount(method);
  5301. const firstParam = method.params[0];
  5302. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  5303. return hasContextParam ? baseCount + 1 : baseCount;
  5304. }
  5305. });
  5306. types.placeholder = new TokenType("%%", {
  5307. startsExpr: true
  5308. });
  5309. var placeholders = (superClass => class extends superClass {
  5310. parsePlaceholder(expectedNode) {
  5311. if (this.match(types.placeholder)) {
  5312. const node = this.startNode();
  5313. this.next();
  5314. this.assertNoSpace("Unexpected space in placeholder.");
  5315. node.name = super.parseIdentifier(true);
  5316. this.assertNoSpace("Unexpected space in placeholder.");
  5317. this.expect(types.placeholder);
  5318. return this.finishPlaceholder(node, expectedNode);
  5319. }
  5320. }
  5321. finishPlaceholder(node, expectedNode) {
  5322. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  5323. node.expectedNode = expectedNode;
  5324. return isFinished ? node : this.finishNode(node, "Placeholder");
  5325. }
  5326. getTokenFromCode(code) {
  5327. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  5328. return this.finishOp(types.placeholder, 2);
  5329. }
  5330. return super.getTokenFromCode(...arguments);
  5331. }
  5332. parseExprAtom() {
  5333. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  5334. }
  5335. parseIdentifier() {
  5336. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  5337. }
  5338. checkReservedWord(word) {
  5339. if (word !== undefined) super.checkReservedWord(...arguments);
  5340. }
  5341. parseBindingAtom() {
  5342. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  5343. }
  5344. checkLVal(expr) {
  5345. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  5346. }
  5347. toAssignable(node) {
  5348. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  5349. node.expectedNode = "Pattern";
  5350. return node;
  5351. }
  5352. return super.toAssignable(...arguments);
  5353. }
  5354. verifyBreakContinue(node) {
  5355. if (node.label && node.label.type === "Placeholder") return;
  5356. super.verifyBreakContinue(...arguments);
  5357. }
  5358. parseExpressionStatement(node, expr) {
  5359. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  5360. return super.parseExpressionStatement(...arguments);
  5361. }
  5362. if (this.match(types.colon)) {
  5363. const stmt = node;
  5364. stmt.label = this.finishPlaceholder(expr, "Identifier");
  5365. this.next();
  5366. stmt.body = this.parseStatement("label");
  5367. return this.finishNode(stmt, "LabeledStatement");
  5368. }
  5369. this.semicolon();
  5370. node.name = expr.name;
  5371. return this.finishPlaceholder(node, "Statement");
  5372. }
  5373. parseBlock() {
  5374. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  5375. }
  5376. parseFunctionId() {
  5377. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  5378. }
  5379. parseClass(node, isStatement, optionalId) {
  5380. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  5381. this.next();
  5382. this.takeDecorators(node);
  5383. const placeholder = this.parsePlaceholder("Identifier");
  5384. if (placeholder) {
  5385. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  5386. node.id = placeholder;
  5387. } else if (optionalId || !isStatement) {
  5388. node.id = null;
  5389. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  5390. return this.finishNode(node, type);
  5391. } else {
  5392. this.unexpected(null, "A class name is required");
  5393. }
  5394. } else {
  5395. this.parseClassId(node, isStatement, optionalId);
  5396. }
  5397. this.parseClassSuper(node);
  5398. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass);
  5399. return this.finishNode(node, type);
  5400. }
  5401. parseExport(node) {
  5402. const placeholder = this.parsePlaceholder("Identifier");
  5403. if (!placeholder) return super.parseExport(...arguments);
  5404. if (!this.isContextual("from") && !this.match(types.comma)) {
  5405. node.specifiers = [];
  5406. node.source = null;
  5407. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  5408. return this.finishNode(node, "ExportNamedDeclaration");
  5409. }
  5410. this.expectPlugin("exportDefaultFrom");
  5411. const specifier = this.startNode();
  5412. specifier.exported = placeholder;
  5413. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  5414. return super.parseExport(node);
  5415. }
  5416. maybeParseExportDefaultSpecifier(node) {
  5417. if (node.specifiers && node.specifiers.length > 0) {
  5418. return true;
  5419. }
  5420. return super.maybeParseExportDefaultSpecifier(...arguments);
  5421. }
  5422. checkExport(node) {
  5423. const {
  5424. specifiers
  5425. } = node;
  5426. if (specifiers && specifiers.length) {
  5427. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  5428. }
  5429. super.checkExport(node);
  5430. node.specifiers = specifiers;
  5431. }
  5432. parseImport(node) {
  5433. const placeholder = this.parsePlaceholder("Identifier");
  5434. if (!placeholder) return super.parseImport(...arguments);
  5435. node.specifiers = [];
  5436. if (!this.isContextual("from") && !this.match(types.comma)) {
  5437. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  5438. this.semicolon();
  5439. return this.finishNode(node, "ImportDeclaration");
  5440. }
  5441. const specifier = this.startNodeAtNode(placeholder);
  5442. specifier.local = placeholder;
  5443. this.finishNode(specifier, "ImportDefaultSpecifier");
  5444. node.specifiers.push(specifier);
  5445. if (this.eat(types.comma)) {
  5446. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  5447. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  5448. }
  5449. this.expectContextual("from");
  5450. node.source = this.parseImportSource();
  5451. this.semicolon();
  5452. return this.finishNode(node, "ImportDeclaration");
  5453. }
  5454. parseImportSource() {
  5455. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  5456. }
  5457. });
  5458. var v8intrinsic = (superClass => class extends superClass {
  5459. parseV8Intrinsic() {
  5460. if (this.match(types.modulo)) {
  5461. const v8IntrinsicStart = this.state.start;
  5462. const node = this.startNode();
  5463. this.eat(types.modulo);
  5464. if (this.match(types.name)) {
  5465. const name = this.parseIdentifierName(this.state.start);
  5466. const identifier = this.createIdentifier(node, name);
  5467. identifier.type = "V8IntrinsicIdentifier";
  5468. if (this.match(types.parenL)) {
  5469. return identifier;
  5470. }
  5471. }
  5472. this.unexpected(v8IntrinsicStart);
  5473. }
  5474. }
  5475. parseExprAtom() {
  5476. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  5477. }
  5478. });
  5479. function hasPlugin(plugins, name) {
  5480. return plugins.some(plugin => {
  5481. if (Array.isArray(plugin)) {
  5482. return plugin[0] === name;
  5483. } else {
  5484. return plugin === name;
  5485. }
  5486. });
  5487. }
  5488. function getPluginOption(plugins, name, option) {
  5489. const plugin = plugins.find(plugin => {
  5490. if (Array.isArray(plugin)) {
  5491. return plugin[0] === name;
  5492. } else {
  5493. return plugin === name;
  5494. }
  5495. });
  5496. if (plugin && Array.isArray(plugin)) {
  5497. return plugin[1][option];
  5498. }
  5499. return null;
  5500. }
  5501. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  5502. function validatePlugins(plugins) {
  5503. if (hasPlugin(plugins, "decorators")) {
  5504. if (hasPlugin(plugins, "decorators-legacy")) {
  5505. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  5506. }
  5507. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  5508. if (decoratorsBeforeExport == null) {
  5509. 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'.");
  5510. } else if (typeof decoratorsBeforeExport !== "boolean") {
  5511. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  5512. }
  5513. }
  5514. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  5515. throw new Error("Cannot combine flow and typescript plugins.");
  5516. }
  5517. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  5518. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  5519. }
  5520. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  5521. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  5522. }
  5523. }
  5524. const mixinPlugins = {
  5525. estree,
  5526. jsx,
  5527. flow,
  5528. typescript,
  5529. v8intrinsic,
  5530. placeholders
  5531. };
  5532. const mixinPluginNames = Object.keys(mixinPlugins);
  5533. const defaultOptions = {
  5534. sourceType: "script",
  5535. sourceFilename: undefined,
  5536. startLine: 1,
  5537. allowAwaitOutsideFunction: false,
  5538. allowReturnOutsideFunction: false,
  5539. allowImportExportEverywhere: false,
  5540. allowSuperOutsideMethod: false,
  5541. allowUndeclaredExports: false,
  5542. plugins: [],
  5543. strictMode: null,
  5544. ranges: false,
  5545. tokens: false,
  5546. createParenthesizedExpressions: false,
  5547. errorRecovery: false
  5548. };
  5549. function getOptions(opts) {
  5550. const options = {};
  5551. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  5552. const key = _Object$keys[_i];
  5553. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  5554. }
  5555. return options;
  5556. }
  5557. class Position {
  5558. constructor(line, col) {
  5559. this.line = line;
  5560. this.column = col;
  5561. }
  5562. }
  5563. class SourceLocation {
  5564. constructor(start, end) {
  5565. this.start = start;
  5566. this.end = end;
  5567. }
  5568. }
  5569. function getLineInfo(input, offset) {
  5570. let line = 1;
  5571. let lineStart = 0;
  5572. let match;
  5573. lineBreakG.lastIndex = 0;
  5574. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  5575. line++;
  5576. lineStart = lineBreakG.lastIndex;
  5577. }
  5578. return new Position(line, offset - lineStart);
  5579. }
  5580. class BaseParser {
  5581. constructor() {
  5582. this.sawUnambiguousESM = false;
  5583. this.ambiguousScriptDifferentAst = false;
  5584. }
  5585. hasPlugin(name) {
  5586. return this.plugins.has(name);
  5587. }
  5588. getPluginOption(plugin, name) {
  5589. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  5590. }
  5591. }
  5592. function last(stack) {
  5593. return stack[stack.length - 1];
  5594. }
  5595. class CommentsParser extends BaseParser {
  5596. addComment(comment) {
  5597. if (this.filename) comment.loc.filename = this.filename;
  5598. this.state.trailingComments.push(comment);
  5599. this.state.leadingComments.push(comment);
  5600. }
  5601. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  5602. if (this.state.leadingComments.length === 0) {
  5603. return;
  5604. }
  5605. let lastElement = null;
  5606. let i = elements.length;
  5607. while (lastElement === null && i > 0) {
  5608. lastElement = elements[--i];
  5609. }
  5610. if (lastElement === null) {
  5611. return;
  5612. }
  5613. for (let j = 0; j < this.state.leadingComments.length; j++) {
  5614. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  5615. this.state.leadingComments.splice(j, 1);
  5616. j--;
  5617. }
  5618. }
  5619. const newTrailingComments = [];
  5620. for (let i = 0; i < this.state.leadingComments.length; i++) {
  5621. const leadingComment = this.state.leadingComments[i];
  5622. if (leadingComment.end < node.end) {
  5623. newTrailingComments.push(leadingComment);
  5624. if (!takeAllComments) {
  5625. this.state.leadingComments.splice(i, 1);
  5626. i--;
  5627. }
  5628. } else {
  5629. if (node.trailingComments === undefined) {
  5630. node.trailingComments = [];
  5631. }
  5632. node.trailingComments.push(leadingComment);
  5633. }
  5634. }
  5635. if (takeAllComments) this.state.leadingComments = [];
  5636. if (newTrailingComments.length > 0) {
  5637. lastElement.trailingComments = newTrailingComments;
  5638. } else if (lastElement.trailingComments !== undefined) {
  5639. lastElement.trailingComments = [];
  5640. }
  5641. }
  5642. processComment(node) {
  5643. if (node.type === "Program" && node.body.length > 0) return;
  5644. const stack = this.state.commentStack;
  5645. let firstChild, lastChild, trailingComments, i, j;
  5646. if (this.state.trailingComments.length > 0) {
  5647. if (this.state.trailingComments[0].start >= node.end) {
  5648. trailingComments = this.state.trailingComments;
  5649. this.state.trailingComments = [];
  5650. } else {
  5651. this.state.trailingComments.length = 0;
  5652. }
  5653. } else if (stack.length > 0) {
  5654. const lastInStack = last(stack);
  5655. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  5656. trailingComments = lastInStack.trailingComments;
  5657. delete lastInStack.trailingComments;
  5658. }
  5659. }
  5660. if (stack.length > 0 && last(stack).start >= node.start) {
  5661. firstChild = stack.pop();
  5662. }
  5663. while (stack.length > 0 && last(stack).start >= node.start) {
  5664. lastChild = stack.pop();
  5665. }
  5666. if (!lastChild && firstChild) lastChild = firstChild;
  5667. if (firstChild) {
  5668. switch (node.type) {
  5669. case "ObjectExpression":
  5670. this.adjustCommentsAfterTrailingComma(node, node.properties);
  5671. break;
  5672. case "ObjectPattern":
  5673. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  5674. break;
  5675. case "CallExpression":
  5676. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  5677. break;
  5678. case "ArrayExpression":
  5679. this.adjustCommentsAfterTrailingComma(node, node.elements);
  5680. break;
  5681. case "ArrayPattern":
  5682. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  5683. break;
  5684. }
  5685. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  5686. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  5687. }
  5688. if (lastChild) {
  5689. if (lastChild.leadingComments) {
  5690. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  5691. node.leadingComments = lastChild.leadingComments;
  5692. delete lastChild.leadingComments;
  5693. } else {
  5694. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  5695. if (lastChild.leadingComments[i].end <= node.start) {
  5696. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  5697. break;
  5698. }
  5699. }
  5700. }
  5701. }
  5702. } else if (this.state.leadingComments.length > 0) {
  5703. if (last(this.state.leadingComments).end <= node.start) {
  5704. if (this.state.commentPreviousNode) {
  5705. for (j = 0; j < this.state.leadingComments.length; j++) {
  5706. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  5707. this.state.leadingComments.splice(j, 1);
  5708. j--;
  5709. }
  5710. }
  5711. }
  5712. if (this.state.leadingComments.length > 0) {
  5713. node.leadingComments = this.state.leadingComments;
  5714. this.state.leadingComments = [];
  5715. }
  5716. } else {
  5717. for (i = 0; i < this.state.leadingComments.length; i++) {
  5718. if (this.state.leadingComments[i].end > node.start) {
  5719. break;
  5720. }
  5721. }
  5722. const leadingComments = this.state.leadingComments.slice(0, i);
  5723. if (leadingComments.length) {
  5724. node.leadingComments = leadingComments;
  5725. }
  5726. trailingComments = this.state.leadingComments.slice(i);
  5727. if (trailingComments.length === 0) {
  5728. trailingComments = null;
  5729. }
  5730. }
  5731. }
  5732. this.state.commentPreviousNode = node;
  5733. if (trailingComments) {
  5734. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  5735. node.innerComments = trailingComments;
  5736. } else {
  5737. node.trailingComments = trailingComments;
  5738. }
  5739. }
  5740. stack.push(node);
  5741. }
  5742. }
  5743. class LocationParser extends CommentsParser {
  5744. getLocationForPosition(pos) {
  5745. let loc;
  5746. 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);
  5747. return loc;
  5748. }
  5749. raise(pos, message, {
  5750. missingPluginNames,
  5751. code
  5752. } = {}) {
  5753. const loc = this.getLocationForPosition(pos);
  5754. message += ` (${loc.line}:${loc.column})`;
  5755. const err = new SyntaxError(message);
  5756. err.pos = pos;
  5757. err.loc = loc;
  5758. if (missingPluginNames) {
  5759. err.missingPlugin = missingPluginNames;
  5760. }
  5761. if (code !== undefined) {
  5762. err.code = code;
  5763. }
  5764. if (this.options.errorRecovery) {
  5765. if (!this.isLookahead) this.state.errors.push(err);
  5766. return err;
  5767. } else {
  5768. throw err;
  5769. }
  5770. }
  5771. }
  5772. class State {
  5773. constructor() {
  5774. this.errors = [];
  5775. this.potentialArrowAt = -1;
  5776. this.noArrowAt = [];
  5777. this.noArrowParamsConversionAt = [];
  5778. this.inParameters = false;
  5779. this.maybeInArrowParameters = false;
  5780. this.inPipeline = false;
  5781. this.inType = false;
  5782. this.noAnonFunctionType = false;
  5783. this.inPropertyName = false;
  5784. this.hasFlowComment = false;
  5785. this.isIterator = false;
  5786. this.topicContext = {
  5787. maxNumOfResolvableTopics: 0,
  5788. maxTopicIndex: null
  5789. };
  5790. this.soloAwait = false;
  5791. this.inFSharpPipelineDirectBody = false;
  5792. this.labels = [];
  5793. this.decoratorStack = [[]];
  5794. this.yieldPos = -1;
  5795. this.awaitPos = -1;
  5796. this.comments = [];
  5797. this.trailingComments = [];
  5798. this.leadingComments = [];
  5799. this.commentStack = [];
  5800. this.commentPreviousNode = null;
  5801. this.pos = 0;
  5802. this.lineStart = 0;
  5803. this.type = types.eof;
  5804. this.value = null;
  5805. this.start = 0;
  5806. this.end = 0;
  5807. this.lastTokEndLoc = null;
  5808. this.lastTokStartLoc = null;
  5809. this.lastTokStart = 0;
  5810. this.lastTokEnd = 0;
  5811. this.context = [types$1.braceStatement];
  5812. this.exprAllowed = true;
  5813. this.containsEsc = false;
  5814. this.containsOctal = false;
  5815. this.octalPosition = null;
  5816. this.exportedIdentifiers = [];
  5817. this.tokensLength = 0;
  5818. }
  5819. init(options) {
  5820. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  5821. this.curLine = options.startLine;
  5822. this.startLoc = this.endLoc = this.curPosition();
  5823. }
  5824. curPosition() {
  5825. return new Position(this.curLine, this.pos - this.lineStart);
  5826. }
  5827. clone(skipArrays) {
  5828. const state = new State();
  5829. const keys = Object.keys(this);
  5830. for (let i = 0, length = keys.length; i < length; i++) {
  5831. const key = keys[i];
  5832. let val = this[key];
  5833. if (!skipArrays && Array.isArray(val)) {
  5834. val = val.slice();
  5835. }
  5836. state[key] = val;
  5837. }
  5838. return state;
  5839. }
  5840. }
  5841. var _isDigit = function isDigit(code) {
  5842. return code >= 48 && code <= 57;
  5843. };
  5844. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  5845. const forbiddenNumericSeparatorSiblings = {
  5846. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  5847. hex: [46, 88, 95, 120]
  5848. };
  5849. const allowedNumericSeparatorSiblings = {};
  5850. allowedNumericSeparatorSiblings.bin = [48, 49];
  5851. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  5852. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  5853. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  5854. class Token {
  5855. constructor(state) {
  5856. this.type = state.type;
  5857. this.value = state.value;
  5858. this.start = state.start;
  5859. this.end = state.end;
  5860. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  5861. }
  5862. }
  5863. class Tokenizer extends LocationParser {
  5864. constructor(options, input) {
  5865. super();
  5866. this.tokens = [];
  5867. this.state = new State();
  5868. this.state.init(options);
  5869. this.input = input;
  5870. this.length = input.length;
  5871. this.isLookahead = false;
  5872. }
  5873. pushToken(token) {
  5874. this.tokens.length = this.state.tokensLength;
  5875. this.tokens.push(token);
  5876. ++this.state.tokensLength;
  5877. }
  5878. next() {
  5879. if (!this.isLookahead) {
  5880. this.checkKeywordEscapes();
  5881. if (this.options.tokens) {
  5882. this.pushToken(new Token(this.state));
  5883. }
  5884. }
  5885. this.state.lastTokEnd = this.state.end;
  5886. this.state.lastTokStart = this.state.start;
  5887. this.state.lastTokEndLoc = this.state.endLoc;
  5888. this.state.lastTokStartLoc = this.state.startLoc;
  5889. this.nextToken();
  5890. }
  5891. eat(type) {
  5892. if (this.match(type)) {
  5893. this.next();
  5894. return true;
  5895. } else {
  5896. return false;
  5897. }
  5898. }
  5899. match(type) {
  5900. return this.state.type === type;
  5901. }
  5902. lookahead() {
  5903. const old = this.state;
  5904. this.state = old.clone(true);
  5905. this.isLookahead = true;
  5906. this.next();
  5907. this.isLookahead = false;
  5908. const curr = this.state;
  5909. this.state = old;
  5910. return curr;
  5911. }
  5912. nextTokenStart() {
  5913. const thisTokEnd = this.state.pos;
  5914. skipWhiteSpace.lastIndex = thisTokEnd;
  5915. const skip = skipWhiteSpace.exec(this.input);
  5916. return thisTokEnd + skip[0].length;
  5917. }
  5918. lookaheadCharCode() {
  5919. return this.input.charCodeAt(this.nextTokenStart());
  5920. }
  5921. setStrict(strict) {
  5922. this.state.strict = strict;
  5923. if (!this.match(types.num) && !this.match(types.string)) return;
  5924. this.state.pos = this.state.start;
  5925. while (this.state.pos < this.state.lineStart) {
  5926. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  5927. --this.state.curLine;
  5928. }
  5929. this.nextToken();
  5930. }
  5931. curContext() {
  5932. return this.state.context[this.state.context.length - 1];
  5933. }
  5934. nextToken() {
  5935. const curContext = this.curContext();
  5936. if (!curContext || !curContext.preserveSpace) this.skipSpace();
  5937. this.state.containsOctal = false;
  5938. this.state.octalPosition = null;
  5939. this.state.start = this.state.pos;
  5940. this.state.startLoc = this.state.curPosition();
  5941. if (this.state.pos >= this.length) {
  5942. this.finishToken(types.eof);
  5943. return;
  5944. }
  5945. if (curContext.override) {
  5946. curContext.override(this);
  5947. } else {
  5948. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  5949. }
  5950. }
  5951. pushComment(block, text, start, end, startLoc, endLoc) {
  5952. const comment = {
  5953. type: block ? "CommentBlock" : "CommentLine",
  5954. value: text,
  5955. start: start,
  5956. end: end,
  5957. loc: new SourceLocation(startLoc, endLoc)
  5958. };
  5959. if (this.options.tokens) this.pushToken(comment);
  5960. this.state.comments.push(comment);
  5961. this.addComment(comment);
  5962. }
  5963. skipBlockComment() {
  5964. const startLoc = this.state.curPosition();
  5965. const start = this.state.pos;
  5966. const end = this.input.indexOf("*/", this.state.pos + 2);
  5967. if (end === -1) throw this.raise(start, "Unterminated comment");
  5968. this.state.pos = end + 2;
  5969. lineBreakG.lastIndex = start;
  5970. let match;
  5971. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  5972. ++this.state.curLine;
  5973. this.state.lineStart = match.index + match[0].length;
  5974. }
  5975. if (this.isLookahead) return;
  5976. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  5977. }
  5978. skipLineComment(startSkip) {
  5979. const start = this.state.pos;
  5980. const startLoc = this.state.curPosition();
  5981. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  5982. if (this.state.pos < this.length) {
  5983. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  5984. ch = this.input.charCodeAt(this.state.pos);
  5985. }
  5986. }
  5987. if (this.isLookahead) return;
  5988. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  5989. }
  5990. skipSpace() {
  5991. loop: while (this.state.pos < this.length) {
  5992. const ch = this.input.charCodeAt(this.state.pos);
  5993. switch (ch) {
  5994. case 32:
  5995. case 160:
  5996. case 9:
  5997. ++this.state.pos;
  5998. break;
  5999. case 13:
  6000. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6001. ++this.state.pos;
  6002. }
  6003. case 10:
  6004. case 8232:
  6005. case 8233:
  6006. ++this.state.pos;
  6007. ++this.state.curLine;
  6008. this.state.lineStart = this.state.pos;
  6009. break;
  6010. case 47:
  6011. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6012. case 42:
  6013. this.skipBlockComment();
  6014. break;
  6015. case 47:
  6016. this.skipLineComment(2);
  6017. break;
  6018. default:
  6019. break loop;
  6020. }
  6021. break;
  6022. default:
  6023. if (isWhitespace(ch)) {
  6024. ++this.state.pos;
  6025. } else {
  6026. break loop;
  6027. }
  6028. }
  6029. }
  6030. }
  6031. finishToken(type, val) {
  6032. this.state.end = this.state.pos;
  6033. this.state.endLoc = this.state.curPosition();
  6034. const prevType = this.state.type;
  6035. this.state.type = type;
  6036. this.state.value = val;
  6037. if (!this.isLookahead) this.updateContext(prevType);
  6038. }
  6039. readToken_numberSign() {
  6040. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6041. return;
  6042. }
  6043. const nextPos = this.state.pos + 1;
  6044. const next = this.input.charCodeAt(nextPos);
  6045. if (next >= 48 && next <= 57) {
  6046. throw this.raise(this.state.pos, "Unexpected digit after hash token");
  6047. }
  6048. if (this.hasPlugin("classPrivateProperties") || this.hasPlugin("classPrivateMethods") || this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  6049. this.finishOp(types.hash, 1);
  6050. } else {
  6051. throw this.raise(this.state.pos, "Unexpected character '#'");
  6052. }
  6053. }
  6054. readToken_dot() {
  6055. const next = this.input.charCodeAt(this.state.pos + 1);
  6056. if (next >= 48 && next <= 57) {
  6057. this.readNumber(true);
  6058. return;
  6059. }
  6060. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6061. this.state.pos += 3;
  6062. this.finishToken(types.ellipsis);
  6063. } else {
  6064. ++this.state.pos;
  6065. this.finishToken(types.dot);
  6066. }
  6067. }
  6068. readToken_slash() {
  6069. if (this.state.exprAllowed && !this.state.inType) {
  6070. ++this.state.pos;
  6071. this.readRegexp();
  6072. return;
  6073. }
  6074. const next = this.input.charCodeAt(this.state.pos + 1);
  6075. if (next === 61) {
  6076. this.finishOp(types.assign, 2);
  6077. } else {
  6078. this.finishOp(types.slash, 1);
  6079. }
  6080. }
  6081. readToken_interpreter() {
  6082. if (this.state.pos !== 0 || this.length < 2) return false;
  6083. const start = this.state.pos;
  6084. this.state.pos += 1;
  6085. let ch = this.input.charCodeAt(this.state.pos);
  6086. if (ch !== 33) return false;
  6087. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6088. ch = this.input.charCodeAt(this.state.pos);
  6089. }
  6090. const value = this.input.slice(start + 2, this.state.pos);
  6091. this.finishToken(types.interpreterDirective, value);
  6092. return true;
  6093. }
  6094. readToken_mult_modulo(code) {
  6095. let type = code === 42 ? types.star : types.modulo;
  6096. let width = 1;
  6097. let next = this.input.charCodeAt(this.state.pos + 1);
  6098. const exprAllowed = this.state.exprAllowed;
  6099. if (code === 42 && next === 42) {
  6100. width++;
  6101. next = this.input.charCodeAt(this.state.pos + 2);
  6102. type = types.exponent;
  6103. }
  6104. if (next === 61 && !exprAllowed) {
  6105. width++;
  6106. type = types.assign;
  6107. }
  6108. this.finishOp(type, width);
  6109. }
  6110. readToken_pipe_amp(code) {
  6111. const next = this.input.charCodeAt(this.state.pos + 1);
  6112. if (next === code) {
  6113. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6114. this.finishOp(types.assign, 3);
  6115. } else {
  6116. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6117. }
  6118. return;
  6119. }
  6120. if (code === 124) {
  6121. if (next === 62) {
  6122. this.finishOp(types.pipeline, 2);
  6123. return;
  6124. }
  6125. }
  6126. if (next === 61) {
  6127. this.finishOp(types.assign, 2);
  6128. return;
  6129. }
  6130. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6131. }
  6132. readToken_caret() {
  6133. const next = this.input.charCodeAt(this.state.pos + 1);
  6134. if (next === 61) {
  6135. this.finishOp(types.assign, 2);
  6136. } else {
  6137. this.finishOp(types.bitwiseXOR, 1);
  6138. }
  6139. }
  6140. readToken_plus_min(code) {
  6141. const next = this.input.charCodeAt(this.state.pos + 1);
  6142. if (next === code) {
  6143. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos)))) {
  6144. this.skipLineComment(3);
  6145. this.skipSpace();
  6146. this.nextToken();
  6147. return;
  6148. }
  6149. this.finishOp(types.incDec, 2);
  6150. return;
  6151. }
  6152. if (next === 61) {
  6153. this.finishOp(types.assign, 2);
  6154. } else {
  6155. this.finishOp(types.plusMin, 1);
  6156. }
  6157. }
  6158. readToken_lt_gt(code) {
  6159. const next = this.input.charCodeAt(this.state.pos + 1);
  6160. let size = 1;
  6161. if (next === code) {
  6162. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6163. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6164. this.finishOp(types.assign, size + 1);
  6165. return;
  6166. }
  6167. this.finishOp(types.bitShift, size);
  6168. return;
  6169. }
  6170. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6171. this.skipLineComment(4);
  6172. this.skipSpace();
  6173. this.nextToken();
  6174. return;
  6175. }
  6176. if (next === 61) {
  6177. size = 2;
  6178. }
  6179. this.finishOp(types.relational, size);
  6180. }
  6181. readToken_eq_excl(code) {
  6182. const next = this.input.charCodeAt(this.state.pos + 1);
  6183. if (next === 61) {
  6184. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6185. return;
  6186. }
  6187. if (code === 61 && next === 62) {
  6188. this.state.pos += 2;
  6189. this.finishToken(types.arrow);
  6190. return;
  6191. }
  6192. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6193. }
  6194. readToken_question() {
  6195. const next = this.input.charCodeAt(this.state.pos + 1);
  6196. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6197. if (next === 63 && !this.state.inType) {
  6198. if (next2 === 61) {
  6199. this.finishOp(types.assign, 3);
  6200. } else {
  6201. this.finishOp(types.nullishCoalescing, 2);
  6202. }
  6203. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6204. this.state.pos += 2;
  6205. this.finishToken(types.questionDot);
  6206. } else {
  6207. ++this.state.pos;
  6208. this.finishToken(types.question);
  6209. }
  6210. }
  6211. getTokenFromCode(code) {
  6212. switch (code) {
  6213. case 46:
  6214. this.readToken_dot();
  6215. return;
  6216. case 40:
  6217. ++this.state.pos;
  6218. this.finishToken(types.parenL);
  6219. return;
  6220. case 41:
  6221. ++this.state.pos;
  6222. this.finishToken(types.parenR);
  6223. return;
  6224. case 59:
  6225. ++this.state.pos;
  6226. this.finishToken(types.semi);
  6227. return;
  6228. case 44:
  6229. ++this.state.pos;
  6230. this.finishToken(types.comma);
  6231. return;
  6232. case 91:
  6233. ++this.state.pos;
  6234. this.finishToken(types.bracketL);
  6235. return;
  6236. case 93:
  6237. ++this.state.pos;
  6238. this.finishToken(types.bracketR);
  6239. return;
  6240. case 123:
  6241. ++this.state.pos;
  6242. this.finishToken(types.braceL);
  6243. return;
  6244. case 125:
  6245. ++this.state.pos;
  6246. this.finishToken(types.braceR);
  6247. return;
  6248. case 58:
  6249. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6250. this.finishOp(types.doubleColon, 2);
  6251. } else {
  6252. ++this.state.pos;
  6253. this.finishToken(types.colon);
  6254. }
  6255. return;
  6256. case 63:
  6257. this.readToken_question();
  6258. return;
  6259. case 96:
  6260. ++this.state.pos;
  6261. this.finishToken(types.backQuote);
  6262. return;
  6263. case 48:
  6264. {
  6265. const next = this.input.charCodeAt(this.state.pos + 1);
  6266. if (next === 120 || next === 88) {
  6267. this.readRadixNumber(16);
  6268. return;
  6269. }
  6270. if (next === 111 || next === 79) {
  6271. this.readRadixNumber(8);
  6272. return;
  6273. }
  6274. if (next === 98 || next === 66) {
  6275. this.readRadixNumber(2);
  6276. return;
  6277. }
  6278. }
  6279. case 49:
  6280. case 50:
  6281. case 51:
  6282. case 52:
  6283. case 53:
  6284. case 54:
  6285. case 55:
  6286. case 56:
  6287. case 57:
  6288. this.readNumber(false);
  6289. return;
  6290. case 34:
  6291. case 39:
  6292. this.readString(code);
  6293. return;
  6294. case 47:
  6295. this.readToken_slash();
  6296. return;
  6297. case 37:
  6298. case 42:
  6299. this.readToken_mult_modulo(code);
  6300. return;
  6301. case 124:
  6302. case 38:
  6303. this.readToken_pipe_amp(code);
  6304. return;
  6305. case 94:
  6306. this.readToken_caret();
  6307. return;
  6308. case 43:
  6309. case 45:
  6310. this.readToken_plus_min(code);
  6311. return;
  6312. case 60:
  6313. case 62:
  6314. this.readToken_lt_gt(code);
  6315. return;
  6316. case 61:
  6317. case 33:
  6318. this.readToken_eq_excl(code);
  6319. return;
  6320. case 126:
  6321. this.finishOp(types.tilde, 1);
  6322. return;
  6323. case 64:
  6324. ++this.state.pos;
  6325. this.finishToken(types.at);
  6326. return;
  6327. case 35:
  6328. this.readToken_numberSign();
  6329. return;
  6330. case 92:
  6331. this.readWord();
  6332. return;
  6333. default:
  6334. if (isIdentifierStart(code)) {
  6335. this.readWord();
  6336. return;
  6337. }
  6338. }
  6339. throw this.raise(this.state.pos, `Unexpected character '${String.fromCodePoint(code)}'`);
  6340. }
  6341. finishOp(type, size) {
  6342. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6343. this.state.pos += size;
  6344. this.finishToken(type, str);
  6345. }
  6346. readRegexp() {
  6347. const start = this.state.pos;
  6348. let escaped, inClass;
  6349. for (;;) {
  6350. if (this.state.pos >= this.length) {
  6351. throw this.raise(start, "Unterminated regular expression");
  6352. }
  6353. const ch = this.input.charAt(this.state.pos);
  6354. if (lineBreak.test(ch)) {
  6355. throw this.raise(start, "Unterminated regular expression");
  6356. }
  6357. if (escaped) {
  6358. escaped = false;
  6359. } else {
  6360. if (ch === "[") {
  6361. inClass = true;
  6362. } else if (ch === "]" && inClass) {
  6363. inClass = false;
  6364. } else if (ch === "/" && !inClass) {
  6365. break;
  6366. }
  6367. escaped = ch === "\\";
  6368. }
  6369. ++this.state.pos;
  6370. }
  6371. const content = this.input.slice(start, this.state.pos);
  6372. ++this.state.pos;
  6373. let mods = "";
  6374. while (this.state.pos < this.length) {
  6375. const char = this.input[this.state.pos];
  6376. const charCode = this.input.codePointAt(this.state.pos);
  6377. if (VALID_REGEX_FLAGS.has(char)) {
  6378. if (mods.indexOf(char) > -1) {
  6379. this.raise(this.state.pos + 1, "Duplicate regular expression flag");
  6380. }
  6381. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6382. this.raise(this.state.pos + 1, "Invalid regular expression flag");
  6383. } else {
  6384. break;
  6385. }
  6386. ++this.state.pos;
  6387. mods += char;
  6388. }
  6389. this.finishToken(types.regexp, {
  6390. pattern: content,
  6391. flags: mods
  6392. });
  6393. }
  6394. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6395. const start = this.state.pos;
  6396. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6397. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6398. let invalid = false;
  6399. let total = 0;
  6400. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  6401. const code = this.input.charCodeAt(this.state.pos);
  6402. let val;
  6403. if (this.hasPlugin("numericSeparator")) {
  6404. if (code === 95) {
  6405. const prev = this.input.charCodeAt(this.state.pos - 1);
  6406. const next = this.input.charCodeAt(this.state.pos + 1);
  6407. if (allowedSiblings.indexOf(next) === -1) {
  6408. this.raise(this.state.pos, "A numeric separator is only allowed between two digits");
  6409. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  6410. this.raise(this.state.pos, "A numeric separator is only allowed between two digits");
  6411. }
  6412. if (!allowNumSeparator) {
  6413. this.raise(this.state.pos, "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences");
  6414. }
  6415. ++this.state.pos;
  6416. continue;
  6417. }
  6418. }
  6419. if (code >= 97) {
  6420. val = code - 97 + 10;
  6421. } else if (code >= 65) {
  6422. val = code - 65 + 10;
  6423. } else if (_isDigit(code)) {
  6424. val = code - 48;
  6425. } else {
  6426. val = Infinity;
  6427. }
  6428. if (val >= radix) {
  6429. if (this.options.errorRecovery && val <= 9) {
  6430. val = 0;
  6431. this.raise(this.state.start + i + 2, "Expected number in radix " + radix);
  6432. } else if (forceLen) {
  6433. val = 0;
  6434. invalid = true;
  6435. } else {
  6436. break;
  6437. }
  6438. }
  6439. ++this.state.pos;
  6440. total = total * radix + val;
  6441. }
  6442. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  6443. return null;
  6444. }
  6445. return total;
  6446. }
  6447. readRadixNumber(radix) {
  6448. const start = this.state.pos;
  6449. let isBigInt = false;
  6450. this.state.pos += 2;
  6451. const val = this.readInt(radix);
  6452. if (val == null) {
  6453. this.raise(this.state.start + 2, "Expected number in radix " + radix);
  6454. }
  6455. if (this.hasPlugin("bigInt")) {
  6456. if (this.input.charCodeAt(this.state.pos) === 110) {
  6457. ++this.state.pos;
  6458. isBigInt = true;
  6459. }
  6460. }
  6461. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6462. throw this.raise(this.state.pos, "Identifier directly after number");
  6463. }
  6464. if (isBigInt) {
  6465. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6466. this.finishToken(types.bigint, str);
  6467. return;
  6468. }
  6469. this.finishToken(types.num, val);
  6470. }
  6471. readNumber(startsWithDot) {
  6472. const start = this.state.pos;
  6473. let isFloat = false;
  6474. let isBigInt = false;
  6475. let isNonOctalDecimalInt = false;
  6476. if (!startsWithDot && this.readInt(10) === null) {
  6477. this.raise(start, "Invalid number");
  6478. }
  6479. let octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  6480. if (octal) {
  6481. if (this.state.strict) {
  6482. this.raise(start, "Legacy octal literals are not allowed in strict mode");
  6483. }
  6484. if (/[89]/.test(this.input.slice(start, this.state.pos))) {
  6485. octal = false;
  6486. isNonOctalDecimalInt = true;
  6487. }
  6488. }
  6489. let next = this.input.charCodeAt(this.state.pos);
  6490. if (next === 46 && !octal) {
  6491. ++this.state.pos;
  6492. this.readInt(10);
  6493. isFloat = true;
  6494. next = this.input.charCodeAt(this.state.pos);
  6495. }
  6496. if ((next === 69 || next === 101) && !octal) {
  6497. next = this.input.charCodeAt(++this.state.pos);
  6498. if (next === 43 || next === 45) {
  6499. ++this.state.pos;
  6500. }
  6501. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  6502. isFloat = true;
  6503. next = this.input.charCodeAt(this.state.pos);
  6504. }
  6505. if (this.hasPlugin("numericSeparator") && (octal || isNonOctalDecimalInt)) {
  6506. const underscorePos = this.input.slice(start, this.state.pos).indexOf("_");
  6507. if (underscorePos > 0) {
  6508. this.raise(underscorePos + start, "Numeric separator can not be used after leading 0");
  6509. }
  6510. }
  6511. if (this.hasPlugin("bigInt")) {
  6512. if (next === 110) {
  6513. if (isFloat || octal || isNonOctalDecimalInt) {
  6514. this.raise(start, "Invalid BigIntLiteral");
  6515. }
  6516. ++this.state.pos;
  6517. isBigInt = true;
  6518. }
  6519. }
  6520. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6521. throw this.raise(this.state.pos, "Identifier directly after number");
  6522. }
  6523. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6524. if (isBigInt) {
  6525. this.finishToken(types.bigint, str);
  6526. return;
  6527. }
  6528. const val = octal ? parseInt(str, 8) : parseFloat(str);
  6529. this.finishToken(types.num, val);
  6530. }
  6531. readCodePoint(throwOnInvalid) {
  6532. const ch = this.input.charCodeAt(this.state.pos);
  6533. let code;
  6534. if (ch === 123) {
  6535. const codePos = ++this.state.pos;
  6536. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  6537. ++this.state.pos;
  6538. if (code !== null && code > 0x10ffff) {
  6539. if (throwOnInvalid) {
  6540. this.raise(codePos, "Code point out of bounds");
  6541. } else {
  6542. return null;
  6543. }
  6544. }
  6545. } else {
  6546. code = this.readHexChar(4, false, throwOnInvalid);
  6547. }
  6548. return code;
  6549. }
  6550. readString(quote) {
  6551. let out = "",
  6552. chunkStart = ++this.state.pos;
  6553. for (;;) {
  6554. if (this.state.pos >= this.length) {
  6555. throw this.raise(this.state.start, "Unterminated string constant");
  6556. }
  6557. const ch = this.input.charCodeAt(this.state.pos);
  6558. if (ch === quote) break;
  6559. if (ch === 92) {
  6560. out += this.input.slice(chunkStart, this.state.pos);
  6561. out += this.readEscapedChar(false);
  6562. chunkStart = this.state.pos;
  6563. } else if (ch === 8232 || ch === 8233) {
  6564. ++this.state.pos;
  6565. ++this.state.curLine;
  6566. this.state.lineStart = this.state.pos;
  6567. } else if (isNewLine(ch)) {
  6568. throw this.raise(this.state.start, "Unterminated string constant");
  6569. } else {
  6570. ++this.state.pos;
  6571. }
  6572. }
  6573. out += this.input.slice(chunkStart, this.state.pos++);
  6574. this.finishToken(types.string, out);
  6575. }
  6576. readTmplToken() {
  6577. let out = "",
  6578. chunkStart = this.state.pos,
  6579. containsInvalid = false;
  6580. for (;;) {
  6581. if (this.state.pos >= this.length) {
  6582. throw this.raise(this.state.start, "Unterminated template");
  6583. }
  6584. const ch = this.input.charCodeAt(this.state.pos);
  6585. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  6586. if (this.state.pos === this.state.start && this.match(types.template)) {
  6587. if (ch === 36) {
  6588. this.state.pos += 2;
  6589. this.finishToken(types.dollarBraceL);
  6590. return;
  6591. } else {
  6592. ++this.state.pos;
  6593. this.finishToken(types.backQuote);
  6594. return;
  6595. }
  6596. }
  6597. out += this.input.slice(chunkStart, this.state.pos);
  6598. this.finishToken(types.template, containsInvalid ? null : out);
  6599. return;
  6600. }
  6601. if (ch === 92) {
  6602. out += this.input.slice(chunkStart, this.state.pos);
  6603. const escaped = this.readEscapedChar(true);
  6604. if (escaped === null) {
  6605. containsInvalid = true;
  6606. } else {
  6607. out += escaped;
  6608. }
  6609. chunkStart = this.state.pos;
  6610. } else if (isNewLine(ch)) {
  6611. out += this.input.slice(chunkStart, this.state.pos);
  6612. ++this.state.pos;
  6613. switch (ch) {
  6614. case 13:
  6615. if (this.input.charCodeAt(this.state.pos) === 10) {
  6616. ++this.state.pos;
  6617. }
  6618. case 10:
  6619. out += "\n";
  6620. break;
  6621. default:
  6622. out += String.fromCharCode(ch);
  6623. break;
  6624. }
  6625. ++this.state.curLine;
  6626. this.state.lineStart = this.state.pos;
  6627. chunkStart = this.state.pos;
  6628. } else {
  6629. ++this.state.pos;
  6630. }
  6631. }
  6632. }
  6633. readEscapedChar(inTemplate) {
  6634. const throwOnInvalid = !inTemplate;
  6635. const ch = this.input.charCodeAt(++this.state.pos);
  6636. ++this.state.pos;
  6637. switch (ch) {
  6638. case 110:
  6639. return "\n";
  6640. case 114:
  6641. return "\r";
  6642. case 120:
  6643. {
  6644. const code = this.readHexChar(2, false, throwOnInvalid);
  6645. return code === null ? null : String.fromCharCode(code);
  6646. }
  6647. case 117:
  6648. {
  6649. const code = this.readCodePoint(throwOnInvalid);
  6650. return code === null ? null : String.fromCodePoint(code);
  6651. }
  6652. case 116:
  6653. return "\t";
  6654. case 98:
  6655. return "\b";
  6656. case 118:
  6657. return "\u000b";
  6658. case 102:
  6659. return "\f";
  6660. case 13:
  6661. if (this.input.charCodeAt(this.state.pos) === 10) {
  6662. ++this.state.pos;
  6663. }
  6664. case 10:
  6665. this.state.lineStart = this.state.pos;
  6666. ++this.state.curLine;
  6667. case 8232:
  6668. case 8233:
  6669. return "";
  6670. case 56:
  6671. case 57:
  6672. if (inTemplate) {
  6673. return null;
  6674. }
  6675. default:
  6676. if (ch >= 48 && ch <= 55) {
  6677. const codePos = this.state.pos - 1;
  6678. let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
  6679. let octal = parseInt(octalStr, 8);
  6680. if (octal > 255) {
  6681. octalStr = octalStr.slice(0, -1);
  6682. octal = parseInt(octalStr, 8);
  6683. }
  6684. this.state.pos += octalStr.length - 1;
  6685. const next = this.input.charCodeAt(this.state.pos);
  6686. if (octalStr !== "0" || next === 56 || next === 57) {
  6687. if (inTemplate) {
  6688. return null;
  6689. } else if (this.state.strict) {
  6690. this.raise(codePos, "Octal literal in strict mode");
  6691. } else if (!this.state.containsOctal) {
  6692. this.state.containsOctal = true;
  6693. this.state.octalPosition = codePos;
  6694. }
  6695. }
  6696. return String.fromCharCode(octal);
  6697. }
  6698. return String.fromCharCode(ch);
  6699. }
  6700. }
  6701. readHexChar(len, forceLen, throwOnInvalid) {
  6702. const codePos = this.state.pos;
  6703. const n = this.readInt(16, len, forceLen, false);
  6704. if (n === null) {
  6705. if (throwOnInvalid) {
  6706. this.raise(codePos, "Bad character escape sequence");
  6707. } else {
  6708. this.state.pos = codePos - 1;
  6709. }
  6710. }
  6711. return n;
  6712. }
  6713. readWord1() {
  6714. let word = "";
  6715. this.state.containsEsc = false;
  6716. const start = this.state.pos;
  6717. let chunkStart = this.state.pos;
  6718. while (this.state.pos < this.length) {
  6719. const ch = this.input.codePointAt(this.state.pos);
  6720. if (isIdentifierChar(ch)) {
  6721. this.state.pos += ch <= 0xffff ? 1 : 2;
  6722. } else if (this.state.isIterator && ch === 64) {
  6723. ++this.state.pos;
  6724. } else if (ch === 92) {
  6725. this.state.containsEsc = true;
  6726. word += this.input.slice(chunkStart, this.state.pos);
  6727. const escStart = this.state.pos;
  6728. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  6729. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  6730. this.raise(this.state.pos, "Expecting Unicode escape sequence \\uXXXX");
  6731. continue;
  6732. }
  6733. ++this.state.pos;
  6734. const esc = this.readCodePoint(true);
  6735. if (esc !== null) {
  6736. if (!identifierCheck(esc)) {
  6737. this.raise(escStart, "Invalid Unicode escape");
  6738. }
  6739. word += String.fromCodePoint(esc);
  6740. }
  6741. chunkStart = this.state.pos;
  6742. } else {
  6743. break;
  6744. }
  6745. }
  6746. return word + this.input.slice(chunkStart, this.state.pos);
  6747. }
  6748. isIterator(word) {
  6749. return word === "@@iterator" || word === "@@asyncIterator";
  6750. }
  6751. readWord() {
  6752. const word = this.readWord1();
  6753. const type = keywords.get(word) || types.name;
  6754. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  6755. this.raise(this.state.pos, `Invalid identifier ${word}`);
  6756. }
  6757. this.finishToken(type, word);
  6758. }
  6759. checkKeywordEscapes() {
  6760. const kw = this.state.type.keyword;
  6761. if (kw && this.state.containsEsc) {
  6762. this.raise(this.state.start, `Escape sequence in keyword ${kw}`);
  6763. }
  6764. }
  6765. braceIsBlock(prevType) {
  6766. const parent = this.curContext();
  6767. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  6768. return true;
  6769. }
  6770. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  6771. return !parent.isExpr;
  6772. }
  6773. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  6774. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  6775. }
  6776. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  6777. return true;
  6778. }
  6779. if (prevType === types.braceL) {
  6780. return parent === types$1.braceStatement;
  6781. }
  6782. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  6783. return false;
  6784. }
  6785. if (prevType === types.relational) {
  6786. return true;
  6787. }
  6788. return !this.state.exprAllowed;
  6789. }
  6790. updateContext(prevType) {
  6791. const type = this.state.type;
  6792. let update;
  6793. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  6794. this.state.exprAllowed = false;
  6795. } else if (update = type.updateContext) {
  6796. update.call(this, prevType);
  6797. } else {
  6798. this.state.exprAllowed = type.beforeExpr;
  6799. }
  6800. }
  6801. }
  6802. const literal = /^('|")((?:\\?.)*?)\1/;
  6803. class UtilParser extends Tokenizer {
  6804. addExtra(node, key, val) {
  6805. if (!node) return;
  6806. const extra = node.extra = node.extra || {};
  6807. extra[key] = val;
  6808. }
  6809. isRelational(op) {
  6810. return this.match(types.relational) && this.state.value === op;
  6811. }
  6812. isLookaheadRelational(op) {
  6813. const next = this.nextTokenStart();
  6814. if (this.input.charAt(next) === op) {
  6815. if (next + 1 === this.input.length) {
  6816. return true;
  6817. }
  6818. const afterNext = this.input.charCodeAt(next + 1);
  6819. return afterNext !== op.charCodeAt(0) && afterNext !== 61;
  6820. }
  6821. return false;
  6822. }
  6823. expectRelational(op) {
  6824. if (this.isRelational(op)) {
  6825. this.next();
  6826. } else {
  6827. this.unexpected(null, types.relational);
  6828. }
  6829. }
  6830. isContextual(name) {
  6831. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  6832. }
  6833. isUnparsedContextual(nameStart, name) {
  6834. const nameEnd = nameStart + name.length;
  6835. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  6836. }
  6837. isLookaheadContextual(name) {
  6838. const next = this.nextTokenStart();
  6839. return this.isUnparsedContextual(next, name);
  6840. }
  6841. eatContextual(name) {
  6842. return this.isContextual(name) && this.eat(types.name);
  6843. }
  6844. expectContextual(name, message) {
  6845. if (!this.eatContextual(name)) this.unexpected(null, message);
  6846. }
  6847. canInsertSemicolon() {
  6848. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  6849. }
  6850. hasPrecedingLineBreak() {
  6851. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  6852. }
  6853. isLineTerminator() {
  6854. return this.eat(types.semi) || this.canInsertSemicolon();
  6855. }
  6856. semicolon() {
  6857. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  6858. }
  6859. expect(type, pos) {
  6860. this.eat(type) || this.unexpected(pos, type);
  6861. }
  6862. assertNoSpace(message = "Unexpected space.") {
  6863. if (this.state.start > this.state.lastTokEnd) {
  6864. this.raise(this.state.lastTokEnd, message);
  6865. }
  6866. }
  6867. unexpected(pos, messageOrType = "Unexpected token") {
  6868. if (typeof messageOrType !== "string") {
  6869. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  6870. }
  6871. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  6872. }
  6873. expectPlugin(name, pos) {
  6874. if (!this.hasPlugin(name)) {
  6875. throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling the parser plugin: '${name}'`, {
  6876. missingPluginNames: [name]
  6877. });
  6878. }
  6879. return true;
  6880. }
  6881. expectOnePlugin(names, pos) {
  6882. if (!names.some(n => this.hasPlugin(n))) {
  6883. throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`, {
  6884. missingPluginNames: names
  6885. });
  6886. }
  6887. }
  6888. checkYieldAwaitInDefaultParams() {
  6889. if (this.state.yieldPos !== -1 && (this.state.awaitPos === -1 || this.state.yieldPos < this.state.awaitPos)) {
  6890. this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function");
  6891. }
  6892. if (this.state.awaitPos !== -1) {
  6893. this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function");
  6894. }
  6895. }
  6896. strictDirective(start) {
  6897. for (;;) {
  6898. skipWhiteSpace.lastIndex = start;
  6899. start += skipWhiteSpace.exec(this.input)[0].length;
  6900. const match = literal.exec(this.input.slice(start));
  6901. if (!match) break;
  6902. if (match[2] === "use strict") return true;
  6903. start += match[0].length;
  6904. skipWhiteSpace.lastIndex = start;
  6905. start += skipWhiteSpace.exec(this.input)[0].length;
  6906. if (this.input[start] === ";") {
  6907. start++;
  6908. }
  6909. }
  6910. return false;
  6911. }
  6912. tryParse(fn, oldState = this.state.clone()) {
  6913. const abortSignal = {
  6914. node: null
  6915. };
  6916. try {
  6917. const node = fn((node = null) => {
  6918. abortSignal.node = node;
  6919. throw abortSignal;
  6920. });
  6921. if (this.state.errors.length > oldState.errors.length) {
  6922. const failState = this.state;
  6923. this.state = oldState;
  6924. return {
  6925. node,
  6926. error: failState.errors[oldState.errors.length],
  6927. thrown: false,
  6928. aborted: false,
  6929. failState
  6930. };
  6931. }
  6932. return {
  6933. node,
  6934. error: null,
  6935. thrown: false,
  6936. aborted: false,
  6937. failState: null
  6938. };
  6939. } catch (error) {
  6940. const failState = this.state;
  6941. this.state = oldState;
  6942. if (error instanceof SyntaxError) {
  6943. return {
  6944. node: null,
  6945. error,
  6946. thrown: true,
  6947. aborted: false,
  6948. failState
  6949. };
  6950. }
  6951. if (error === abortSignal) {
  6952. return {
  6953. node: abortSignal.node,
  6954. error: null,
  6955. thrown: false,
  6956. aborted: true,
  6957. failState
  6958. };
  6959. }
  6960. throw error;
  6961. }
  6962. }
  6963. checkExpressionErrors(refExpressionErrors, andThrow) {
  6964. if (!refExpressionErrors) return false;
  6965. const {
  6966. shorthandAssign,
  6967. doubleProto
  6968. } = refExpressionErrors;
  6969. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  6970. if (shorthandAssign >= 0) {
  6971. this.unexpected(shorthandAssign);
  6972. }
  6973. if (doubleProto >= 0) {
  6974. this.raise(doubleProto, "Redefinition of __proto__ property");
  6975. }
  6976. }
  6977. }
  6978. class ExpressionErrors {
  6979. constructor() {
  6980. this.shorthandAssign = -1;
  6981. this.doubleProto = -1;
  6982. }
  6983. }
  6984. class Node {
  6985. constructor(parser, pos, loc) {
  6986. this.type = "";
  6987. this.start = pos;
  6988. this.end = 0;
  6989. this.loc = new SourceLocation(loc);
  6990. if (parser && parser.options.ranges) this.range = [pos, 0];
  6991. if (parser && parser.filename) this.loc.filename = parser.filename;
  6992. }
  6993. __clone() {
  6994. const newNode = new Node();
  6995. const keys = Object.keys(this);
  6996. for (let i = 0, length = keys.length; i < length; i++) {
  6997. const key = keys[i];
  6998. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  6999. newNode[key] = this[key];
  7000. }
  7001. }
  7002. return newNode;
  7003. }
  7004. }
  7005. class NodeUtils extends UtilParser {
  7006. startNode() {
  7007. return new Node(this, this.state.start, this.state.startLoc);
  7008. }
  7009. startNodeAt(pos, loc) {
  7010. return new Node(this, pos, loc);
  7011. }
  7012. startNodeAtNode(type) {
  7013. return this.startNodeAt(type.start, type.loc.start);
  7014. }
  7015. finishNode(node, type) {
  7016. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  7017. }
  7018. finishNodeAt(node, type, pos, loc) {
  7019. node.type = type;
  7020. node.end = pos;
  7021. node.loc.end = loc;
  7022. if (this.options.ranges) node.range[1] = pos;
  7023. this.processComment(node);
  7024. return node;
  7025. }
  7026. resetStartLocation(node, start, startLoc) {
  7027. node.start = start;
  7028. node.loc.start = startLoc;
  7029. if (this.options.ranges) node.range[0] = start;
  7030. }
  7031. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  7032. node.end = end;
  7033. node.loc.end = endLoc;
  7034. if (this.options.ranges) node.range[1] = end;
  7035. }
  7036. resetStartLocationFromNode(node, locationNode) {
  7037. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  7038. }
  7039. }
  7040. const unwrapParenthesizedExpression = node => {
  7041. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7042. };
  7043. class LValParser extends NodeUtils {
  7044. toAssignable(node) {
  7045. var _node$extra, _node$extra3;
  7046. let parenthesized = undefined;
  7047. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  7048. parenthesized = unwrapParenthesizedExpression(node);
  7049. if (parenthesized.type !== "Identifier" && parenthesized.type !== "MemberExpression") {
  7050. this.raise(node.start, "Invalid parenthesized assignment pattern");
  7051. }
  7052. }
  7053. switch (node.type) {
  7054. case "Identifier":
  7055. case "ObjectPattern":
  7056. case "ArrayPattern":
  7057. case "AssignmentPattern":
  7058. break;
  7059. case "ObjectExpression":
  7060. node.type = "ObjectPattern";
  7061. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7062. var _node$extra2;
  7063. const prop = node.properties[i];
  7064. const isLast = i === last;
  7065. this.toAssignableObjectExpressionProp(prop, isLast);
  7066. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  7067. this.raiseRestNotLast(node.extra.trailingComma);
  7068. }
  7069. }
  7070. break;
  7071. case "ObjectProperty":
  7072. this.toAssignable(node.value);
  7073. break;
  7074. case "SpreadElement":
  7075. {
  7076. this.checkToRestConversion(node);
  7077. node.type = "RestElement";
  7078. const arg = node.argument;
  7079. this.toAssignable(arg);
  7080. break;
  7081. }
  7082. case "ArrayExpression":
  7083. node.type = "ArrayPattern";
  7084. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma);
  7085. break;
  7086. case "AssignmentExpression":
  7087. if (node.operator !== "=") {
  7088. this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
  7089. }
  7090. node.type = "AssignmentPattern";
  7091. delete node.operator;
  7092. this.toAssignable(node.left);
  7093. break;
  7094. case "ParenthesizedExpression":
  7095. this.toAssignable(parenthesized);
  7096. break;
  7097. }
  7098. return node;
  7099. }
  7100. toAssignableObjectExpressionProp(prop, isLast) {
  7101. if (prop.type === "ObjectMethod") {
  7102. const error = prop.kind === "get" || prop.kind === "set" ? "Object pattern can't contain getter or setter" : "Object pattern can't contain methods";
  7103. this.raise(prop.key.start, error);
  7104. } else if (prop.type === "SpreadElement" && !isLast) {
  7105. this.raiseRestNotLast(prop.start);
  7106. } else {
  7107. this.toAssignable(prop);
  7108. }
  7109. }
  7110. toAssignableList(exprList, trailingCommaPos) {
  7111. let end = exprList.length;
  7112. if (end) {
  7113. const last = exprList[end - 1];
  7114. if (last && last.type === "RestElement") {
  7115. --end;
  7116. } else if (last && last.type === "SpreadElement") {
  7117. last.type = "RestElement";
  7118. const arg = last.argument;
  7119. this.toAssignable(arg);
  7120. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7121. this.unexpected(arg.start);
  7122. }
  7123. if (trailingCommaPos) {
  7124. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7125. }
  7126. --end;
  7127. }
  7128. }
  7129. for (let i = 0; i < end; i++) {
  7130. const elt = exprList[i];
  7131. if (elt) {
  7132. this.toAssignable(elt);
  7133. if (elt.type === "RestElement") {
  7134. this.raiseRestNotLast(elt.start);
  7135. }
  7136. }
  7137. }
  7138. return exprList;
  7139. }
  7140. toReferencedList(exprList, isParenthesizedExpr) {
  7141. return exprList;
  7142. }
  7143. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7144. this.toReferencedList(exprList, isParenthesizedExpr);
  7145. for (let _i = 0; _i < exprList.length; _i++) {
  7146. const expr = exprList[_i];
  7147. if (expr && expr.type === "ArrayExpression") {
  7148. this.toReferencedListDeep(expr.elements);
  7149. }
  7150. }
  7151. }
  7152. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  7153. const node = this.startNode();
  7154. this.next();
  7155. node.argument = this.parseMaybeAssign(false, refExpressionErrors, undefined, refNeedsArrowPos);
  7156. return this.finishNode(node, "SpreadElement");
  7157. }
  7158. parseRestBinding() {
  7159. const node = this.startNode();
  7160. this.next();
  7161. node.argument = this.parseBindingAtom();
  7162. return this.finishNode(node, "RestElement");
  7163. }
  7164. parseBindingAtom() {
  7165. switch (this.state.type) {
  7166. case types.bracketL:
  7167. {
  7168. const node = this.startNode();
  7169. this.next();
  7170. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7171. return this.finishNode(node, "ArrayPattern");
  7172. }
  7173. case types.braceL:
  7174. return this.parseObj(true);
  7175. }
  7176. return this.parseIdentifier();
  7177. }
  7178. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7179. const elts = [];
  7180. let first = true;
  7181. while (!this.eat(close)) {
  7182. if (first) {
  7183. first = false;
  7184. } else {
  7185. this.expect(types.comma);
  7186. }
  7187. if (allowEmpty && this.match(types.comma)) {
  7188. elts.push(null);
  7189. } else if (this.eat(close)) {
  7190. break;
  7191. } else if (this.match(types.ellipsis)) {
  7192. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7193. this.checkCommaAfterRest(closeCharCode);
  7194. this.expect(close);
  7195. break;
  7196. } else {
  7197. const decorators = [];
  7198. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7199. this.raise(this.state.start, "Stage 2 decorators cannot be used to decorate parameters");
  7200. }
  7201. while (this.match(types.at)) {
  7202. decorators.push(this.parseDecorator());
  7203. }
  7204. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7205. }
  7206. }
  7207. return elts;
  7208. }
  7209. parseAssignableListItem(allowModifiers, decorators) {
  7210. const left = this.parseMaybeDefault();
  7211. this.parseAssignableListItemTypes(left);
  7212. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7213. if (decorators.length) {
  7214. left.decorators = decorators;
  7215. }
  7216. return elt;
  7217. }
  7218. parseAssignableListItemTypes(param) {
  7219. return param;
  7220. }
  7221. parseMaybeDefault(startPos, startLoc, left) {
  7222. startLoc = startLoc || this.state.startLoc;
  7223. startPos = startPos || this.state.start;
  7224. left = left || this.parseBindingAtom();
  7225. if (!this.eat(types.eq)) return left;
  7226. const node = this.startNodeAt(startPos, startLoc);
  7227. node.left = left;
  7228. node.right = this.parseMaybeAssign();
  7229. return this.finishNode(node, "AssignmentPattern");
  7230. }
  7231. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding, strictModeChanged = false) {
  7232. switch (expr.type) {
  7233. case "Identifier":
  7234. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) {
  7235. this.raise(expr.start, `${bindingType === BIND_NONE ? "Assigning to" : "Binding"} '${expr.name}' in strict mode`);
  7236. }
  7237. if (checkClashes) {
  7238. const key = `_${expr.name}`;
  7239. if (checkClashes[key]) {
  7240. this.raise(expr.start, "Argument name clash");
  7241. } else {
  7242. checkClashes[key] = true;
  7243. }
  7244. }
  7245. if (disallowLetBinding && expr.name === "let") {
  7246. this.raise(expr.start, "'let' is not allowed to be used as a name in 'let' or 'const' declarations.");
  7247. }
  7248. if (!(bindingType & BIND_NONE)) {
  7249. this.scope.declareName(expr.name, bindingType, expr.start);
  7250. }
  7251. break;
  7252. case "MemberExpression":
  7253. if (bindingType !== BIND_NONE) {
  7254. this.raise(expr.start, "Binding member expression");
  7255. }
  7256. break;
  7257. case "ObjectPattern":
  7258. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7259. let prop = _expr$properties[_i2];
  7260. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  7261. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  7262. }
  7263. break;
  7264. case "ArrayPattern":
  7265. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7266. const elem = _expr$elements[_i3];
  7267. if (elem) {
  7268. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding);
  7269. }
  7270. }
  7271. break;
  7272. case "AssignmentPattern":
  7273. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  7274. break;
  7275. case "RestElement":
  7276. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  7277. break;
  7278. case "ParenthesizedExpression":
  7279. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  7280. break;
  7281. default:
  7282. {
  7283. const message = (bindingType === BIND_NONE ? "Invalid" : "Binding invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : "expression");
  7284. this.raise(expr.start, message);
  7285. }
  7286. }
  7287. }
  7288. checkToRestConversion(node) {
  7289. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7290. this.raise(node.argument.start, "Invalid rest operator's argument");
  7291. }
  7292. }
  7293. checkCommaAfterRest(close) {
  7294. if (this.match(types.comma)) {
  7295. if (this.lookaheadCharCode() === close) {
  7296. this.raiseTrailingCommaAfterRest(this.state.start);
  7297. } else {
  7298. this.raiseRestNotLast(this.state.start);
  7299. }
  7300. }
  7301. }
  7302. raiseRestNotLast(pos) {
  7303. throw this.raise(pos, `Rest element must be last element`);
  7304. }
  7305. raiseTrailingCommaAfterRest(pos) {
  7306. this.raise(pos, `Unexpected trailing comma after rest element`);
  7307. }
  7308. }
  7309. class ExpressionParser extends LValParser {
  7310. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  7311. if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) {
  7312. return;
  7313. }
  7314. const key = prop.key;
  7315. const name = key.type === "Identifier" ? key.name : String(key.value);
  7316. if (name === "__proto__") {
  7317. if (protoRef.used) {
  7318. if (refExpressionErrors) {
  7319. if (refExpressionErrors.doubleProto === -1) {
  7320. refExpressionErrors.doubleProto = key.start;
  7321. }
  7322. } else {
  7323. this.raise(key.start, "Redefinition of __proto__ property");
  7324. }
  7325. }
  7326. protoRef.used = true;
  7327. }
  7328. }
  7329. getExpression() {
  7330. let scopeFlags = SCOPE_PROGRAM;
  7331. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  7332. scopeFlags |= SCOPE_ASYNC;
  7333. }
  7334. this.scope.enter(scopeFlags);
  7335. this.nextToken();
  7336. const expr = this.parseExpression();
  7337. if (!this.match(types.eof)) {
  7338. this.unexpected();
  7339. }
  7340. expr.comments = this.state.comments;
  7341. expr.errors = this.state.errors;
  7342. return expr;
  7343. }
  7344. parseExpression(noIn, refExpressionErrors) {
  7345. const startPos = this.state.start;
  7346. const startLoc = this.state.startLoc;
  7347. const expr = this.parseMaybeAssign(noIn, refExpressionErrors);
  7348. if (this.match(types.comma)) {
  7349. const node = this.startNodeAt(startPos, startLoc);
  7350. node.expressions = [expr];
  7351. while (this.eat(types.comma)) {
  7352. node.expressions.push(this.parseMaybeAssign(noIn, refExpressionErrors));
  7353. }
  7354. this.toReferencedList(node.expressions);
  7355. return this.finishNode(node, "SequenceExpression");
  7356. }
  7357. return expr;
  7358. }
  7359. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  7360. const startPos = this.state.start;
  7361. const startLoc = this.state.startLoc;
  7362. if (this.isContextual("yield")) {
  7363. if (this.scope.inGenerator) {
  7364. let left = this.parseYield(noIn);
  7365. if (afterLeftParse) {
  7366. left = afterLeftParse.call(this, left, startPos, startLoc);
  7367. }
  7368. return left;
  7369. } else {
  7370. this.state.exprAllowed = false;
  7371. }
  7372. }
  7373. let ownExpressionErrors;
  7374. if (refExpressionErrors) {
  7375. ownExpressionErrors = false;
  7376. } else {
  7377. refExpressionErrors = new ExpressionErrors();
  7378. ownExpressionErrors = true;
  7379. }
  7380. if (this.match(types.parenL) || this.match(types.name)) {
  7381. this.state.potentialArrowAt = this.state.start;
  7382. }
  7383. let left = this.parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos);
  7384. if (afterLeftParse) {
  7385. left = afterLeftParse.call(this, left, startPos, startLoc);
  7386. }
  7387. if (this.state.type.isAssign) {
  7388. const node = this.startNodeAt(startPos, startLoc);
  7389. const operator = this.state.value;
  7390. node.operator = operator;
  7391. if (operator === "??=") {
  7392. this.expectPlugin("logicalAssignment");
  7393. }
  7394. if (operator === "||=" || operator === "&&=") {
  7395. this.expectPlugin("logicalAssignment");
  7396. }
  7397. if (this.match(types.eq)) {
  7398. node.left = this.toAssignable(left);
  7399. refExpressionErrors.doubleProto = -1;
  7400. } else {
  7401. node.left = left;
  7402. }
  7403. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  7404. refExpressionErrors.shorthandAssign = -1;
  7405. }
  7406. this.checkLVal(left, undefined, undefined, "assignment expression");
  7407. this.next();
  7408. node.right = this.parseMaybeAssign(noIn);
  7409. return this.finishNode(node, "AssignmentExpression");
  7410. } else if (ownExpressionErrors) {
  7411. this.checkExpressionErrors(refExpressionErrors, true);
  7412. }
  7413. return left;
  7414. }
  7415. parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos) {
  7416. const startPos = this.state.start;
  7417. const startLoc = this.state.startLoc;
  7418. const potentialArrowAt = this.state.potentialArrowAt;
  7419. const expr = this.parseExprOps(noIn, refExpressionErrors);
  7420. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7421. return expr;
  7422. }
  7423. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7424. return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  7425. }
  7426. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  7427. if (this.eat(types.question)) {
  7428. const node = this.startNodeAt(startPos, startLoc);
  7429. node.test = expr;
  7430. node.consequent = this.parseMaybeAssign();
  7431. this.expect(types.colon);
  7432. node.alternate = this.parseMaybeAssign(noIn);
  7433. return this.finishNode(node, "ConditionalExpression");
  7434. }
  7435. return expr;
  7436. }
  7437. parseExprOps(noIn, refExpressionErrors) {
  7438. const startPos = this.state.start;
  7439. const startLoc = this.state.startLoc;
  7440. const potentialArrowAt = this.state.potentialArrowAt;
  7441. const expr = this.parseMaybeUnary(refExpressionErrors);
  7442. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7443. return expr;
  7444. }
  7445. if (this.checkExpressionErrors(refExpressionErrors, false)) {
  7446. return expr;
  7447. }
  7448. return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  7449. }
  7450. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  7451. let prec = this.state.type.binop;
  7452. if (prec != null && (!noIn || !this.match(types._in))) {
  7453. if (prec > minPrec) {
  7454. const operator = this.state.value;
  7455. if (operator === "|>" && this.state.inFSharpPipelineDirectBody) {
  7456. return left;
  7457. }
  7458. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  7459. node.left = left;
  7460. node.operator = operator;
  7461. if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  7462. this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");
  7463. }
  7464. const op = this.state.type;
  7465. const logical = op === types.logicalOR || op === types.logicalAND;
  7466. const coalesce = op === types.nullishCoalescing;
  7467. if (op === types.pipeline) {
  7468. this.expectPlugin("pipelineOperator");
  7469. this.state.inPipeline = true;
  7470. this.checkPipelineAtInfixOperator(left, leftStartPos);
  7471. } else if (coalesce) {
  7472. prec = types.logicalAND.binop;
  7473. }
  7474. this.next();
  7475. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  7476. if (this.match(types.name) && this.state.value === "await" && this.scope.inAsync) {
  7477. throw this.raise(this.state.start, `Unexpected "await" after pipeline body; await must have parentheses in minimal proposal`);
  7478. }
  7479. }
  7480. node.right = this.parseExprOpRightExpr(op, prec, noIn);
  7481. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  7482. const nextOp = this.state.type;
  7483. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  7484. throw this.raise(this.state.start, `Nullish coalescing operator(??) requires parens when mixing with logical operators`);
  7485. }
  7486. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  7487. }
  7488. }
  7489. return left;
  7490. }
  7491. parseExprOpRightExpr(op, prec, noIn) {
  7492. const startPos = this.state.start;
  7493. const startLoc = this.state.startLoc;
  7494. switch (op) {
  7495. case types.pipeline:
  7496. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  7497. case "smart":
  7498. return this.withTopicPermittingContext(() => {
  7499. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc);
  7500. });
  7501. case "fsharp":
  7502. return this.withSoloAwaitPermittingContext(() => {
  7503. return this.parseFSharpPipelineBody(prec, noIn);
  7504. });
  7505. }
  7506. default:
  7507. return this.parseExprOpBaseRightExpr(op, prec, noIn);
  7508. }
  7509. }
  7510. parseExprOpBaseRightExpr(op, prec, noIn) {
  7511. const startPos = this.state.start;
  7512. const startLoc = this.state.startLoc;
  7513. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
  7514. }
  7515. parseMaybeUnary(refExpressionErrors) {
  7516. if (this.isContextual("await") && this.isAwaitAllowed()) {
  7517. return this.parseAwait();
  7518. } else if (this.state.type.prefix) {
  7519. const node = this.startNode();
  7520. const update = this.match(types.incDec);
  7521. node.operator = this.state.value;
  7522. node.prefix = true;
  7523. if (node.operator === "throw") {
  7524. this.expectPlugin("throwExpressions");
  7525. }
  7526. this.next();
  7527. node.argument = this.parseMaybeUnary();
  7528. this.checkExpressionErrors(refExpressionErrors, true);
  7529. if (update) {
  7530. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  7531. } else if (this.state.strict && node.operator === "delete") {
  7532. const arg = node.argument;
  7533. if (arg.type === "Identifier") {
  7534. this.raise(node.start, "Deleting local variable in strict mode");
  7535. } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") {
  7536. this.raise(node.start, "Deleting a private field is not allowed");
  7537. }
  7538. }
  7539. return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  7540. }
  7541. const startPos = this.state.start;
  7542. const startLoc = this.state.startLoc;
  7543. let expr = this.parseExprSubscripts(refExpressionErrors);
  7544. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7545. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  7546. const node = this.startNodeAt(startPos, startLoc);
  7547. node.operator = this.state.value;
  7548. node.prefix = false;
  7549. node.argument = expr;
  7550. this.checkLVal(expr, undefined, undefined, "postfix operation");
  7551. this.next();
  7552. expr = this.finishNode(node, "UpdateExpression");
  7553. }
  7554. return expr;
  7555. }
  7556. parseExprSubscripts(refExpressionErrors) {
  7557. const startPos = this.state.start;
  7558. const startLoc = this.state.startLoc;
  7559. const potentialArrowAt = this.state.potentialArrowAt;
  7560. const expr = this.parseExprAtom(refExpressionErrors);
  7561. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7562. return expr;
  7563. }
  7564. return this.parseSubscripts(expr, startPos, startLoc);
  7565. }
  7566. parseSubscripts(base, startPos, startLoc, noCalls) {
  7567. const state = {
  7568. optionalChainMember: false,
  7569. maybeAsyncArrow: this.atPossibleAsync(base),
  7570. stop: false
  7571. };
  7572. do {
  7573. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  7574. state.maybeAsyncArrow = false;
  7575. } while (!state.stop);
  7576. return base;
  7577. }
  7578. parseSubscript(base, startPos, startLoc, noCalls, state) {
  7579. if (!noCalls && this.eat(types.doubleColon)) {
  7580. const node = this.startNodeAt(startPos, startLoc);
  7581. node.object = base;
  7582. node.callee = this.parseNoCallExpr();
  7583. state.stop = true;
  7584. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  7585. }
  7586. let optional = false;
  7587. if (this.match(types.questionDot)) {
  7588. state.optionalChainMember = optional = true;
  7589. if (noCalls && this.lookaheadCharCode() === 40) {
  7590. state.stop = true;
  7591. return base;
  7592. }
  7593. this.next();
  7594. }
  7595. const computed = this.eat(types.bracketL);
  7596. if (optional && !this.match(types.parenL) && !this.match(types.backQuote) || computed || this.eat(types.dot)) {
  7597. const node = this.startNodeAt(startPos, startLoc);
  7598. node.object = base;
  7599. node.property = computed ? this.parseExpression() : optional ? this.parseIdentifier(true) : this.parseMaybePrivateName(true);
  7600. node.computed = computed;
  7601. if (node.property.type === "PrivateName") {
  7602. if (node.object.type === "Super") {
  7603. this.raise(startPos, "Private fields can't be accessed on super");
  7604. }
  7605. this.classScope.usePrivateName(node.property.id.name, node.property.start);
  7606. }
  7607. if (computed) {
  7608. this.expect(types.bracketR);
  7609. }
  7610. if (state.optionalChainMember) {
  7611. node.optional = optional;
  7612. return this.finishNode(node, "OptionalMemberExpression");
  7613. } else {
  7614. return this.finishNode(node, "MemberExpression");
  7615. }
  7616. } else if (!noCalls && this.match(types.parenL)) {
  7617. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7618. const oldYieldPos = this.state.yieldPos;
  7619. const oldAwaitPos = this.state.awaitPos;
  7620. this.state.maybeInArrowParameters = true;
  7621. this.state.yieldPos = -1;
  7622. this.state.awaitPos = -1;
  7623. this.next();
  7624. let node = this.startNodeAt(startPos, startLoc);
  7625. node.callee = base;
  7626. if (optional) {
  7627. node.optional = true;
  7628. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  7629. } else {
  7630. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  7631. }
  7632. this.finishCallExpression(node, state.optionalChainMember);
  7633. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  7634. state.stop = true;
  7635. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  7636. this.checkYieldAwaitInDefaultParams();
  7637. this.state.yieldPos = oldYieldPos;
  7638. this.state.awaitPos = oldAwaitPos;
  7639. } else {
  7640. this.toReferencedListDeep(node.arguments);
  7641. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  7642. if (!this.isAwaitAllowed() && !oldMaybeInArrowParameters || oldAwaitPos !== -1) {
  7643. this.state.awaitPos = oldAwaitPos;
  7644. }
  7645. }
  7646. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7647. return node;
  7648. } else if (this.match(types.backQuote)) {
  7649. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state);
  7650. } else {
  7651. state.stop = true;
  7652. return base;
  7653. }
  7654. }
  7655. parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) {
  7656. const node = this.startNodeAt(startPos, startLoc);
  7657. node.tag = base;
  7658. node.quasi = this.parseTemplate(true);
  7659. if (typeArguments) node.typeParameters = typeArguments;
  7660. if (state.optionalChainMember) {
  7661. this.raise(startPos, "Tagged Template Literals are not allowed in optionalChain");
  7662. }
  7663. return this.finishNode(node, "TaggedTemplateExpression");
  7664. }
  7665. atPossibleAsync(base) {
  7666. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async";
  7667. }
  7668. finishCallExpression(node, optional) {
  7669. if (node.callee.type === "Import") {
  7670. if (node.arguments.length !== 1) {
  7671. this.raise(node.start, "import() requires exactly one argument");
  7672. } else {
  7673. const importArg = node.arguments[0];
  7674. if (importArg && importArg.type === "SpreadElement") {
  7675. this.raise(importArg.start, "... is not allowed in import()");
  7676. }
  7677. }
  7678. }
  7679. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  7680. }
  7681. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  7682. const elts = [];
  7683. let innerParenStart;
  7684. let first = true;
  7685. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7686. this.state.inFSharpPipelineDirectBody = false;
  7687. while (!this.eat(close)) {
  7688. if (first) {
  7689. first = false;
  7690. } else {
  7691. this.expect(types.comma);
  7692. if (this.match(close)) {
  7693. if (dynamicImport) {
  7694. this.raise(this.state.lastTokStart, "Trailing comma is disallowed inside import(...) arguments");
  7695. }
  7696. if (nodeForExtra) {
  7697. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  7698. }
  7699. this.next();
  7700. break;
  7701. }
  7702. }
  7703. if (this.match(types.parenL) && !innerParenStart) {
  7704. innerParenStart = this.state.start;
  7705. }
  7706. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  7707. start: 0
  7708. } : undefined, allowPlaceholder));
  7709. }
  7710. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  7711. this.unexpected();
  7712. }
  7713. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  7714. return elts;
  7715. }
  7716. shouldParseAsyncArrow() {
  7717. return this.match(types.arrow) && !this.canInsertSemicolon();
  7718. }
  7719. parseAsyncArrowFromCallExpression(node, call) {
  7720. var _call$extra;
  7721. this.expect(types.arrow);
  7722. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  7723. return node;
  7724. }
  7725. parseNoCallExpr() {
  7726. const startPos = this.state.start;
  7727. const startLoc = this.state.startLoc;
  7728. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  7729. }
  7730. parseExprAtom(refExpressionErrors) {
  7731. if (this.state.type === types.slash) this.readRegexp();
  7732. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  7733. let node;
  7734. switch (this.state.type) {
  7735. case types._super:
  7736. node = this.startNode();
  7737. this.next();
  7738. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  7739. this.raise(node.start, "super() is only valid inside a class constructor of a subclass. " + "Maybe a typo in the method name ('constructor') or not extending another class?");
  7740. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  7741. this.raise(node.start, "super is only allowed in object methods and classes");
  7742. }
  7743. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  7744. this.raise(node.start, "super can only be used with function calls (i.e. super()) or " + "in property accesses (i.e. super.prop or super[prop])");
  7745. }
  7746. return this.finishNode(node, "Super");
  7747. case types._import:
  7748. node = this.startNode();
  7749. this.next();
  7750. if (this.match(types.dot)) {
  7751. return this.parseImportMetaProperty(node);
  7752. }
  7753. if (!this.match(types.parenL)) {
  7754. this.raise(this.state.lastTokStart, "import can only be used in import() or import.meta");
  7755. }
  7756. return this.finishNode(node, "Import");
  7757. case types._this:
  7758. node = this.startNode();
  7759. this.next();
  7760. return this.finishNode(node, "ThisExpression");
  7761. case types.name:
  7762. {
  7763. node = this.startNode();
  7764. const containsEsc = this.state.containsEsc;
  7765. const id = this.parseIdentifier();
  7766. if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) {
  7767. const last = this.state.context.length - 1;
  7768. if (this.state.context[last] !== types$1.functionStatement) {
  7769. throw new Error("Internal error");
  7770. }
  7771. this.state.context[last] = types$1.functionExpression;
  7772. this.next();
  7773. return this.parseFunction(node, undefined, true);
  7774. } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) {
  7775. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7776. const oldYieldPos = this.state.yieldPos;
  7777. const oldAwaitPos = this.state.awaitPos;
  7778. this.state.maybeInArrowParameters = true;
  7779. this.state.yieldPos = -1;
  7780. this.state.awaitPos = -1;
  7781. const params = [this.parseIdentifier()];
  7782. this.expect(types.arrow);
  7783. this.checkYieldAwaitInDefaultParams();
  7784. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7785. this.state.yieldPos = oldYieldPos;
  7786. this.state.awaitPos = oldAwaitPos;
  7787. this.parseArrowExpression(node, params, true);
  7788. return node;
  7789. }
  7790. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  7791. this.next();
  7792. this.parseArrowExpression(node, [id], false);
  7793. return node;
  7794. }
  7795. return id;
  7796. }
  7797. case types._do:
  7798. {
  7799. this.expectPlugin("doExpressions");
  7800. const node = this.startNode();
  7801. this.next();
  7802. const oldLabels = this.state.labels;
  7803. this.state.labels = [];
  7804. node.body = this.parseBlock();
  7805. this.state.labels = oldLabels;
  7806. return this.finishNode(node, "DoExpression");
  7807. }
  7808. case types.regexp:
  7809. {
  7810. const value = this.state.value;
  7811. node = this.parseLiteral(value.value, "RegExpLiteral");
  7812. node.pattern = value.pattern;
  7813. node.flags = value.flags;
  7814. return node;
  7815. }
  7816. case types.num:
  7817. return this.parseLiteral(this.state.value, "NumericLiteral");
  7818. case types.bigint:
  7819. return this.parseLiteral(this.state.value, "BigIntLiteral");
  7820. case types.string:
  7821. return this.parseLiteral(this.state.value, "StringLiteral");
  7822. case types._null:
  7823. node = this.startNode();
  7824. this.next();
  7825. return this.finishNode(node, "NullLiteral");
  7826. case types._true:
  7827. case types._false:
  7828. return this.parseBooleanLiteral();
  7829. case types.parenL:
  7830. return this.parseParenAndDistinguishExpression(canBeArrow);
  7831. case types.bracketL:
  7832. {
  7833. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7834. this.state.inFSharpPipelineDirectBody = false;
  7835. node = this.startNode();
  7836. this.next();
  7837. node.elements = this.parseExprList(types.bracketR, true, refExpressionErrors, node);
  7838. if (!this.state.maybeInArrowParameters) {
  7839. this.toReferencedList(node.elements);
  7840. }
  7841. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  7842. return this.finishNode(node, "ArrayExpression");
  7843. }
  7844. case types.braceL:
  7845. {
  7846. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7847. this.state.inFSharpPipelineDirectBody = false;
  7848. const ret = this.parseObj(false, refExpressionErrors);
  7849. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  7850. return ret;
  7851. }
  7852. case types._function:
  7853. return this.parseFunctionExpression();
  7854. case types.at:
  7855. this.parseDecorators();
  7856. case types._class:
  7857. node = this.startNode();
  7858. this.takeDecorators(node);
  7859. return this.parseClass(node, false);
  7860. case types._new:
  7861. return this.parseNew();
  7862. case types.backQuote:
  7863. return this.parseTemplate(false);
  7864. case types.doubleColon:
  7865. {
  7866. node = this.startNode();
  7867. this.next();
  7868. node.object = null;
  7869. const callee = node.callee = this.parseNoCallExpr();
  7870. if (callee.type === "MemberExpression") {
  7871. return this.finishNode(node, "BindExpression");
  7872. } else {
  7873. throw this.raise(callee.start, "Binding should be performed on object property.");
  7874. }
  7875. }
  7876. case types.hash:
  7877. {
  7878. if (this.state.inPipeline) {
  7879. node = this.startNode();
  7880. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  7881. this.raise(node.start, "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.");
  7882. }
  7883. this.next();
  7884. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  7885. this.raise(node.start, `Topic reference was used in a lexical context without topic binding`);
  7886. }
  7887. this.registerTopicReference();
  7888. return this.finishNode(node, "PipelinePrimaryTopicReference");
  7889. }
  7890. }
  7891. default:
  7892. throw this.unexpected();
  7893. }
  7894. }
  7895. parseBooleanLiteral() {
  7896. const node = this.startNode();
  7897. node.value = this.match(types._true);
  7898. this.next();
  7899. return this.finishNode(node, "BooleanLiteral");
  7900. }
  7901. parseMaybePrivateName(isPrivateNameAllowed) {
  7902. const isPrivate = this.match(types.hash);
  7903. if (isPrivate) {
  7904. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  7905. if (!isPrivateNameAllowed) {
  7906. this.raise(this.state.pos, "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).");
  7907. }
  7908. const node = this.startNode();
  7909. this.next();
  7910. this.assertNoSpace("Unexpected space between # and identifier");
  7911. node.id = this.parseIdentifier(true);
  7912. return this.finishNode(node, "PrivateName");
  7913. } else {
  7914. return this.parseIdentifier(true);
  7915. }
  7916. }
  7917. parseFunctionExpression() {
  7918. const node = this.startNode();
  7919. let meta = this.startNode();
  7920. this.next();
  7921. meta = this.createIdentifier(meta, "function");
  7922. if (this.scope.inGenerator && this.eat(types.dot)) {
  7923. return this.parseMetaProperty(node, meta, "sent");
  7924. }
  7925. return this.parseFunction(node);
  7926. }
  7927. parseMetaProperty(node, meta, propertyName) {
  7928. node.meta = meta;
  7929. if (meta.name === "function" && propertyName === "sent") {
  7930. if (this.isContextual(propertyName)) {
  7931. this.expectPlugin("functionSent");
  7932. } else if (!this.hasPlugin("functionSent")) {
  7933. this.unexpected();
  7934. }
  7935. }
  7936. const containsEsc = this.state.containsEsc;
  7937. node.property = this.parseIdentifier(true);
  7938. if (node.property.name !== propertyName || containsEsc) {
  7939. this.raise(node.property.start, `The only valid meta property for ${meta.name} is ${meta.name}.${propertyName}`);
  7940. }
  7941. return this.finishNode(node, "MetaProperty");
  7942. }
  7943. parseImportMetaProperty(node) {
  7944. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  7945. this.expect(types.dot);
  7946. if (this.isContextual("meta")) {
  7947. this.expectPlugin("importMeta");
  7948. if (!this.inModule) {
  7949. this.raise(id.start, `import.meta may appear only with 'sourceType: "module"'`, {
  7950. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  7951. });
  7952. }
  7953. this.sawUnambiguousESM = true;
  7954. } else if (!this.hasPlugin("importMeta")) {
  7955. this.raise(id.start, `Dynamic imports require a parameter: import('a.js')`);
  7956. }
  7957. return this.parseMetaProperty(node, id, "meta");
  7958. }
  7959. parseLiteral(value, type, startPos, startLoc) {
  7960. startPos = startPos || this.state.start;
  7961. startLoc = startLoc || this.state.startLoc;
  7962. const node = this.startNodeAt(startPos, startLoc);
  7963. this.addExtra(node, "rawValue", value);
  7964. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  7965. node.value = value;
  7966. this.next();
  7967. return this.finishNode(node, type);
  7968. }
  7969. parseParenAndDistinguishExpression(canBeArrow) {
  7970. const startPos = this.state.start;
  7971. const startLoc = this.state.startLoc;
  7972. let val;
  7973. this.expect(types.parenL);
  7974. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7975. const oldYieldPos = this.state.yieldPos;
  7976. const oldAwaitPos = this.state.awaitPos;
  7977. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  7978. this.state.maybeInArrowParameters = true;
  7979. this.state.yieldPos = -1;
  7980. this.state.awaitPos = -1;
  7981. this.state.inFSharpPipelineDirectBody = false;
  7982. const innerStartPos = this.state.start;
  7983. const innerStartLoc = this.state.startLoc;
  7984. const exprList = [];
  7985. const refExpressionErrors = new ExpressionErrors();
  7986. const refNeedsArrowPos = {
  7987. start: 0
  7988. };
  7989. let first = true;
  7990. let spreadStart;
  7991. let optionalCommaStart;
  7992. while (!this.match(types.parenR)) {
  7993. if (first) {
  7994. first = false;
  7995. } else {
  7996. this.expect(types.comma, refNeedsArrowPos.start || null);
  7997. if (this.match(types.parenR)) {
  7998. optionalCommaStart = this.state.start;
  7999. break;
  8000. }
  8001. }
  8002. if (this.match(types.ellipsis)) {
  8003. const spreadNodeStartPos = this.state.start;
  8004. const spreadNodeStartLoc = this.state.startLoc;
  8005. spreadStart = this.state.start;
  8006. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  8007. this.checkCommaAfterRest(41);
  8008. break;
  8009. } else {
  8010. exprList.push(this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  8011. }
  8012. }
  8013. const innerEndPos = this.state.start;
  8014. const innerEndLoc = this.state.startLoc;
  8015. this.expect(types.parenR);
  8016. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8017. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8018. let arrowNode = this.startNodeAt(startPos, startLoc);
  8019. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  8020. this.checkYieldAwaitInDefaultParams();
  8021. this.state.yieldPos = oldYieldPos;
  8022. this.state.awaitPos = oldAwaitPos;
  8023. for (let _i = 0; _i < exprList.length; _i++) {
  8024. const param = exprList[_i];
  8025. if (param.extra && param.extra.parenthesized) {
  8026. this.unexpected(param.extra.parenStart);
  8027. }
  8028. }
  8029. this.parseArrowExpression(arrowNode, exprList, false);
  8030. return arrowNode;
  8031. }
  8032. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  8033. if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
  8034. if (!exprList.length) {
  8035. this.unexpected(this.state.lastTokStart);
  8036. }
  8037. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8038. if (spreadStart) this.unexpected(spreadStart);
  8039. this.checkExpressionErrors(refExpressionErrors, true);
  8040. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8041. this.toReferencedListDeep(exprList, true);
  8042. if (exprList.length > 1) {
  8043. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8044. val.expressions = exprList;
  8045. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8046. } else {
  8047. val = exprList[0];
  8048. }
  8049. if (!this.options.createParenthesizedExpressions) {
  8050. this.addExtra(val, "parenthesized", true);
  8051. this.addExtra(val, "parenStart", startPos);
  8052. return val;
  8053. }
  8054. const parenExpression = this.startNodeAt(startPos, startLoc);
  8055. parenExpression.expression = val;
  8056. this.finishNode(parenExpression, "ParenthesizedExpression");
  8057. return parenExpression;
  8058. }
  8059. shouldParseArrow() {
  8060. return !this.canInsertSemicolon();
  8061. }
  8062. parseArrow(node) {
  8063. if (this.eat(types.arrow)) {
  8064. return node;
  8065. }
  8066. }
  8067. parseParenItem(node, startPos, startLoc) {
  8068. return node;
  8069. }
  8070. parseNew() {
  8071. const node = this.startNode();
  8072. let meta = this.startNode();
  8073. this.next();
  8074. meta = this.createIdentifier(meta, "new");
  8075. if (this.eat(types.dot)) {
  8076. const metaProp = this.parseMetaProperty(node, meta, "target");
  8077. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  8078. let error = "new.target can only be used in functions";
  8079. if (this.hasPlugin("classProperties")) {
  8080. error += " or class properties";
  8081. }
  8082. this.raise(metaProp.start, error);
  8083. }
  8084. return metaProp;
  8085. }
  8086. node.callee = this.parseNoCallExpr();
  8087. if (node.callee.type === "Import") {
  8088. this.raise(node.callee.start, "Cannot use new with import(...)");
  8089. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  8090. this.raise(this.state.lastTokEnd, "constructors in/after an Optional Chain are not allowed");
  8091. } else if (this.eat(types.questionDot)) {
  8092. this.raise(this.state.start, "constructors in/after an Optional Chain are not allowed");
  8093. }
  8094. this.parseNewArguments(node);
  8095. return this.finishNode(node, "NewExpression");
  8096. }
  8097. parseNewArguments(node) {
  8098. if (this.eat(types.parenL)) {
  8099. const args = this.parseExprList(types.parenR);
  8100. this.toReferencedList(args);
  8101. node.arguments = args;
  8102. } else {
  8103. node.arguments = [];
  8104. }
  8105. }
  8106. parseTemplateElement(isTagged) {
  8107. const elem = this.startNode();
  8108. if (this.state.value === null) {
  8109. if (!isTagged) {
  8110. this.raise(this.state.start + 1, "Invalid escape sequence in template");
  8111. }
  8112. }
  8113. elem.value = {
  8114. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8115. cooked: this.state.value
  8116. };
  8117. this.next();
  8118. elem.tail = this.match(types.backQuote);
  8119. return this.finishNode(elem, "TemplateElement");
  8120. }
  8121. parseTemplate(isTagged) {
  8122. const node = this.startNode();
  8123. this.next();
  8124. node.expressions = [];
  8125. let curElt = this.parseTemplateElement(isTagged);
  8126. node.quasis = [curElt];
  8127. while (!curElt.tail) {
  8128. this.expect(types.dollarBraceL);
  8129. node.expressions.push(this.parseExpression());
  8130. this.expect(types.braceR);
  8131. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8132. }
  8133. this.next();
  8134. return this.finishNode(node, "TemplateLiteral");
  8135. }
  8136. parseObj(isPattern, refExpressionErrors) {
  8137. const propHash = Object.create(null);
  8138. let first = true;
  8139. const node = this.startNode();
  8140. node.properties = [];
  8141. this.next();
  8142. while (!this.eat(types.braceR)) {
  8143. if (first) {
  8144. first = false;
  8145. } else {
  8146. this.expect(types.comma);
  8147. if (this.match(types.braceR)) {
  8148. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8149. this.next();
  8150. break;
  8151. }
  8152. }
  8153. const prop = this.parseObjectMember(isPattern, refExpressionErrors);
  8154. if (!isPattern) {
  8155. this.checkDuplicatedProto(prop, propHash, refExpressionErrors);
  8156. }
  8157. if (prop.shorthand) {
  8158. this.addExtra(prop, "shorthand", true);
  8159. }
  8160. node.properties.push(prop);
  8161. }
  8162. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
  8163. }
  8164. isAsyncProp(prop) {
  8165. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.match(types.name) || this.match(types.num) || this.match(types.string) || this.match(types.bracketL) || this.state.type.keyword || this.match(types.star)) && !this.hasPrecedingLineBreak();
  8166. }
  8167. parseObjectMember(isPattern, refExpressionErrors) {
  8168. let decorators = [];
  8169. if (this.match(types.at)) {
  8170. if (this.hasPlugin("decorators")) {
  8171. this.raise(this.state.start, "Stage 2 decorators disallow object literal property decorators");
  8172. }
  8173. while (this.match(types.at)) {
  8174. decorators.push(this.parseDecorator());
  8175. }
  8176. }
  8177. const prop = this.startNode();
  8178. let isGenerator = false;
  8179. let isAsync = false;
  8180. let startPos;
  8181. let startLoc;
  8182. if (this.match(types.ellipsis)) {
  8183. if (decorators.length) this.unexpected();
  8184. if (isPattern) {
  8185. this.next();
  8186. prop.argument = this.parseIdentifier();
  8187. this.checkCommaAfterRest(125);
  8188. return this.finishNode(prop, "RestElement");
  8189. }
  8190. return this.parseSpread();
  8191. }
  8192. if (decorators.length) {
  8193. prop.decorators = decorators;
  8194. decorators = [];
  8195. }
  8196. prop.method = false;
  8197. if (isPattern || refExpressionErrors) {
  8198. startPos = this.state.start;
  8199. startLoc = this.state.startLoc;
  8200. }
  8201. if (!isPattern) {
  8202. isGenerator = this.eat(types.star);
  8203. }
  8204. const containsEsc = this.state.containsEsc;
  8205. this.parsePropertyName(prop, false);
  8206. if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) {
  8207. isAsync = true;
  8208. isGenerator = this.eat(types.star);
  8209. this.parsePropertyName(prop, false);
  8210. } else {
  8211. isAsync = false;
  8212. }
  8213. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  8214. return prop;
  8215. }
  8216. isGetterOrSetterMethod(prop, isPattern) {
  8217. return !isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.match(types.string) || this.match(types.num) || this.match(types.bracketL) || this.match(types.name) || !!this.state.type.keyword);
  8218. }
  8219. getGetterSetterExpectedParamCount(method) {
  8220. return method.kind === "get" ? 0 : 1;
  8221. }
  8222. checkGetterSetterParams(method) {
  8223. const paramCount = this.getGetterSetterExpectedParamCount(method);
  8224. const start = method.start;
  8225. if (method.params.length !== paramCount) {
  8226. if (method.kind === "get") {
  8227. this.raise(start, "getter must not have any formal parameters");
  8228. } else {
  8229. this.raise(start, "setter must have exactly one formal parameter");
  8230. }
  8231. }
  8232. if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") {
  8233. this.raise(start, "setter function argument must not be a rest parameter");
  8234. }
  8235. }
  8236. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  8237. if (isAsync || isGenerator || this.match(types.parenL)) {
  8238. if (isPattern) this.unexpected();
  8239. prop.kind = "method";
  8240. prop.method = true;
  8241. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  8242. }
  8243. if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) {
  8244. if (isGenerator || isAsync) this.unexpected();
  8245. prop.kind = prop.key.name;
  8246. this.parsePropertyName(prop, false);
  8247. this.parseMethod(prop, false, false, false, false, "ObjectMethod");
  8248. this.checkGetterSetterParams(prop);
  8249. return prop;
  8250. }
  8251. }
  8252. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  8253. prop.shorthand = false;
  8254. if (this.eat(types.colon)) {
  8255. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refExpressionErrors);
  8256. return this.finishNode(prop, "ObjectProperty");
  8257. }
  8258. if (!prop.computed && prop.key.type === "Identifier") {
  8259. this.checkReservedWord(prop.key.name, prop.key.start, true, true);
  8260. if (isPattern) {
  8261. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8262. } else if (this.match(types.eq) && refExpressionErrors) {
  8263. if (refExpressionErrors.shorthandAssign === -1) {
  8264. refExpressionErrors.shorthandAssign = this.state.start;
  8265. }
  8266. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8267. } else {
  8268. prop.value = prop.key.__clone();
  8269. }
  8270. prop.shorthand = true;
  8271. return this.finishNode(prop, "ObjectProperty");
  8272. }
  8273. }
  8274. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  8275. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  8276. if (!node) this.unexpected();
  8277. return node;
  8278. }
  8279. parsePropertyName(prop, isPrivateNameAllowed) {
  8280. if (this.eat(types.bracketL)) {
  8281. prop.computed = true;
  8282. prop.key = this.parseMaybeAssign();
  8283. this.expect(types.bracketR);
  8284. } else {
  8285. const oldInPropertyName = this.state.inPropertyName;
  8286. this.state.inPropertyName = true;
  8287. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  8288. if (prop.key.type !== "PrivateName") {
  8289. prop.computed = false;
  8290. }
  8291. this.state.inPropertyName = oldInPropertyName;
  8292. }
  8293. return prop.key;
  8294. }
  8295. initFunction(node, isAsync) {
  8296. node.id = null;
  8297. node.generator = false;
  8298. node.async = !!isAsync;
  8299. }
  8300. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  8301. const oldYieldPos = this.state.yieldPos;
  8302. const oldAwaitPos = this.state.awaitPos;
  8303. this.state.yieldPos = -1;
  8304. this.state.awaitPos = -1;
  8305. this.initFunction(node, isAsync);
  8306. node.generator = !!isGenerator;
  8307. const allowModifiers = isConstructor;
  8308. this.scope.enter(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  8309. this.parseFunctionParams(node, allowModifiers);
  8310. this.parseFunctionBodyAndFinish(node, type, true);
  8311. this.scope.exit();
  8312. this.state.yieldPos = oldYieldPos;
  8313. this.state.awaitPos = oldAwaitPos;
  8314. return node;
  8315. }
  8316. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  8317. this.scope.enter(functionFlags(isAsync, false) | SCOPE_ARROW);
  8318. this.initFunction(node, isAsync);
  8319. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8320. const oldYieldPos = this.state.yieldPos;
  8321. const oldAwaitPos = this.state.awaitPos;
  8322. if (params) {
  8323. this.state.maybeInArrowParameters = true;
  8324. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  8325. }
  8326. this.state.maybeInArrowParameters = false;
  8327. this.state.yieldPos = -1;
  8328. this.state.awaitPos = -1;
  8329. this.parseFunctionBody(node, true);
  8330. this.scope.exit();
  8331. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8332. this.state.yieldPos = oldYieldPos;
  8333. this.state.awaitPos = oldAwaitPos;
  8334. return this.finishNode(node, "ArrowFunctionExpression");
  8335. }
  8336. setArrowFunctionParameters(node, params, trailingCommaPos) {
  8337. node.params = this.toAssignableList(params, trailingCommaPos);
  8338. }
  8339. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8340. this.parseFunctionBody(node, false, isMethod);
  8341. this.finishNode(node, type);
  8342. }
  8343. parseFunctionBody(node, allowExpression, isMethod = false) {
  8344. const isExpression = allowExpression && !this.match(types.braceL);
  8345. const oldStrict = this.state.strict;
  8346. let useStrict = false;
  8347. const oldInParameters = this.state.inParameters;
  8348. this.state.inParameters = false;
  8349. if (isExpression) {
  8350. node.body = this.parseMaybeAssign();
  8351. this.checkParams(node, false, allowExpression, false);
  8352. } else {
  8353. const nonSimple = !this.isSimpleParamList(node.params);
  8354. if (!oldStrict || nonSimple) {
  8355. useStrict = this.strictDirective(this.state.end);
  8356. if (useStrict && nonSimple) {
  8357. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  8358. this.raise(errorPos, "Illegal 'use strict' directive in function with non-simple parameter list");
  8359. }
  8360. }
  8361. const oldLabels = this.state.labels;
  8362. this.state.labels = [];
  8363. if (useStrict) this.state.strict = true;
  8364. this.checkParams(node, !oldStrict && !useStrict && !allowExpression && !isMethod && !nonSimple, allowExpression, !oldStrict && useStrict);
  8365. node.body = this.parseBlock(true, false);
  8366. this.state.labels = oldLabels;
  8367. }
  8368. this.state.inParameters = oldInParameters;
  8369. if (this.state.strict && node.id) {
  8370. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, !oldStrict && useStrict);
  8371. }
  8372. this.state.strict = oldStrict;
  8373. }
  8374. isSimpleParamList(params) {
  8375. for (let i = 0, len = params.length; i < len; i++) {
  8376. if (params[i].type !== "Identifier") return false;
  8377. }
  8378. return true;
  8379. }
  8380. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  8381. const nameHash = Object.create(null);
  8382. for (let i = 0; i < node.params.length; i++) {
  8383. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged);
  8384. }
  8385. }
  8386. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  8387. const elts = [];
  8388. let first = true;
  8389. while (!this.eat(close)) {
  8390. if (first) {
  8391. first = false;
  8392. } else {
  8393. this.expect(types.comma);
  8394. if (this.match(close)) {
  8395. if (nodeForExtra) {
  8396. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8397. }
  8398. this.next();
  8399. break;
  8400. }
  8401. }
  8402. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  8403. }
  8404. return elts;
  8405. }
  8406. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  8407. let elt;
  8408. if (allowEmpty && this.match(types.comma)) {
  8409. elt = null;
  8410. } else if (this.match(types.ellipsis)) {
  8411. const spreadNodeStartPos = this.state.start;
  8412. const spreadNodeStartLoc = this.state.startLoc;
  8413. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  8414. } else if (this.match(types.question)) {
  8415. this.expectPlugin("partialApplication");
  8416. if (!allowPlaceholder) {
  8417. this.raise(this.state.start, "Unexpected argument placeholder");
  8418. }
  8419. const node = this.startNode();
  8420. this.next();
  8421. elt = this.finishNode(node, "ArgumentPlaceholder");
  8422. } else {
  8423. elt = this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  8424. }
  8425. return elt;
  8426. }
  8427. parseIdentifier(liberal) {
  8428. const node = this.startNode();
  8429. const name = this.parseIdentifierName(node.start, liberal);
  8430. return this.createIdentifier(node, name);
  8431. }
  8432. createIdentifier(node, name) {
  8433. node.name = name;
  8434. node.loc.identifierName = name;
  8435. return this.finishNode(node, "Identifier");
  8436. }
  8437. parseIdentifierName(pos, liberal) {
  8438. let name;
  8439. if (this.match(types.name)) {
  8440. name = this.state.value;
  8441. } else if (this.state.type.keyword) {
  8442. name = this.state.type.keyword;
  8443. if ((name === "class" || name === "function") && (this.state.lastTokEnd !== this.state.lastTokStart + 1 || this.input.charCodeAt(this.state.lastTokStart) !== 46)) {
  8444. this.state.context.pop();
  8445. }
  8446. } else {
  8447. throw this.unexpected();
  8448. }
  8449. if (liberal) {
  8450. this.state.type = types.name;
  8451. } else {
  8452. this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false);
  8453. }
  8454. this.next();
  8455. return name;
  8456. }
  8457. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  8458. if (this.scope.inGenerator && word === "yield") {
  8459. this.raise(startLoc, "Can not use 'yield' as identifier inside a generator");
  8460. return;
  8461. }
  8462. if (word === "await") {
  8463. if (this.scope.inAsync) {
  8464. this.raise(startLoc, "Can not use 'await' as identifier inside an async function");
  8465. return;
  8466. }
  8467. if (this.state.awaitPos === -1 && (this.state.maybeInArrowParameters || this.isAwaitAllowed())) {
  8468. this.state.awaitPos = this.state.start;
  8469. }
  8470. }
  8471. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  8472. this.raise(startLoc, "'arguments' is not allowed in class field initializer");
  8473. return;
  8474. }
  8475. if (checkKeywords && isKeyword(word)) {
  8476. this.raise(startLoc, `Unexpected keyword '${word}'`);
  8477. return;
  8478. }
  8479. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  8480. if (reservedTest(word, this.inModule)) {
  8481. if (!this.scope.inAsync && word === "await") {
  8482. this.raise(startLoc, "Can not use keyword 'await' outside an async function");
  8483. } else {
  8484. this.raise(startLoc, `Unexpected reserved word '${word}'`);
  8485. }
  8486. }
  8487. }
  8488. isAwaitAllowed() {
  8489. if (this.scope.inFunction) return this.scope.inAsync;
  8490. if (this.options.allowAwaitOutsideFunction) return true;
  8491. if (this.hasPlugin("topLevelAwait")) {
  8492. return this.inModule && this.scope.inAsync;
  8493. }
  8494. return false;
  8495. }
  8496. parseAwait() {
  8497. const node = this.startNode();
  8498. this.next();
  8499. if (this.state.inParameters) {
  8500. this.raise(node.start, "await is not allowed in async function parameters");
  8501. } else if (this.state.awaitPos === -1) {
  8502. this.state.awaitPos = node.start;
  8503. }
  8504. if (this.eat(types.star)) {
  8505. this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead.");
  8506. }
  8507. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  8508. 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)) {
  8509. this.ambiguousScriptDifferentAst = true;
  8510. } else {
  8511. this.sawUnambiguousESM = true;
  8512. }
  8513. }
  8514. if (!this.state.soloAwait) {
  8515. node.argument = this.parseMaybeUnary();
  8516. }
  8517. return this.finishNode(node, "AwaitExpression");
  8518. }
  8519. parseYield(noIn) {
  8520. const node = this.startNode();
  8521. if (this.state.inParameters) {
  8522. this.raise(node.start, "yield is not allowed in generator parameters");
  8523. } else if (this.state.yieldPos === -1) {
  8524. this.state.yieldPos = node.start;
  8525. }
  8526. this.next();
  8527. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  8528. node.delegate = false;
  8529. node.argument = null;
  8530. } else {
  8531. node.delegate = this.eat(types.star);
  8532. node.argument = this.parseMaybeAssign(noIn);
  8533. }
  8534. return this.finishNode(node, "YieldExpression");
  8535. }
  8536. checkPipelineAtInfixOperator(left, leftStartPos) {
  8537. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  8538. if (left.type === "SequenceExpression") {
  8539. this.raise(leftStartPos, `Pipeline head should not be a comma-separated sequence expression`);
  8540. }
  8541. }
  8542. }
  8543. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  8544. const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
  8545. this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos);
  8546. return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc);
  8547. }
  8548. checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) {
  8549. if (this.match(types.arrow)) {
  8550. throw this.raise(this.state.start, `Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized`);
  8551. } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") {
  8552. this.raise(startPos, `Pipeline body may not be a comma-separated sequence expression`);
  8553. }
  8554. }
  8555. parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) {
  8556. const bodyNode = this.startNodeAt(startPos, startLoc);
  8557. switch (pipelineStyle) {
  8558. case "PipelineBareFunction":
  8559. bodyNode.callee = childExpression;
  8560. break;
  8561. case "PipelineBareConstructor":
  8562. bodyNode.callee = childExpression.callee;
  8563. break;
  8564. case "PipelineBareAwaitedFunction":
  8565. bodyNode.callee = childExpression.argument;
  8566. break;
  8567. case "PipelineTopicExpression":
  8568. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  8569. this.raise(startPos, `Pipeline is in topic style but does not use topic reference`);
  8570. }
  8571. bodyNode.expression = childExpression;
  8572. break;
  8573. default:
  8574. throw new Error(`Internal @babel/parser error: Unknown pipeline style (${pipelineStyle})`);
  8575. }
  8576. return this.finishNode(bodyNode, pipelineStyle);
  8577. }
  8578. checkSmartPipelineBodyStyle(expression) {
  8579. switch (expression.type) {
  8580. default:
  8581. return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression";
  8582. }
  8583. }
  8584. isSimpleReference(expression) {
  8585. switch (expression.type) {
  8586. case "MemberExpression":
  8587. return !expression.computed && this.isSimpleReference(expression.object);
  8588. case "Identifier":
  8589. return true;
  8590. default:
  8591. return false;
  8592. }
  8593. }
  8594. withTopicPermittingContext(callback) {
  8595. const outerContextTopicState = this.state.topicContext;
  8596. this.state.topicContext = {
  8597. maxNumOfResolvableTopics: 1,
  8598. maxTopicIndex: null
  8599. };
  8600. try {
  8601. return callback();
  8602. } finally {
  8603. this.state.topicContext = outerContextTopicState;
  8604. }
  8605. }
  8606. withTopicForbiddingContext(callback) {
  8607. const outerContextTopicState = this.state.topicContext;
  8608. this.state.topicContext = {
  8609. maxNumOfResolvableTopics: 0,
  8610. maxTopicIndex: null
  8611. };
  8612. try {
  8613. return callback();
  8614. } finally {
  8615. this.state.topicContext = outerContextTopicState;
  8616. }
  8617. }
  8618. withSoloAwaitPermittingContext(callback) {
  8619. const outerContextSoloAwaitState = this.state.soloAwait;
  8620. this.state.soloAwait = true;
  8621. try {
  8622. return callback();
  8623. } finally {
  8624. this.state.soloAwait = outerContextSoloAwaitState;
  8625. }
  8626. }
  8627. registerTopicReference() {
  8628. this.state.topicContext.maxTopicIndex = 0;
  8629. }
  8630. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  8631. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  8632. }
  8633. topicReferenceWasUsedInCurrentTopicContext() {
  8634. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  8635. }
  8636. parseFSharpPipelineBody(prec, noIn) {
  8637. const startPos = this.state.start;
  8638. const startLoc = this.state.startLoc;
  8639. this.state.potentialArrowAt = this.state.start;
  8640. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8641. this.state.inFSharpPipelineDirectBody = true;
  8642. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
  8643. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8644. return ret;
  8645. }
  8646. }
  8647. const loopLabel = {
  8648. kind: "loop"
  8649. },
  8650. switchLabel = {
  8651. kind: "switch"
  8652. };
  8653. const FUNC_NO_FLAGS = 0b000,
  8654. FUNC_STATEMENT = 0b001,
  8655. FUNC_HANGING_STATEMENT = 0b010,
  8656. FUNC_NULLABLE_ID = 0b100;
  8657. class StatementParser extends ExpressionParser {
  8658. parseTopLevel(file, program) {
  8659. program.sourceType = this.options.sourceType;
  8660. program.interpreter = this.parseInterpreterDirective();
  8661. this.parseBlockBody(program, true, true, types.eof);
  8662. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  8663. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  8664. const [name] = _Array$from[_i];
  8665. const pos = this.scope.undefinedExports.get(name);
  8666. this.raise(pos, `Export '${name}' is not defined`);
  8667. }
  8668. }
  8669. file.program = this.finishNode(program, "Program");
  8670. file.comments = this.state.comments;
  8671. if (this.options.tokens) file.tokens = this.tokens;
  8672. return this.finishNode(file, "File");
  8673. }
  8674. stmtToDirective(stmt) {
  8675. const expr = stmt.expression;
  8676. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  8677. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  8678. const raw = this.input.slice(expr.start, expr.end);
  8679. const val = directiveLiteral.value = raw.slice(1, -1);
  8680. this.addExtra(directiveLiteral, "raw", raw);
  8681. this.addExtra(directiveLiteral, "rawValue", val);
  8682. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  8683. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  8684. }
  8685. parseInterpreterDirective() {
  8686. if (!this.match(types.interpreterDirective)) {
  8687. return null;
  8688. }
  8689. const node = this.startNode();
  8690. node.value = this.state.value;
  8691. this.next();
  8692. return this.finishNode(node, "InterpreterDirective");
  8693. }
  8694. isLet(context) {
  8695. if (!this.isContextual("let")) {
  8696. return false;
  8697. }
  8698. const next = this.nextTokenStart();
  8699. const nextCh = this.input.charCodeAt(next);
  8700. if (nextCh === 91) return true;
  8701. if (context) return false;
  8702. if (nextCh === 123) return true;
  8703. if (isIdentifierStart(nextCh)) {
  8704. let pos = next + 1;
  8705. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  8706. ++pos;
  8707. }
  8708. const ident = this.input.slice(next, pos);
  8709. if (!keywordRelationalOperator.test(ident)) return true;
  8710. }
  8711. return false;
  8712. }
  8713. parseStatement(context, topLevel) {
  8714. if (this.match(types.at)) {
  8715. this.parseDecorators(true);
  8716. }
  8717. return this.parseStatementContent(context, topLevel);
  8718. }
  8719. parseStatementContent(context, topLevel) {
  8720. let starttype = this.state.type;
  8721. const node = this.startNode();
  8722. let kind;
  8723. if (this.isLet(context)) {
  8724. starttype = types._var;
  8725. kind = "let";
  8726. }
  8727. switch (starttype) {
  8728. case types._break:
  8729. case types._continue:
  8730. return this.parseBreakContinueStatement(node, starttype.keyword);
  8731. case types._debugger:
  8732. return this.parseDebuggerStatement(node);
  8733. case types._do:
  8734. return this.parseDoStatement(node);
  8735. case types._for:
  8736. return this.parseForStatement(node);
  8737. case types._function:
  8738. if (this.lookaheadCharCode() === 46) break;
  8739. if (context) {
  8740. if (this.state.strict) {
  8741. this.raise(this.state.start, "In strict mode code, functions can only be declared at top level or inside a block");
  8742. } else if (context !== "if" && context !== "label") {
  8743. this.raise(this.state.start, "In non-strict mode code, functions can only be declared at top level, " + "inside a block, or as the body of an if statement");
  8744. }
  8745. }
  8746. return this.parseFunctionStatement(node, false, !context);
  8747. case types._class:
  8748. if (context) this.unexpected();
  8749. return this.parseClass(node, true);
  8750. case types._if:
  8751. return this.parseIfStatement(node);
  8752. case types._return:
  8753. return this.parseReturnStatement(node);
  8754. case types._switch:
  8755. return this.parseSwitchStatement(node);
  8756. case types._throw:
  8757. return this.parseThrowStatement(node);
  8758. case types._try:
  8759. return this.parseTryStatement(node);
  8760. case types._const:
  8761. case types._var:
  8762. kind = kind || this.state.value;
  8763. if (context && kind !== "var") {
  8764. this.raise(this.state.start, "Lexical declaration cannot appear in a single-statement context");
  8765. }
  8766. return this.parseVarStatement(node, kind);
  8767. case types._while:
  8768. return this.parseWhileStatement(node);
  8769. case types._with:
  8770. return this.parseWithStatement(node);
  8771. case types.braceL:
  8772. return this.parseBlock();
  8773. case types.semi:
  8774. return this.parseEmptyStatement(node);
  8775. case types._export:
  8776. case types._import:
  8777. {
  8778. const nextTokenCharCode = this.lookaheadCharCode();
  8779. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  8780. break;
  8781. }
  8782. if (!this.options.allowImportExportEverywhere && !topLevel) {
  8783. this.raise(this.state.start, "'import' and 'export' may only appear at the top level");
  8784. }
  8785. this.next();
  8786. let result;
  8787. if (starttype === types._import) {
  8788. result = this.parseImport(node);
  8789. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  8790. this.sawUnambiguousESM = true;
  8791. }
  8792. } else {
  8793. result = this.parseExport(node);
  8794. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  8795. this.sawUnambiguousESM = true;
  8796. }
  8797. }
  8798. this.assertModuleNodeAllowed(node);
  8799. return result;
  8800. }
  8801. default:
  8802. {
  8803. if (this.isAsyncFunction()) {
  8804. if (context) {
  8805. this.raise(this.state.start, "Async functions can only be declared at the top level or inside a block");
  8806. }
  8807. this.next();
  8808. return this.parseFunctionStatement(node, true, !context);
  8809. }
  8810. }
  8811. }
  8812. const maybeName = this.state.value;
  8813. const expr = this.parseExpression();
  8814. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  8815. return this.parseLabeledStatement(node, maybeName, expr, context);
  8816. } else {
  8817. return this.parseExpressionStatement(node, expr);
  8818. }
  8819. }
  8820. assertModuleNodeAllowed(node) {
  8821. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  8822. this.raise(node.start, `'import' and 'export' may appear only with 'sourceType: "module"'`, {
  8823. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8824. });
  8825. }
  8826. }
  8827. takeDecorators(node) {
  8828. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  8829. if (decorators.length) {
  8830. node.decorators = decorators;
  8831. this.resetStartLocationFromNode(node, decorators[0]);
  8832. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  8833. }
  8834. }
  8835. canHaveLeadingDecorator() {
  8836. return this.match(types._class);
  8837. }
  8838. parseDecorators(allowExport) {
  8839. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  8840. while (this.match(types.at)) {
  8841. const decorator = this.parseDecorator();
  8842. currentContextDecorators.push(decorator);
  8843. }
  8844. if (this.match(types._export)) {
  8845. if (!allowExport) {
  8846. this.unexpected();
  8847. }
  8848. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  8849. this.raise(this.state.start, "Using the export keyword between a decorator and a class is not allowed. " + "Please use `export @dec class` instead.");
  8850. }
  8851. } else if (!this.canHaveLeadingDecorator()) {
  8852. throw this.raise(this.state.start, "Leading decorators must be attached to a class declaration");
  8853. }
  8854. }
  8855. parseDecorator() {
  8856. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  8857. const node = this.startNode();
  8858. this.next();
  8859. if (this.hasPlugin("decorators")) {
  8860. this.state.decoratorStack.push([]);
  8861. const startPos = this.state.start;
  8862. const startLoc = this.state.startLoc;
  8863. let expr;
  8864. if (this.eat(types.parenL)) {
  8865. expr = this.parseExpression();
  8866. this.expect(types.parenR);
  8867. } else {
  8868. expr = this.parseIdentifier(false);
  8869. while (this.eat(types.dot)) {
  8870. const node = this.startNodeAt(startPos, startLoc);
  8871. node.object = expr;
  8872. node.property = this.parseIdentifier(true);
  8873. node.computed = false;
  8874. expr = this.finishNode(node, "MemberExpression");
  8875. }
  8876. }
  8877. node.expression = this.parseMaybeDecoratorArguments(expr);
  8878. this.state.decoratorStack.pop();
  8879. } else {
  8880. node.expression = this.parseExprSubscripts();
  8881. }
  8882. return this.finishNode(node, "Decorator");
  8883. }
  8884. parseMaybeDecoratorArguments(expr) {
  8885. if (this.eat(types.parenL)) {
  8886. const node = this.startNodeAtNode(expr);
  8887. node.callee = expr;
  8888. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8889. this.toReferencedList(node.arguments);
  8890. return this.finishNode(node, "CallExpression");
  8891. }
  8892. return expr;
  8893. }
  8894. parseBreakContinueStatement(node, keyword) {
  8895. const isBreak = keyword === "break";
  8896. this.next();
  8897. if (this.isLineTerminator()) {
  8898. node.label = null;
  8899. } else {
  8900. node.label = this.parseIdentifier();
  8901. this.semicolon();
  8902. }
  8903. this.verifyBreakContinue(node, keyword);
  8904. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  8905. }
  8906. verifyBreakContinue(node, keyword) {
  8907. const isBreak = keyword === "break";
  8908. let i;
  8909. for (i = 0; i < this.state.labels.length; ++i) {
  8910. const lab = this.state.labels[i];
  8911. if (node.label == null || lab.name === node.label.name) {
  8912. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  8913. if (node.label && isBreak) break;
  8914. }
  8915. }
  8916. if (i === this.state.labels.length) {
  8917. this.raise(node.start, "Unsyntactic " + keyword);
  8918. }
  8919. }
  8920. parseDebuggerStatement(node) {
  8921. this.next();
  8922. this.semicolon();
  8923. return this.finishNode(node, "DebuggerStatement");
  8924. }
  8925. parseHeaderExpression() {
  8926. this.expect(types.parenL);
  8927. const val = this.parseExpression();
  8928. this.expect(types.parenR);
  8929. return val;
  8930. }
  8931. parseDoStatement(node) {
  8932. this.next();
  8933. this.state.labels.push(loopLabel);
  8934. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  8935. this.state.labels.pop();
  8936. this.expect(types._while);
  8937. node.test = this.parseHeaderExpression();
  8938. this.eat(types.semi);
  8939. return this.finishNode(node, "DoWhileStatement");
  8940. }
  8941. parseForStatement(node) {
  8942. this.next();
  8943. this.state.labels.push(loopLabel);
  8944. let awaitAt = -1;
  8945. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  8946. awaitAt = this.state.lastTokStart;
  8947. }
  8948. this.scope.enter(SCOPE_OTHER);
  8949. this.expect(types.parenL);
  8950. if (this.match(types.semi)) {
  8951. if (awaitAt > -1) {
  8952. this.unexpected(awaitAt);
  8953. }
  8954. return this.parseFor(node, null);
  8955. }
  8956. const isLet = this.isLet();
  8957. if (this.match(types._var) || this.match(types._const) || isLet) {
  8958. const init = this.startNode();
  8959. const kind = isLet ? "let" : this.state.value;
  8960. this.next();
  8961. this.parseVar(init, true, kind);
  8962. this.finishNode(init, "VariableDeclaration");
  8963. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  8964. return this.parseForIn(node, init, awaitAt);
  8965. }
  8966. if (awaitAt > -1) {
  8967. this.unexpected(awaitAt);
  8968. }
  8969. return this.parseFor(node, init);
  8970. }
  8971. const refExpressionErrors = new ExpressionErrors();
  8972. const init = this.parseExpression(true, refExpressionErrors);
  8973. if (this.match(types._in) || this.isContextual("of")) {
  8974. this.toAssignable(init);
  8975. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  8976. this.checkLVal(init, undefined, undefined, description);
  8977. return this.parseForIn(node, init, awaitAt);
  8978. } else {
  8979. this.checkExpressionErrors(refExpressionErrors, true);
  8980. }
  8981. if (awaitAt > -1) {
  8982. this.unexpected(awaitAt);
  8983. }
  8984. return this.parseFor(node, init);
  8985. }
  8986. parseFunctionStatement(node, isAsync, declarationPosition) {
  8987. this.next();
  8988. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  8989. }
  8990. parseIfStatement(node) {
  8991. this.next();
  8992. node.test = this.parseHeaderExpression();
  8993. node.consequent = this.parseStatement("if");
  8994. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  8995. return this.finishNode(node, "IfStatement");
  8996. }
  8997. parseReturnStatement(node) {
  8998. if (!this.scope.inFunction && !this.options.allowReturnOutsideFunction) {
  8999. this.raise(this.state.start, "'return' outside of function");
  9000. }
  9001. this.next();
  9002. if (this.isLineTerminator()) {
  9003. node.argument = null;
  9004. } else {
  9005. node.argument = this.parseExpression();
  9006. this.semicolon();
  9007. }
  9008. return this.finishNode(node, "ReturnStatement");
  9009. }
  9010. parseSwitchStatement(node) {
  9011. this.next();
  9012. node.discriminant = this.parseHeaderExpression();
  9013. const cases = node.cases = [];
  9014. this.expect(types.braceL);
  9015. this.state.labels.push(switchLabel);
  9016. this.scope.enter(SCOPE_OTHER);
  9017. let cur;
  9018. for (let sawDefault; !this.match(types.braceR);) {
  9019. if (this.match(types._case) || this.match(types._default)) {
  9020. const isCase = this.match(types._case);
  9021. if (cur) this.finishNode(cur, "SwitchCase");
  9022. cases.push(cur = this.startNode());
  9023. cur.consequent = [];
  9024. this.next();
  9025. if (isCase) {
  9026. cur.test = this.parseExpression();
  9027. } else {
  9028. if (sawDefault) {
  9029. this.raise(this.state.lastTokStart, "Multiple default clauses");
  9030. }
  9031. sawDefault = true;
  9032. cur.test = null;
  9033. }
  9034. this.expect(types.colon);
  9035. } else {
  9036. if (cur) {
  9037. cur.consequent.push(this.parseStatement(null));
  9038. } else {
  9039. this.unexpected();
  9040. }
  9041. }
  9042. }
  9043. this.scope.exit();
  9044. if (cur) this.finishNode(cur, "SwitchCase");
  9045. this.next();
  9046. this.state.labels.pop();
  9047. return this.finishNode(node, "SwitchStatement");
  9048. }
  9049. parseThrowStatement(node) {
  9050. this.next();
  9051. if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) {
  9052. this.raise(this.state.lastTokEnd, "Illegal newline after throw");
  9053. }
  9054. node.argument = this.parseExpression();
  9055. this.semicolon();
  9056. return this.finishNode(node, "ThrowStatement");
  9057. }
  9058. parseTryStatement(node) {
  9059. this.next();
  9060. node.block = this.parseBlock();
  9061. node.handler = null;
  9062. if (this.match(types._catch)) {
  9063. const clause = this.startNode();
  9064. this.next();
  9065. if (this.match(types.parenL)) {
  9066. this.expect(types.parenL);
  9067. clause.param = this.parseBindingAtom();
  9068. const simple = clause.param.type === "Identifier";
  9069. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9070. this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause");
  9071. this.expect(types.parenR);
  9072. } else {
  9073. clause.param = null;
  9074. this.scope.enter(SCOPE_OTHER);
  9075. }
  9076. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9077. this.scope.exit();
  9078. node.handler = this.finishNode(clause, "CatchClause");
  9079. }
  9080. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9081. if (!node.handler && !node.finalizer) {
  9082. this.raise(node.start, "Missing catch or finally clause");
  9083. }
  9084. return this.finishNode(node, "TryStatement");
  9085. }
  9086. parseVarStatement(node, kind) {
  9087. this.next();
  9088. this.parseVar(node, false, kind);
  9089. this.semicolon();
  9090. return this.finishNode(node, "VariableDeclaration");
  9091. }
  9092. parseWhileStatement(node) {
  9093. this.next();
  9094. node.test = this.parseHeaderExpression();
  9095. this.state.labels.push(loopLabel);
  9096. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9097. this.state.labels.pop();
  9098. return this.finishNode(node, "WhileStatement");
  9099. }
  9100. parseWithStatement(node) {
  9101. if (this.state.strict) {
  9102. this.raise(this.state.start, "'with' in strict mode");
  9103. }
  9104. this.next();
  9105. node.object = this.parseHeaderExpression();
  9106. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9107. return this.finishNode(node, "WithStatement");
  9108. }
  9109. parseEmptyStatement(node) {
  9110. this.next();
  9111. return this.finishNode(node, "EmptyStatement");
  9112. }
  9113. parseLabeledStatement(node, maybeName, expr, context) {
  9114. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9115. const label = _this$state$labels[_i2];
  9116. if (label.name === maybeName) {
  9117. this.raise(expr.start, `Label '${maybeName}' is already declared`);
  9118. }
  9119. }
  9120. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9121. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9122. const label = this.state.labels[i];
  9123. if (label.statementStart === node.start) {
  9124. label.statementStart = this.state.start;
  9125. label.kind = kind;
  9126. } else {
  9127. break;
  9128. }
  9129. }
  9130. this.state.labels.push({
  9131. name: maybeName,
  9132. kind: kind,
  9133. statementStart: this.state.start
  9134. });
  9135. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9136. this.state.labels.pop();
  9137. node.label = expr;
  9138. return this.finishNode(node, "LabeledStatement");
  9139. }
  9140. parseExpressionStatement(node, expr) {
  9141. node.expression = expr;
  9142. this.semicolon();
  9143. return this.finishNode(node, "ExpressionStatement");
  9144. }
  9145. parseBlock(allowDirectives = false, createNewLexicalScope = true) {
  9146. const node = this.startNode();
  9147. this.expect(types.braceL);
  9148. if (createNewLexicalScope) {
  9149. this.scope.enter(SCOPE_OTHER);
  9150. }
  9151. this.parseBlockBody(node, allowDirectives, false, types.braceR);
  9152. if (createNewLexicalScope) {
  9153. this.scope.exit();
  9154. }
  9155. return this.finishNode(node, "BlockStatement");
  9156. }
  9157. isValidDirective(stmt) {
  9158. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9159. }
  9160. parseBlockBody(node, allowDirectives, topLevel, end) {
  9161. const body = node.body = [];
  9162. const directives = node.directives = [];
  9163. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end);
  9164. }
  9165. parseBlockOrModuleBlockBody(body, directives, topLevel, end) {
  9166. let parsedNonDirective = false;
  9167. let oldStrict;
  9168. let octalPosition;
  9169. while (!this.eat(end)) {
  9170. if (!parsedNonDirective && this.state.containsOctal && !octalPosition) {
  9171. octalPosition = this.state.octalPosition;
  9172. }
  9173. const stmt = this.parseStatement(null, topLevel);
  9174. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  9175. const directive = this.stmtToDirective(stmt);
  9176. directives.push(directive);
  9177. if (oldStrict === undefined && directive.value.value === "use strict") {
  9178. oldStrict = this.state.strict;
  9179. this.setStrict(true);
  9180. if (octalPosition) {
  9181. this.raise(octalPosition, "Octal literal in strict mode");
  9182. }
  9183. }
  9184. continue;
  9185. }
  9186. parsedNonDirective = true;
  9187. body.push(stmt);
  9188. }
  9189. if (oldStrict === false) {
  9190. this.setStrict(false);
  9191. }
  9192. }
  9193. parseFor(node, init) {
  9194. node.init = init;
  9195. this.expect(types.semi);
  9196. node.test = this.match(types.semi) ? null : this.parseExpression();
  9197. this.expect(types.semi);
  9198. node.update = this.match(types.parenR) ? null : this.parseExpression();
  9199. this.expect(types.parenR);
  9200. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9201. this.scope.exit();
  9202. this.state.labels.pop();
  9203. return this.finishNode(node, "ForStatement");
  9204. }
  9205. parseForIn(node, init, awaitAt) {
  9206. const isForIn = this.match(types._in);
  9207. this.next();
  9208. if (isForIn) {
  9209. if (awaitAt > -1) this.unexpected(awaitAt);
  9210. } else {
  9211. node.await = awaitAt > -1;
  9212. }
  9213. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  9214. this.raise(init.start, `${isForIn ? "for-in" : "for-of"} loop variable declaration may not have an initializer`);
  9215. } else if (init.type === "AssignmentPattern") {
  9216. this.raise(init.start, "Invalid left-hand side in for-loop");
  9217. }
  9218. node.left = init;
  9219. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  9220. this.expect(types.parenR);
  9221. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9222. this.scope.exit();
  9223. this.state.labels.pop();
  9224. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  9225. }
  9226. parseVar(node, isFor, kind) {
  9227. const declarations = node.declarations = [];
  9228. const isTypescript = this.hasPlugin("typescript");
  9229. node.kind = kind;
  9230. for (;;) {
  9231. const decl = this.startNode();
  9232. this.parseVarId(decl, kind);
  9233. if (this.eat(types.eq)) {
  9234. decl.init = this.parseMaybeAssign(isFor);
  9235. } else {
  9236. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  9237. if (!isTypescript) {
  9238. this.unexpected();
  9239. }
  9240. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  9241. this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value");
  9242. }
  9243. decl.init = null;
  9244. }
  9245. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  9246. if (!this.eat(types.comma)) break;
  9247. }
  9248. return node;
  9249. }
  9250. parseVarId(decl, kind) {
  9251. decl.id = this.parseBindingAtom();
  9252. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var");
  9253. }
  9254. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  9255. const isStatement = statement & FUNC_STATEMENT;
  9256. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  9257. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  9258. this.initFunction(node, isAsync);
  9259. if (this.match(types.star) && isHangingStatement) {
  9260. this.raise(this.state.start, "Generators can only be declared at the top level or inside a block");
  9261. }
  9262. node.generator = this.eat(types.star);
  9263. if (isStatement) {
  9264. node.id = this.parseFunctionId(requireId);
  9265. }
  9266. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9267. const oldYieldPos = this.state.yieldPos;
  9268. const oldAwaitPos = this.state.awaitPos;
  9269. this.state.maybeInArrowParameters = false;
  9270. this.state.yieldPos = -1;
  9271. this.state.awaitPos = -1;
  9272. this.scope.enter(functionFlags(node.async, node.generator));
  9273. if (!isStatement) {
  9274. node.id = this.parseFunctionId();
  9275. }
  9276. this.parseFunctionParams(node);
  9277. this.withTopicForbiddingContext(() => {
  9278. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  9279. });
  9280. this.scope.exit();
  9281. if (isStatement && !isHangingStatement) {
  9282. this.registerFunctionStatementId(node);
  9283. }
  9284. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9285. this.state.yieldPos = oldYieldPos;
  9286. this.state.awaitPos = oldAwaitPos;
  9287. return node;
  9288. }
  9289. parseFunctionId(requireId) {
  9290. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  9291. }
  9292. parseFunctionParams(node, allowModifiers) {
  9293. const oldInParameters = this.state.inParameters;
  9294. this.state.inParameters = true;
  9295. this.expect(types.parenL);
  9296. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  9297. this.state.inParameters = oldInParameters;
  9298. this.checkYieldAwaitInDefaultParams();
  9299. }
  9300. registerFunctionStatementId(node) {
  9301. if (!node.id) return;
  9302. 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);
  9303. }
  9304. parseClass(node, isStatement, optionalId) {
  9305. this.next();
  9306. this.takeDecorators(node);
  9307. const oldStrict = this.state.strict;
  9308. this.state.strict = true;
  9309. this.parseClassId(node, isStatement, optionalId);
  9310. this.parseClassSuper(node);
  9311. node.body = this.parseClassBody(!!node.superClass);
  9312. this.state.strict = oldStrict;
  9313. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  9314. }
  9315. isClassProperty() {
  9316. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  9317. }
  9318. isClassMethod() {
  9319. return this.match(types.parenL);
  9320. }
  9321. isNonstaticConstructor(method) {
  9322. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  9323. }
  9324. parseClassBody(constructorAllowsSuper) {
  9325. this.classScope.enter();
  9326. const state = {
  9327. hadConstructor: false
  9328. };
  9329. let decorators = [];
  9330. const classBody = this.startNode();
  9331. classBody.body = [];
  9332. this.expect(types.braceL);
  9333. this.withTopicForbiddingContext(() => {
  9334. while (!this.eat(types.braceR)) {
  9335. if (this.eat(types.semi)) {
  9336. if (decorators.length > 0) {
  9337. throw this.raise(this.state.lastTokEnd, "Decorators must not be followed by a semicolon");
  9338. }
  9339. continue;
  9340. }
  9341. if (this.match(types.at)) {
  9342. decorators.push(this.parseDecorator());
  9343. continue;
  9344. }
  9345. const member = this.startNode();
  9346. if (decorators.length) {
  9347. member.decorators = decorators;
  9348. this.resetStartLocationFromNode(member, decorators[0]);
  9349. decorators = [];
  9350. }
  9351. this.parseClassMember(classBody, member, state, constructorAllowsSuper);
  9352. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  9353. this.raise(member.start, "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?");
  9354. }
  9355. }
  9356. });
  9357. if (decorators.length) {
  9358. throw this.raise(this.state.start, "You have trailing decorators with no method");
  9359. }
  9360. this.classScope.exit();
  9361. return this.finishNode(classBody, "ClassBody");
  9362. }
  9363. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  9364. let isStatic = false;
  9365. const containsEsc = this.state.containsEsc;
  9366. if (this.match(types.name) && this.state.value === "static") {
  9367. const key = this.parseIdentifier(true);
  9368. if (this.isClassMethod()) {
  9369. const method = member;
  9370. method.kind = "method";
  9371. method.computed = false;
  9372. method.key = key;
  9373. method.static = false;
  9374. this.pushClassMethod(classBody, method, false, false, false, false);
  9375. return;
  9376. } else if (this.isClassProperty()) {
  9377. const prop = member;
  9378. prop.computed = false;
  9379. prop.key = key;
  9380. prop.static = false;
  9381. classBody.body.push(this.parseClassProperty(prop));
  9382. return;
  9383. } else if (containsEsc) {
  9384. throw this.unexpected();
  9385. }
  9386. isStatic = true;
  9387. }
  9388. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  9389. }
  9390. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  9391. const publicMethod = member;
  9392. const privateMethod = member;
  9393. const publicProp = member;
  9394. const privateProp = member;
  9395. const method = publicMethod;
  9396. const publicMember = publicMethod;
  9397. member.static = isStatic;
  9398. if (this.eat(types.star)) {
  9399. method.kind = "method";
  9400. this.parseClassPropertyName(method);
  9401. if (method.key.type === "PrivateName") {
  9402. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  9403. return;
  9404. }
  9405. if (this.isNonstaticConstructor(publicMethod)) {
  9406. this.raise(publicMethod.key.start, "Constructor can't be a generator");
  9407. }
  9408. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  9409. return;
  9410. }
  9411. const containsEsc = this.state.containsEsc;
  9412. const key = this.parseClassPropertyName(member);
  9413. const isPrivate = key.type === "PrivateName";
  9414. const isSimple = key.type === "Identifier";
  9415. const maybeQuestionTokenStart = this.state.start;
  9416. this.parsePostMemberNameModifiers(publicMember);
  9417. if (this.isClassMethod()) {
  9418. method.kind = "method";
  9419. if (isPrivate) {
  9420. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9421. return;
  9422. }
  9423. const isConstructor = this.isNonstaticConstructor(publicMethod);
  9424. let allowsDirectSuper = false;
  9425. if (isConstructor) {
  9426. publicMethod.kind = "constructor";
  9427. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  9428. this.raise(key.start, "Duplicate constructor in the same class");
  9429. }
  9430. state.hadConstructor = true;
  9431. allowsDirectSuper = constructorAllowsSuper;
  9432. }
  9433. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  9434. } else if (this.isClassProperty()) {
  9435. if (isPrivate) {
  9436. this.pushClassPrivateProperty(classBody, privateProp);
  9437. } else {
  9438. this.pushClassProperty(classBody, publicProp);
  9439. }
  9440. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  9441. const isGenerator = this.eat(types.star);
  9442. if (publicMember.optional) {
  9443. this.unexpected(maybeQuestionTokenStart);
  9444. }
  9445. method.kind = "method";
  9446. this.parseClassPropertyName(method);
  9447. this.parsePostMemberNameModifiers(publicMember);
  9448. if (method.key.type === "PrivateName") {
  9449. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  9450. } else {
  9451. if (this.isNonstaticConstructor(publicMethod)) {
  9452. this.raise(publicMethod.key.start, "Constructor can't be an async function");
  9453. }
  9454. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  9455. }
  9456. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  9457. method.kind = key.name;
  9458. this.parseClassPropertyName(publicMethod);
  9459. if (method.key.type === "PrivateName") {
  9460. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9461. } else {
  9462. if (this.isNonstaticConstructor(publicMethod)) {
  9463. this.raise(publicMethod.key.start, "Constructor can't have get/set modifier");
  9464. }
  9465. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  9466. }
  9467. this.checkGetterSetterParams(publicMethod);
  9468. } else if (this.isLineTerminator()) {
  9469. if (isPrivate) {
  9470. this.pushClassPrivateProperty(classBody, privateProp);
  9471. } else {
  9472. this.pushClassProperty(classBody, publicProp);
  9473. }
  9474. } else {
  9475. this.unexpected();
  9476. }
  9477. }
  9478. parseClassPropertyName(member) {
  9479. const key = this.parsePropertyName(member, true);
  9480. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  9481. this.raise(key.start, "Classes may not have static property named prototype");
  9482. }
  9483. if (key.type === "PrivateName" && key.id.name === "constructor") {
  9484. this.raise(key.start, "Classes may not have a private field named '#constructor'");
  9485. }
  9486. return key;
  9487. }
  9488. pushClassProperty(classBody, prop) {
  9489. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  9490. this.raise(prop.key.start, "Classes may not have a field named 'constructor'");
  9491. }
  9492. classBody.body.push(this.parseClassProperty(prop));
  9493. }
  9494. pushClassPrivateProperty(classBody, prop) {
  9495. this.expectPlugin("classPrivateProperties", prop.key.start);
  9496. const node = this.parseClassPrivateProperty(prop);
  9497. classBody.body.push(node);
  9498. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  9499. }
  9500. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9501. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  9502. }
  9503. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9504. this.expectPlugin("classPrivateMethods", method.key.start);
  9505. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  9506. classBody.body.push(node);
  9507. 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;
  9508. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  9509. }
  9510. parsePostMemberNameModifiers(methodOrProp) {}
  9511. parseAccessModifier() {
  9512. return undefined;
  9513. }
  9514. parseClassPrivateProperty(node) {
  9515. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9516. node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null;
  9517. this.semicolon();
  9518. this.scope.exit();
  9519. return this.finishNode(node, "ClassPrivateProperty");
  9520. }
  9521. parseClassProperty(node) {
  9522. if (!node.typeAnnotation) {
  9523. this.expectPlugin("classProperties");
  9524. }
  9525. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9526. if (this.match(types.eq)) {
  9527. this.expectPlugin("classProperties");
  9528. this.next();
  9529. node.value = this.parseMaybeAssign();
  9530. } else {
  9531. node.value = null;
  9532. }
  9533. this.semicolon();
  9534. this.scope.exit();
  9535. return this.finishNode(node, "ClassProperty");
  9536. }
  9537. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  9538. if (this.match(types.name)) {
  9539. node.id = this.parseIdentifier();
  9540. if (isStatement) {
  9541. this.checkLVal(node.id, bindingType, undefined, "class name");
  9542. }
  9543. } else {
  9544. if (optionalId || !isStatement) {
  9545. node.id = null;
  9546. } else {
  9547. this.unexpected(null, "A class name is required");
  9548. }
  9549. }
  9550. }
  9551. parseClassSuper(node) {
  9552. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  9553. }
  9554. parseExport(node) {
  9555. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  9556. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  9557. const hasStar = parseAfterDefault && this.eatExportStar(node);
  9558. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  9559. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  9560. const isFromRequired = hasDefault || hasStar;
  9561. if (hasStar && !hasNamespace) {
  9562. if (hasDefault) this.unexpected();
  9563. this.parseExportFrom(node, true);
  9564. return this.finishNode(node, "ExportAllDeclaration");
  9565. }
  9566. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  9567. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  9568. throw this.unexpected(null, types.braceL);
  9569. }
  9570. let hasDeclaration;
  9571. if (isFromRequired || hasSpecifiers) {
  9572. hasDeclaration = false;
  9573. this.parseExportFrom(node, isFromRequired);
  9574. } else {
  9575. hasDeclaration = this.maybeParseExportDeclaration(node);
  9576. }
  9577. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  9578. this.checkExport(node, true, false, !!node.source);
  9579. return this.finishNode(node, "ExportNamedDeclaration");
  9580. }
  9581. if (this.eat(types._default)) {
  9582. node.declaration = this.parseExportDefaultExpression();
  9583. this.checkExport(node, true, true);
  9584. return this.finishNode(node, "ExportDefaultDeclaration");
  9585. }
  9586. throw this.unexpected(null, types.braceL);
  9587. }
  9588. eatExportStar(node) {
  9589. return this.eat(types.star);
  9590. }
  9591. maybeParseExportDefaultSpecifier(node) {
  9592. if (this.isExportDefaultSpecifier()) {
  9593. this.expectPlugin("exportDefaultFrom");
  9594. const specifier = this.startNode();
  9595. specifier.exported = this.parseIdentifier(true);
  9596. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9597. return true;
  9598. }
  9599. return false;
  9600. }
  9601. maybeParseExportNamespaceSpecifier(node) {
  9602. if (this.isContextual("as")) {
  9603. if (!node.specifiers) node.specifiers = [];
  9604. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  9605. this.next();
  9606. specifier.exported = this.parseIdentifier(true);
  9607. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  9608. return true;
  9609. }
  9610. return false;
  9611. }
  9612. maybeParseExportNamedSpecifiers(node) {
  9613. if (this.match(types.braceL)) {
  9614. if (!node.specifiers) node.specifiers = [];
  9615. node.specifiers.push(...this.parseExportSpecifiers());
  9616. node.source = null;
  9617. node.declaration = null;
  9618. return true;
  9619. }
  9620. return false;
  9621. }
  9622. maybeParseExportDeclaration(node) {
  9623. if (this.shouldParseExportDeclaration()) {
  9624. if (this.isContextual("async")) {
  9625. const next = this.nextTokenStart();
  9626. if (!this.isUnparsedContextual(next, "function")) {
  9627. this.unexpected(next, `Unexpected token, expected "function"`);
  9628. }
  9629. }
  9630. node.specifiers = [];
  9631. node.source = null;
  9632. node.declaration = this.parseExportDeclaration(node);
  9633. return true;
  9634. }
  9635. return false;
  9636. }
  9637. isAsyncFunction() {
  9638. if (!this.isContextual("async")) return false;
  9639. const next = this.nextTokenStart();
  9640. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  9641. }
  9642. parseExportDefaultExpression() {
  9643. const expr = this.startNode();
  9644. const isAsync = this.isAsyncFunction();
  9645. if (this.match(types._function) || isAsync) {
  9646. this.next();
  9647. if (isAsync) {
  9648. this.next();
  9649. }
  9650. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  9651. } else if (this.match(types._class)) {
  9652. return this.parseClass(expr, true, true);
  9653. } else if (this.match(types.at)) {
  9654. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9655. this.raise(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax");
  9656. }
  9657. this.parseDecorators(false);
  9658. return this.parseClass(expr, true, true);
  9659. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  9660. throw this.raise(this.state.start, "Only expressions, functions or classes are allowed as the `default` export.");
  9661. } else {
  9662. const res = this.parseMaybeAssign();
  9663. this.semicolon();
  9664. return res;
  9665. }
  9666. }
  9667. parseExportDeclaration(node) {
  9668. return this.parseStatement(null);
  9669. }
  9670. isExportDefaultSpecifier() {
  9671. if (this.match(types.name)) {
  9672. return this.state.value !== "async" && this.state.value !== "let";
  9673. }
  9674. if (!this.match(types._default)) {
  9675. return false;
  9676. }
  9677. const next = this.nextTokenStart();
  9678. return this.input.charCodeAt(next) === 44 || this.isUnparsedContextual(next, "from");
  9679. }
  9680. parseExportFrom(node, expect) {
  9681. if (this.eatContextual("from")) {
  9682. node.source = this.parseImportSource();
  9683. this.checkExport(node);
  9684. } else {
  9685. if (expect) {
  9686. this.unexpected();
  9687. } else {
  9688. node.source = null;
  9689. }
  9690. }
  9691. this.semicolon();
  9692. }
  9693. shouldParseExportDeclaration() {
  9694. if (this.match(types.at)) {
  9695. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  9696. if (this.hasPlugin("decorators")) {
  9697. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9698. this.unexpected(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax");
  9699. } else {
  9700. return true;
  9701. }
  9702. }
  9703. }
  9704. 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();
  9705. }
  9706. checkExport(node, checkNames, isDefault, isFrom) {
  9707. if (checkNames) {
  9708. if (isDefault) {
  9709. this.checkDuplicateExports(node, "default");
  9710. } else if (node.specifiers && node.specifiers.length) {
  9711. for (let _i3 = 0, _node$specifiers = node.specifiers; _i3 < _node$specifiers.length; _i3++) {
  9712. const specifier = _node$specifiers[_i3];
  9713. this.checkDuplicateExports(specifier, specifier.exported.name);
  9714. if (!isFrom && specifier.local) {
  9715. this.checkReservedWord(specifier.local.name, specifier.local.start, true, false);
  9716. this.scope.checkLocalExport(specifier.local);
  9717. }
  9718. }
  9719. } else if (node.declaration) {
  9720. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  9721. const id = node.declaration.id;
  9722. if (!id) throw new Error("Assertion failure");
  9723. this.checkDuplicateExports(node, id.name);
  9724. } else if (node.declaration.type === "VariableDeclaration") {
  9725. for (let _i4 = 0, _node$declaration$dec = node.declaration.declarations; _i4 < _node$declaration$dec.length; _i4++) {
  9726. const declaration = _node$declaration$dec[_i4];
  9727. this.checkDeclaration(declaration.id);
  9728. }
  9729. }
  9730. }
  9731. }
  9732. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9733. if (currentContextDecorators.length) {
  9734. const isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
  9735. if (!node.declaration || !isClass) {
  9736. throw this.raise(node.start, "You can only use decorators on an export when exporting a class");
  9737. }
  9738. this.takeDecorators(node.declaration);
  9739. }
  9740. }
  9741. checkDeclaration(node) {
  9742. if (node.type === "Identifier") {
  9743. this.checkDuplicateExports(node, node.name);
  9744. } else if (node.type === "ObjectPattern") {
  9745. for (let _i5 = 0, _node$properties = node.properties; _i5 < _node$properties.length; _i5++) {
  9746. const prop = _node$properties[_i5];
  9747. this.checkDeclaration(prop);
  9748. }
  9749. } else if (node.type === "ArrayPattern") {
  9750. for (let _i6 = 0, _node$elements = node.elements; _i6 < _node$elements.length; _i6++) {
  9751. const elem = _node$elements[_i6];
  9752. if (elem) {
  9753. this.checkDeclaration(elem);
  9754. }
  9755. }
  9756. } else if (node.type === "ObjectProperty") {
  9757. this.checkDeclaration(node.value);
  9758. } else if (node.type === "RestElement") {
  9759. this.checkDeclaration(node.argument);
  9760. } else if (node.type === "AssignmentPattern") {
  9761. this.checkDeclaration(node.left);
  9762. }
  9763. }
  9764. checkDuplicateExports(node, name) {
  9765. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  9766. this.raise(node.start, name === "default" ? "Only one default export allowed per module." : `\`${name}\` has already been exported. Exported identifiers must be unique.`);
  9767. }
  9768. this.state.exportedIdentifiers.push(name);
  9769. }
  9770. parseExportSpecifiers() {
  9771. const nodes = [];
  9772. let first = true;
  9773. this.expect(types.braceL);
  9774. while (!this.eat(types.braceR)) {
  9775. if (first) {
  9776. first = false;
  9777. } else {
  9778. this.expect(types.comma);
  9779. if (this.eat(types.braceR)) break;
  9780. }
  9781. const node = this.startNode();
  9782. node.local = this.parseIdentifier(true);
  9783. node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
  9784. nodes.push(this.finishNode(node, "ExportSpecifier"));
  9785. }
  9786. return nodes;
  9787. }
  9788. parseImport(node) {
  9789. node.specifiers = [];
  9790. if (!this.match(types.string)) {
  9791. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  9792. const parseNext = !hasDefault || this.eat(types.comma);
  9793. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  9794. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  9795. this.expectContextual("from");
  9796. }
  9797. node.source = this.parseImportSource();
  9798. this.semicolon();
  9799. return this.finishNode(node, "ImportDeclaration");
  9800. }
  9801. parseImportSource() {
  9802. if (!this.match(types.string)) this.unexpected();
  9803. return this.parseExprAtom();
  9804. }
  9805. shouldParseDefaultImport(node) {
  9806. return this.match(types.name);
  9807. }
  9808. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  9809. specifier.local = this.parseIdentifier();
  9810. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  9811. node.specifiers.push(this.finishNode(specifier, type));
  9812. }
  9813. maybeParseDefaultImportSpecifier(node) {
  9814. if (this.shouldParseDefaultImport(node)) {
  9815. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  9816. return true;
  9817. }
  9818. return false;
  9819. }
  9820. maybeParseStarImportSpecifier(node) {
  9821. if (this.match(types.star)) {
  9822. const specifier = this.startNode();
  9823. this.next();
  9824. this.expectContextual("as");
  9825. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  9826. return true;
  9827. }
  9828. return false;
  9829. }
  9830. parseNamedImportSpecifiers(node) {
  9831. let first = true;
  9832. this.expect(types.braceL);
  9833. while (!this.eat(types.braceR)) {
  9834. if (first) {
  9835. first = false;
  9836. } else {
  9837. if (this.eat(types.colon)) {
  9838. throw this.raise(this.state.start, "ES2015 named imports do not destructure. " + "Use another statement for destructuring after the import.");
  9839. }
  9840. this.expect(types.comma);
  9841. if (this.eat(types.braceR)) break;
  9842. }
  9843. this.parseImportSpecifier(node);
  9844. }
  9845. }
  9846. parseImportSpecifier(node) {
  9847. const specifier = this.startNode();
  9848. specifier.imported = this.parseIdentifier(true);
  9849. if (this.eatContextual("as")) {
  9850. specifier.local = this.parseIdentifier();
  9851. } else {
  9852. this.checkReservedWord(specifier.imported.name, specifier.start, true, true);
  9853. specifier.local = specifier.imported.__clone();
  9854. }
  9855. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  9856. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  9857. }
  9858. }
  9859. class ClassScope {
  9860. constructor() {
  9861. this.privateNames = new Set();
  9862. this.loneAccessors = new Map();
  9863. this.undefinedPrivateNames = new Map();
  9864. }
  9865. }
  9866. class ClassScopeHandler {
  9867. constructor(raise) {
  9868. this.stack = [];
  9869. this.undefinedPrivateNames = new Map();
  9870. this.raise = raise;
  9871. }
  9872. current() {
  9873. return this.stack[this.stack.length - 1];
  9874. }
  9875. enter() {
  9876. this.stack.push(new ClassScope());
  9877. }
  9878. exit() {
  9879. const oldClassScope = this.stack.pop();
  9880. const current = this.current();
  9881. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  9882. const [name, pos] = _Array$from[_i];
  9883. if (current) {
  9884. if (!current.undefinedPrivateNames.has(name)) {
  9885. current.undefinedPrivateNames.set(name, pos);
  9886. }
  9887. } else {
  9888. this.raiseUndeclaredPrivateName(name, pos);
  9889. }
  9890. }
  9891. }
  9892. declarePrivateName(name, elementType, pos) {
  9893. const classScope = this.current();
  9894. let redefined = classScope.privateNames.has(name);
  9895. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  9896. const accessor = redefined && classScope.loneAccessors.get(name);
  9897. if (accessor) {
  9898. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  9899. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  9900. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  9901. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  9902. redefined = oldKind === newKind || oldStatic !== newStatic;
  9903. if (!redefined) classScope.loneAccessors.delete(name);
  9904. } else if (!redefined) {
  9905. classScope.loneAccessors.set(name, elementType);
  9906. }
  9907. }
  9908. if (redefined) {
  9909. this.raise(pos, `Duplicate private name #${name}`);
  9910. }
  9911. classScope.privateNames.add(name);
  9912. classScope.undefinedPrivateNames.delete(name);
  9913. }
  9914. usePrivateName(name, pos) {
  9915. let classScope;
  9916. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  9917. classScope = _this$stack[_i2];
  9918. if (classScope.privateNames.has(name)) return;
  9919. }
  9920. if (classScope) {
  9921. classScope.undefinedPrivateNames.set(name, pos);
  9922. } else {
  9923. this.raiseUndeclaredPrivateName(name, pos);
  9924. }
  9925. }
  9926. raiseUndeclaredPrivateName(name, pos) {
  9927. this.raise(pos, `Private name #${name} is not defined`);
  9928. }
  9929. }
  9930. class Parser extends StatementParser {
  9931. constructor(options, input) {
  9932. options = getOptions(options);
  9933. super(options, input);
  9934. const ScopeHandler = this.getScopeHandler();
  9935. this.options = options;
  9936. this.inModule = this.options.sourceType === "module";
  9937. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  9938. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  9939. this.plugins = pluginsMap(this.options.plugins);
  9940. this.filename = options.sourceFilename;
  9941. }
  9942. getScopeHandler() {
  9943. return ScopeHandler;
  9944. }
  9945. parse() {
  9946. let scopeFlags = SCOPE_PROGRAM;
  9947. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  9948. scopeFlags |= SCOPE_ASYNC;
  9949. }
  9950. this.scope.enter(scopeFlags);
  9951. const file = this.startNode();
  9952. const program = this.startNode();
  9953. this.nextToken();
  9954. file.errors = null;
  9955. this.parseTopLevel(file, program);
  9956. file.errors = this.state.errors;
  9957. return file;
  9958. }
  9959. }
  9960. function pluginsMap(plugins) {
  9961. const pluginMap = new Map();
  9962. for (let _i = 0; _i < plugins.length; _i++) {
  9963. const plugin = plugins[_i];
  9964. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  9965. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  9966. }
  9967. return pluginMap;
  9968. }
  9969. function parse(input, options) {
  9970. if (options && options.sourceType === "unambiguous") {
  9971. options = Object.assign({}, options);
  9972. try {
  9973. options.sourceType = "module";
  9974. const parser = getParser(options, input);
  9975. const ast = parser.parse();
  9976. if (parser.sawUnambiguousESM) {
  9977. return ast;
  9978. }
  9979. if (parser.ambiguousScriptDifferentAst) {
  9980. try {
  9981. options.sourceType = "script";
  9982. return getParser(options, input).parse();
  9983. } catch (_unused) {}
  9984. } else {
  9985. ast.program.sourceType = "script";
  9986. }
  9987. return ast;
  9988. } catch (moduleError) {
  9989. try {
  9990. options.sourceType = "script";
  9991. return getParser(options, input).parse();
  9992. } catch (_unused2) {}
  9993. throw moduleError;
  9994. }
  9995. } else {
  9996. return getParser(options, input).parse();
  9997. }
  9998. }
  9999. function parseExpression(input, options) {
  10000. const parser = getParser(options, input);
  10001. if (parser.options.strictMode) {
  10002. parser.state.strict = true;
  10003. }
  10004. return parser.getExpression();
  10005. }
  10006. function getParser(options, input) {
  10007. let cls = Parser;
  10008. if (options && options.plugins) {
  10009. validatePlugins(options.plugins);
  10010. cls = getParserClass(options.plugins);
  10011. }
  10012. return new cls(options, input);
  10013. }
  10014. const parserClassCache = {};
  10015. function getParserClass(pluginsFromOptions) {
  10016. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  10017. const key = pluginList.join("/");
  10018. let cls = parserClassCache[key];
  10019. if (!cls) {
  10020. cls = Parser;
  10021. for (let _i = 0; _i < pluginList.length; _i++) {
  10022. const plugin = pluginList[_i];
  10023. cls = mixinPlugins[plugin](cls);
  10024. }
  10025. parserClassCache[key] = cls;
  10026. }
  10027. return cls;
  10028. }
  10029. exports.parse = parse;
  10030. exports.parseExpression = parseExpression;
  10031. exports.tokTypes = types;
  10032. //# sourceMappingURL=index.js.map