index.js 378 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771
  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. bracketHashL: new TokenType("#[", {
  59. beforeExpr,
  60. startsExpr
  61. }),
  62. bracketBarL: new TokenType("[|", {
  63. beforeExpr,
  64. startsExpr
  65. }),
  66. bracketR: new TokenType("]"),
  67. bracketBarR: new TokenType("|]"),
  68. braceL: new TokenType("{", {
  69. beforeExpr,
  70. startsExpr
  71. }),
  72. braceBarL: new TokenType("{|", {
  73. beforeExpr,
  74. startsExpr
  75. }),
  76. braceHashL: new TokenType("#{", {
  77. beforeExpr,
  78. startsExpr
  79. }),
  80. braceR: new TokenType("}"),
  81. braceBarR: new TokenType("|}"),
  82. parenL: new TokenType("(", {
  83. beforeExpr,
  84. startsExpr
  85. }),
  86. parenR: new TokenType(")"),
  87. comma: new TokenType(",", {
  88. beforeExpr
  89. }),
  90. semi: new TokenType(";", {
  91. beforeExpr
  92. }),
  93. colon: new TokenType(":", {
  94. beforeExpr
  95. }),
  96. doubleColon: new TokenType("::", {
  97. beforeExpr
  98. }),
  99. dot: new TokenType("."),
  100. question: new TokenType("?", {
  101. beforeExpr
  102. }),
  103. questionDot: new TokenType("?."),
  104. arrow: new TokenType("=>", {
  105. beforeExpr
  106. }),
  107. template: new TokenType("template"),
  108. ellipsis: new TokenType("...", {
  109. beforeExpr
  110. }),
  111. backQuote: new TokenType("`", {
  112. startsExpr
  113. }),
  114. dollarBraceL: new TokenType("${", {
  115. beforeExpr,
  116. startsExpr
  117. }),
  118. at: new TokenType("@"),
  119. hash: new TokenType("#", {
  120. startsExpr
  121. }),
  122. interpreterDirective: new TokenType("#!..."),
  123. eq: new TokenType("=", {
  124. beforeExpr,
  125. isAssign
  126. }),
  127. assign: new TokenType("_=", {
  128. beforeExpr,
  129. isAssign
  130. }),
  131. incDec: new TokenType("++/--", {
  132. prefix,
  133. postfix,
  134. startsExpr
  135. }),
  136. bang: new TokenType("!", {
  137. beforeExpr,
  138. prefix,
  139. startsExpr
  140. }),
  141. tilde: new TokenType("~", {
  142. beforeExpr,
  143. prefix,
  144. startsExpr
  145. }),
  146. pipeline: createBinop("|>", 0),
  147. nullishCoalescing: createBinop("??", 1),
  148. logicalOR: createBinop("||", 1),
  149. logicalAND: createBinop("&&", 2),
  150. bitwiseOR: createBinop("|", 3),
  151. bitwiseXOR: createBinop("^", 4),
  152. bitwiseAND: createBinop("&", 5),
  153. equality: createBinop("==/!=/===/!==", 6),
  154. relational: createBinop("</>/<=/>=", 7),
  155. bitShift: createBinop("<</>>/>>>", 8),
  156. plusMin: new TokenType("+/-", {
  157. beforeExpr,
  158. binop: 9,
  159. prefix,
  160. startsExpr
  161. }),
  162. modulo: new TokenType("%", {
  163. beforeExpr,
  164. binop: 10,
  165. startsExpr
  166. }),
  167. star: createBinop("*", 10),
  168. slash: createBinop("/", 10),
  169. exponent: new TokenType("**", {
  170. beforeExpr,
  171. binop: 11,
  172. rightAssociative: true
  173. }),
  174. _break: createKeyword("break"),
  175. _case: createKeyword("case", {
  176. beforeExpr
  177. }),
  178. _catch: createKeyword("catch"),
  179. _continue: createKeyword("continue"),
  180. _debugger: createKeyword("debugger"),
  181. _default: createKeyword("default", {
  182. beforeExpr
  183. }),
  184. _do: createKeyword("do", {
  185. isLoop,
  186. beforeExpr
  187. }),
  188. _else: createKeyword("else", {
  189. beforeExpr
  190. }),
  191. _finally: createKeyword("finally"),
  192. _for: createKeyword("for", {
  193. isLoop
  194. }),
  195. _function: createKeyword("function", {
  196. startsExpr
  197. }),
  198. _if: createKeyword("if"),
  199. _return: createKeyword("return", {
  200. beforeExpr
  201. }),
  202. _switch: createKeyword("switch"),
  203. _throw: createKeyword("throw", {
  204. beforeExpr,
  205. prefix,
  206. startsExpr
  207. }),
  208. _try: createKeyword("try"),
  209. _var: createKeyword("var"),
  210. _const: createKeyword("const"),
  211. _while: createKeyword("while", {
  212. isLoop
  213. }),
  214. _with: createKeyword("with"),
  215. _new: createKeyword("new", {
  216. beforeExpr,
  217. startsExpr
  218. }),
  219. _this: createKeyword("this", {
  220. startsExpr
  221. }),
  222. _super: createKeyword("super", {
  223. startsExpr
  224. }),
  225. _class: createKeyword("class", {
  226. startsExpr
  227. }),
  228. _extends: createKeyword("extends", {
  229. beforeExpr
  230. }),
  231. _export: createKeyword("export"),
  232. _import: createKeyword("import", {
  233. startsExpr
  234. }),
  235. _null: createKeyword("null", {
  236. startsExpr
  237. }),
  238. _true: createKeyword("true", {
  239. startsExpr
  240. }),
  241. _false: createKeyword("false", {
  242. startsExpr
  243. }),
  244. _in: createKeyword("in", {
  245. beforeExpr,
  246. binop: 7
  247. }),
  248. _instanceof: createKeyword("instanceof", {
  249. beforeExpr,
  250. binop: 7
  251. }),
  252. _typeof: createKeyword("typeof", {
  253. beforeExpr,
  254. prefix,
  255. startsExpr
  256. }),
  257. _void: createKeyword("void", {
  258. beforeExpr,
  259. prefix,
  260. startsExpr
  261. }),
  262. _delete: createKeyword("delete", {
  263. beforeExpr,
  264. prefix,
  265. startsExpr
  266. })
  267. };
  268. const SCOPE_OTHER = 0b00000000,
  269. SCOPE_PROGRAM = 0b00000001,
  270. SCOPE_FUNCTION = 0b00000010,
  271. SCOPE_ARROW = 0b00000100,
  272. SCOPE_SIMPLE_CATCH = 0b00001000,
  273. SCOPE_SUPER = 0b00010000,
  274. SCOPE_DIRECT_SUPER = 0b00100000,
  275. SCOPE_CLASS = 0b01000000,
  276. SCOPE_TS_MODULE = 0b10000000,
  277. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  278. const BIND_KIND_VALUE = 0b00000000001,
  279. BIND_KIND_TYPE = 0b00000000010,
  280. BIND_SCOPE_VAR = 0b00000000100,
  281. BIND_SCOPE_LEXICAL = 0b00000001000,
  282. BIND_SCOPE_FUNCTION = 0b00000010000,
  283. BIND_FLAGS_NONE = 0b00001000000,
  284. BIND_FLAGS_CLASS = 0b00010000000,
  285. BIND_FLAGS_TS_ENUM = 0b00100000000,
  286. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  287. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  288. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  289. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  290. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  291. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  292. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  293. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  294. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  295. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  296. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  297. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  298. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  299. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  300. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  301. CLASS_ELEMENT_KIND_GETTER = 0b010,
  302. CLASS_ELEMENT_KIND_SETTER = 0b001,
  303. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  304. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  305. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  306. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  307. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  308. CLASS_ELEMENT_OTHER = 0;
  309. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  310. const lineBreakG = new RegExp(lineBreak.source, "g");
  311. function isNewLine(code) {
  312. switch (code) {
  313. case 10:
  314. case 13:
  315. case 8232:
  316. case 8233:
  317. return true;
  318. default:
  319. return false;
  320. }
  321. }
  322. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  323. function isWhitespace(code) {
  324. switch (code) {
  325. case 0x0009:
  326. case 0x000b:
  327. case 0x000c:
  328. case 32:
  329. case 160:
  330. case 5760:
  331. case 0x2000:
  332. case 0x2001:
  333. case 0x2002:
  334. case 0x2003:
  335. case 0x2004:
  336. case 0x2005:
  337. case 0x2006:
  338. case 0x2007:
  339. case 0x2008:
  340. case 0x2009:
  341. case 0x200a:
  342. case 0x202f:
  343. case 0x205f:
  344. case 0x3000:
  345. case 0xfeff:
  346. return true;
  347. default:
  348. return false;
  349. }
  350. }
  351. class Position {
  352. constructor(line, col) {
  353. this.line = line;
  354. this.column = col;
  355. }
  356. }
  357. class SourceLocation {
  358. constructor(start, end) {
  359. this.start = start;
  360. this.end = end;
  361. }
  362. }
  363. function getLineInfo(input, offset) {
  364. let line = 1;
  365. let lineStart = 0;
  366. let match;
  367. lineBreakG.lastIndex = 0;
  368. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  369. line++;
  370. lineStart = lineBreakG.lastIndex;
  371. }
  372. return new Position(line, offset - lineStart);
  373. }
  374. class BaseParser {
  375. constructor() {
  376. this.sawUnambiguousESM = false;
  377. this.ambiguousScriptDifferentAst = false;
  378. }
  379. hasPlugin(name) {
  380. return this.plugins.has(name);
  381. }
  382. getPluginOption(plugin, name) {
  383. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  384. }
  385. }
  386. function last(stack) {
  387. return stack[stack.length - 1];
  388. }
  389. class CommentsParser extends BaseParser {
  390. addComment(comment) {
  391. if (this.filename) comment.loc.filename = this.filename;
  392. this.state.trailingComments.push(comment);
  393. this.state.leadingComments.push(comment);
  394. }
  395. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  396. if (this.state.leadingComments.length === 0) {
  397. return;
  398. }
  399. let lastElement = null;
  400. let i = elements.length;
  401. while (lastElement === null && i > 0) {
  402. lastElement = elements[--i];
  403. }
  404. if (lastElement === null) {
  405. return;
  406. }
  407. for (let j = 0; j < this.state.leadingComments.length; j++) {
  408. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  409. this.state.leadingComments.splice(j, 1);
  410. j--;
  411. }
  412. }
  413. const newTrailingComments = [];
  414. for (let i = 0; i < this.state.leadingComments.length; i++) {
  415. const leadingComment = this.state.leadingComments[i];
  416. if (leadingComment.end < node.end) {
  417. newTrailingComments.push(leadingComment);
  418. if (!takeAllComments) {
  419. this.state.leadingComments.splice(i, 1);
  420. i--;
  421. }
  422. } else {
  423. if (node.trailingComments === undefined) {
  424. node.trailingComments = [];
  425. }
  426. node.trailingComments.push(leadingComment);
  427. }
  428. }
  429. if (takeAllComments) this.state.leadingComments = [];
  430. if (newTrailingComments.length > 0) {
  431. lastElement.trailingComments = newTrailingComments;
  432. } else if (lastElement.trailingComments !== undefined) {
  433. lastElement.trailingComments = [];
  434. }
  435. }
  436. processComment(node) {
  437. if (node.type === "Program" && node.body.length > 0) return;
  438. const stack = this.state.commentStack;
  439. let firstChild, lastChild, trailingComments, i, j;
  440. if (this.state.trailingComments.length > 0) {
  441. if (this.state.trailingComments[0].start >= node.end) {
  442. trailingComments = this.state.trailingComments;
  443. this.state.trailingComments = [];
  444. } else {
  445. this.state.trailingComments.length = 0;
  446. }
  447. } else if (stack.length > 0) {
  448. const lastInStack = last(stack);
  449. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  450. trailingComments = lastInStack.trailingComments;
  451. delete lastInStack.trailingComments;
  452. }
  453. }
  454. if (stack.length > 0 && last(stack).start >= node.start) {
  455. firstChild = stack.pop();
  456. }
  457. while (stack.length > 0 && last(stack).start >= node.start) {
  458. lastChild = stack.pop();
  459. }
  460. if (!lastChild && firstChild) lastChild = firstChild;
  461. if (firstChild) {
  462. switch (node.type) {
  463. case "ObjectExpression":
  464. this.adjustCommentsAfterTrailingComma(node, node.properties);
  465. break;
  466. case "ObjectPattern":
  467. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  468. break;
  469. case "CallExpression":
  470. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  471. break;
  472. case "ArrayExpression":
  473. this.adjustCommentsAfterTrailingComma(node, node.elements);
  474. break;
  475. case "ArrayPattern":
  476. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  477. break;
  478. }
  479. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  480. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  481. }
  482. if (lastChild) {
  483. if (lastChild.leadingComments) {
  484. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  485. node.leadingComments = lastChild.leadingComments;
  486. delete lastChild.leadingComments;
  487. } else {
  488. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  489. if (lastChild.leadingComments[i].end <= node.start) {
  490. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  491. break;
  492. }
  493. }
  494. }
  495. }
  496. } else if (this.state.leadingComments.length > 0) {
  497. if (last(this.state.leadingComments).end <= node.start) {
  498. if (this.state.commentPreviousNode) {
  499. for (j = 0; j < this.state.leadingComments.length; j++) {
  500. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  501. this.state.leadingComments.splice(j, 1);
  502. j--;
  503. }
  504. }
  505. }
  506. if (this.state.leadingComments.length > 0) {
  507. node.leadingComments = this.state.leadingComments;
  508. this.state.leadingComments = [];
  509. }
  510. } else {
  511. for (i = 0; i < this.state.leadingComments.length; i++) {
  512. if (this.state.leadingComments[i].end > node.start) {
  513. break;
  514. }
  515. }
  516. const leadingComments = this.state.leadingComments.slice(0, i);
  517. if (leadingComments.length) {
  518. node.leadingComments = leadingComments;
  519. }
  520. trailingComments = this.state.leadingComments.slice(i);
  521. if (trailingComments.length === 0) {
  522. trailingComments = null;
  523. }
  524. }
  525. }
  526. this.state.commentPreviousNode = node;
  527. if (trailingComments) {
  528. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  529. node.innerComments = trailingComments;
  530. } else {
  531. node.trailingComments = trailingComments;
  532. }
  533. }
  534. stack.push(node);
  535. }
  536. }
  537. const Errors = Object.freeze({
  538. ArgumentsDisallowedInInitializer: "'arguments' is not allowed in class field initializer",
  539. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  540. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  541. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  542. AwaitNotInAsyncFunction: "Can not use keyword 'await' outside an async function",
  543. BadGetterArity: "getter must not have any formal parameters",
  544. BadSetterArity: "setter must have exactly one formal parameter",
  545. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  546. ConstructorClassField: "Classes may not have a field named 'constructor'",
  547. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  548. ConstructorIsAccessor: "Class constructor may not be an accessor",
  549. ConstructorIsAsync: "Constructor can't be an async function",
  550. ConstructorIsGenerator: "Constructor can't be a generator",
  551. DeclarationMissingInitializer: "%0 require an initialization value",
  552. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  553. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  554. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  555. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  556. DeletePrivateField: "Deleting a private field is not allowed",
  557. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  558. DuplicateConstructor: "Duplicate constructor in the same class",
  559. DuplicateDefaultExport: "Only one default export allowed per module.",
  560. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  561. DuplicateProto: "Redefinition of __proto__ property",
  562. DuplicateRegExpFlags: "Duplicate regular expression flag",
  563. ElementAfterRest: "Rest element must be last element",
  564. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  565. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  566. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  567. IllegalBreakContinue: "Unsyntactic %0",
  568. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  569. IllegalReturn: "'return' outside of function",
  570. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  571. ImportCallArity: "import() requires exactly one argument",
  572. ImportCallArityLtOne: "Dynamic imports require a parameter: import('a.js')",
  573. ImportCallNotNewExpression: "Cannot use new with import(...)",
  574. ImportCallSpreadArgument: "... is not allowed in import()",
  575. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  576. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  577. InvalidCodePoint: "Code point out of bounds",
  578. InvalidDigit: "Expected number in radix %0",
  579. InvalidEscapeSequence: "Bad character escape sequence",
  580. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  581. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  582. InvalidIdentifier: "Invalid identifier %0",
  583. InvalidLhs: "Invalid left-hand side in %0",
  584. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  585. InvalidNumber: "Invalid number",
  586. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  587. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  588. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  589. InvalidPropertyBindingPattern: "Binding member expression",
  590. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  591. LabelRedeclaration: "Label '%0' is already declared",
  592. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  593. MalformedRegExpFlags: "Invalid regular expression flag",
  594. MissingClassName: "A class name is required",
  595. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  596. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  597. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  598. ModuleExportUndefined: "Export '%0' is not defined",
  599. MultipleDefaultsInSwitch: "Multiple default clauses",
  600. NewlineAfterThrow: "Illegal newline after throw",
  601. NoCatchOrFinally: "Missing catch or finally clause",
  602. NumberIdentifier: "Identifier directly after number",
  603. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  604. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  605. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  606. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  607. ParamDupe: "Argument name clash",
  608. PatternHasAccessor: "Object pattern can't contain getter or setter",
  609. PatternHasMethod: "Object pattern can't contain methods",
  610. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  611. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  612. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  613. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  614. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  615. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  616. PrivateNameRedeclaration: "Duplicate private name #%0",
  617. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  618. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  619. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  620. RestTrailingComma: "Unexpected trailing comma after rest element",
  621. SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement",
  622. StaticPrototype: "Classes may not have static property named prototype",
  623. StrictDelete: "Deleting local variable in strict mode",
  624. StrictEvalArguments: "Assigning to '%0' in strict mode",
  625. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  626. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  627. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  628. StrictWith: "'with' in strict mode",
  629. SuperNotAllowed: "super() is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  630. SuperPrivateField: "Private fields can't be accessed on super",
  631. TrailingDecorator: "Decorators must be attached to a class element",
  632. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  633. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  634. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  635. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  636. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  637. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  638. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  639. UnexpectedKeyword: "Unexpected keyword '%0'",
  640. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  641. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  642. UnexpectedNewTarget: "new.target can only be used in functions",
  643. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  644. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  645. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  646. UnexpectedSuper: "super is only allowed in object methods and classes",
  647. UnexpectedToken: "Unexpected token '%'",
  648. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  649. UnsupportedBind: "Binding should be performed on object property.",
  650. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  651. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  652. UnsupportedImport: "import can only be used in import() or import.meta",
  653. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  654. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  655. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  656. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  657. UnterminatedComment: "Unterminated comment",
  658. UnterminatedRegExp: "Unterminated regular expression",
  659. UnterminatedString: "Unterminated string constant",
  660. UnterminatedTemplate: "Unterminated template",
  661. VarRedeclaration: "Identifier '%0' has already been declared",
  662. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  663. YieldInParameter: "yield is not allowed in generator parameters",
  664. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  665. });
  666. class LocationParser extends CommentsParser {
  667. getLocationForPosition(pos) {
  668. let loc;
  669. 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);
  670. return loc;
  671. }
  672. raise(pos, errorTemplate, ...params) {
  673. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  674. }
  675. raiseWithData(pos, data, errorTemplate, ...params) {
  676. const loc = this.getLocationForPosition(pos);
  677. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  678. return this._raise(Object.assign({
  679. loc,
  680. pos
  681. }, data), message);
  682. }
  683. _raise(errorContext, message) {
  684. const err = new SyntaxError(message);
  685. Object.assign(err, errorContext);
  686. if (this.options.errorRecovery) {
  687. if (!this.isLookahead) this.state.errors.push(err);
  688. return err;
  689. } else {
  690. throw err;
  691. }
  692. }
  693. }
  694. function isSimpleProperty(node) {
  695. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  696. }
  697. var estree = (superClass => class extends superClass {
  698. estreeParseRegExpLiteral({
  699. pattern,
  700. flags
  701. }) {
  702. let regex = null;
  703. try {
  704. regex = new RegExp(pattern, flags);
  705. } catch (e) {}
  706. const node = this.estreeParseLiteral(regex);
  707. node.regex = {
  708. pattern,
  709. flags
  710. };
  711. return node;
  712. }
  713. estreeParseBigIntLiteral(value) {
  714. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  715. const node = this.estreeParseLiteral(bigInt);
  716. node.bigint = String(node.value || value);
  717. return node;
  718. }
  719. estreeParseLiteral(value) {
  720. return this.parseLiteral(value, "Literal");
  721. }
  722. directiveToStmt(directive) {
  723. const directiveLiteral = directive.value;
  724. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  725. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  726. expression.value = directiveLiteral.value;
  727. expression.raw = directiveLiteral.extra.raw;
  728. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  729. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  730. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  731. }
  732. initFunction(node, isAsync) {
  733. super.initFunction(node, isAsync);
  734. node.expression = false;
  735. }
  736. checkDeclaration(node) {
  737. if (isSimpleProperty(node)) {
  738. this.checkDeclaration(node.value);
  739. } else {
  740. super.checkDeclaration(node);
  741. }
  742. }
  743. checkGetterSetterParams(method) {
  744. const prop = method;
  745. const paramCount = prop.kind === "get" ? 0 : 1;
  746. const start = prop.start;
  747. if (prop.value.params.length !== paramCount) {
  748. if (method.kind === "get") {
  749. this.raise(start, Errors.BadGetterArity);
  750. } else {
  751. this.raise(start, Errors.BadSetterArity);
  752. }
  753. } else if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
  754. this.raise(start, Errors.BadSetterRestParameter);
  755. }
  756. }
  757. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding) {
  758. switch (expr.type) {
  759. case "ObjectPattern":
  760. expr.properties.forEach(prop => {
  761. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  762. });
  763. break;
  764. default:
  765. super.checkLVal(expr, bindingType, checkClashes, contextDescription, disallowLetBinding);
  766. }
  767. }
  768. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  769. if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) {
  770. return;
  771. }
  772. const key = prop.key;
  773. const name = key.type === "Identifier" ? key.name : String(key.value);
  774. if (name === "__proto__" && prop.kind === "init") {
  775. if (protoRef.used) {
  776. if (refExpressionErrors && refExpressionErrors.doubleProto === -1) {
  777. refExpressionErrors.doubleProto = key.start;
  778. } else {
  779. this.raise(key.start, Errors.DuplicateProto);
  780. }
  781. }
  782. protoRef.used = true;
  783. }
  784. }
  785. isValidDirective(stmt) {
  786. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized);
  787. }
  788. stmtToDirective(stmt) {
  789. const directive = super.stmtToDirective(stmt);
  790. const value = stmt.expression.value;
  791. directive.value.value = value;
  792. return directive;
  793. }
  794. parseBlockBody(node, allowDirectives, topLevel, end) {
  795. super.parseBlockBody(node, allowDirectives, topLevel, end);
  796. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  797. node.body = directiveStatements.concat(node.body);
  798. delete node.directives;
  799. }
  800. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  801. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  802. if (method.typeParameters) {
  803. method.value.typeParameters = method.typeParameters;
  804. delete method.typeParameters;
  805. }
  806. classBody.body.push(method);
  807. }
  808. parseExprAtom(refExpressionErrors) {
  809. switch (this.state.type) {
  810. case types.num:
  811. case types.string:
  812. return this.estreeParseLiteral(this.state.value);
  813. case types.regexp:
  814. return this.estreeParseRegExpLiteral(this.state.value);
  815. case types.bigint:
  816. return this.estreeParseBigIntLiteral(this.state.value);
  817. case types._null:
  818. return this.estreeParseLiteral(null);
  819. case types._true:
  820. return this.estreeParseLiteral(true);
  821. case types._false:
  822. return this.estreeParseLiteral(false);
  823. default:
  824. return super.parseExprAtom(refExpressionErrors);
  825. }
  826. }
  827. parseLiteral(value, type, startPos, startLoc) {
  828. const node = super.parseLiteral(value, type, startPos, startLoc);
  829. node.raw = node.extra.raw;
  830. delete node.extra;
  831. return node;
  832. }
  833. parseFunctionBody(node, allowExpression, isMethod = false) {
  834. super.parseFunctionBody(node, allowExpression, isMethod);
  835. node.expression = node.body.type !== "BlockStatement";
  836. }
  837. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  838. let funcNode = this.startNode();
  839. funcNode.kind = node.kind;
  840. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  841. funcNode.type = "FunctionExpression";
  842. delete funcNode.kind;
  843. node.value = funcNode;
  844. type = type === "ClassMethod" ? "MethodDefinition" : type;
  845. return this.finishNode(node, type);
  846. }
  847. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  848. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc);
  849. if (node) {
  850. node.type = "Property";
  851. if (node.kind === "method") node.kind = "init";
  852. node.shorthand = false;
  853. }
  854. return node;
  855. }
  856. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  857. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  858. if (node) {
  859. node.kind = "init";
  860. node.type = "Property";
  861. }
  862. return node;
  863. }
  864. toAssignable(node) {
  865. if (isSimpleProperty(node)) {
  866. this.toAssignable(node.value);
  867. return node;
  868. }
  869. return super.toAssignable(node);
  870. }
  871. toAssignableObjectExpressionProp(prop, isLast) {
  872. if (prop.kind === "get" || prop.kind === "set") {
  873. throw this.raise(prop.key.start, Errors.PatternHasAccessor);
  874. } else if (prop.method) {
  875. throw this.raise(prop.key.start, Errors.PatternHasMethod);
  876. } else {
  877. super.toAssignableObjectExpressionProp(prop, isLast);
  878. }
  879. }
  880. finishCallExpression(node, optional) {
  881. super.finishCallExpression(node, optional);
  882. if (node.callee.type === "Import") {
  883. node.type = "ImportExpression";
  884. node.source = node.arguments[0];
  885. delete node.arguments;
  886. delete node.callee;
  887. }
  888. return node;
  889. }
  890. toReferencedListDeep(exprList, isParenthesizedExpr) {
  891. if (!exprList) {
  892. return;
  893. }
  894. super.toReferencedListDeep(exprList, isParenthesizedExpr);
  895. }
  896. parseExport(node) {
  897. super.parseExport(node);
  898. switch (node.type) {
  899. case "ExportAllDeclaration":
  900. node.exported = null;
  901. break;
  902. case "ExportNamedDeclaration":
  903. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  904. node.type = "ExportAllDeclaration";
  905. node.exported = node.specifiers[0].exported;
  906. delete node.specifiers;
  907. }
  908. break;
  909. }
  910. return node;
  911. }
  912. });
  913. class TokContext {
  914. constructor(token, isExpr, preserveSpace, override) {
  915. this.token = token;
  916. this.isExpr = !!isExpr;
  917. this.preserveSpace = !!preserveSpace;
  918. this.override = override;
  919. }
  920. }
  921. const types$1 = {
  922. braceStatement: new TokContext("{", false),
  923. braceExpression: new TokContext("{", true),
  924. templateQuasi: new TokContext("${", false),
  925. parenStatement: new TokContext("(", false),
  926. parenExpression: new TokContext("(", true),
  927. template: new TokContext("`", true, true, p => p.readTmplToken()),
  928. functionExpression: new TokContext("function", true),
  929. functionStatement: new TokContext("function", false)
  930. };
  931. types.parenR.updateContext = types.braceR.updateContext = function () {
  932. if (this.state.context.length === 1) {
  933. this.state.exprAllowed = true;
  934. return;
  935. }
  936. let out = this.state.context.pop();
  937. if (out === types$1.braceStatement && this.curContext().token === "function") {
  938. out = this.state.context.pop();
  939. }
  940. this.state.exprAllowed = !out.isExpr;
  941. };
  942. types.name.updateContext = function (prevType) {
  943. let allowed = false;
  944. if (prevType !== types.dot) {
  945. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class || this.state.value === "yield" && this.prodParam.hasYield) {
  946. allowed = true;
  947. }
  948. }
  949. this.state.exprAllowed = allowed;
  950. if (this.state.isIterator) {
  951. this.state.isIterator = false;
  952. }
  953. };
  954. types.braceL.updateContext = function (prevType) {
  955. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  956. this.state.exprAllowed = true;
  957. };
  958. types.dollarBraceL.updateContext = function () {
  959. this.state.context.push(types$1.templateQuasi);
  960. this.state.exprAllowed = true;
  961. };
  962. types.parenL.updateContext = function (prevType) {
  963. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  964. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  965. this.state.exprAllowed = true;
  966. };
  967. types.incDec.updateContext = function () {};
  968. types._function.updateContext = types._class.updateContext = function (prevType) {
  969. if (prevType === types.dot || prevType === types.questionDot) ; else 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)) {
  970. this.state.context.push(types$1.functionExpression);
  971. } else {
  972. this.state.context.push(types$1.functionStatement);
  973. }
  974. this.state.exprAllowed = false;
  975. };
  976. types.backQuote.updateContext = function () {
  977. if (this.curContext() === types$1.template) {
  978. this.state.context.pop();
  979. } else {
  980. this.state.context.push(types$1.template);
  981. }
  982. this.state.exprAllowed = false;
  983. };
  984. types.star.updateContext = function () {
  985. this.state.exprAllowed = false;
  986. };
  987. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  988. let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  989. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  990. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  991. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  992. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  993. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  994. function isInAstralSet(code, set) {
  995. let pos = 0x10000;
  996. for (let i = 0, length = set.length; i < length; i += 2) {
  997. pos += set[i];
  998. if (pos > code) return false;
  999. pos += set[i + 1];
  1000. if (pos >= code) return true;
  1001. }
  1002. return false;
  1003. }
  1004. function isIdentifierStart(code) {
  1005. if (code < 65) return code === 36;
  1006. if (code <= 90) return true;
  1007. if (code < 97) return code === 95;
  1008. if (code <= 122) return true;
  1009. if (code <= 0xffff) {
  1010. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1011. }
  1012. return isInAstralSet(code, astralIdentifierStartCodes);
  1013. }
  1014. function isIdentifierChar(code) {
  1015. if (code < 48) return code === 36;
  1016. if (code < 58) return true;
  1017. if (code < 65) return false;
  1018. if (code <= 90) return true;
  1019. if (code < 97) return code === 95;
  1020. if (code <= 122) return true;
  1021. if (code <= 0xffff) {
  1022. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1023. }
  1024. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1025. }
  1026. const reservedWords = {
  1027. keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  1028. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1029. strictBind: ["eval", "arguments"]
  1030. };
  1031. const keywords$1 = new Set(reservedWords.keyword);
  1032. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1033. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1034. function isReservedWord(word, inModule) {
  1035. return inModule && word === "await" || word === "enum";
  1036. }
  1037. function isStrictReservedWord(word, inModule) {
  1038. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1039. }
  1040. function isStrictBindOnlyReservedWord(word) {
  1041. return reservedWordsStrictBindSet.has(word);
  1042. }
  1043. function isStrictBindReservedWord(word, inModule) {
  1044. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1045. }
  1046. function isKeyword(word) {
  1047. return keywords$1.has(word);
  1048. }
  1049. const keywordRelationalOperator = /^in(stanceof)?$/;
  1050. function isIteratorStart(current, next) {
  1051. return current === 64 && next === 64;
  1052. }
  1053. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1054. const FlowErrors = Object.freeze({
  1055. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1056. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",
  1057. AssignReservedType: "Cannot overwrite reserved type %0",
  1058. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1059. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1060. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1061. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1062. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1063. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1064. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1065. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1066. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1067. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1068. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1069. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1070. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1071. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1072. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",
  1073. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1074. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1075. InexactVariance: "Explicit inexact syntax cannot have variance",
  1076. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1077. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1078. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1079. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1080. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1081. SpreadVariance: "Spread properties cannot have variance",
  1082. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1083. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1084. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1085. UnexpectedReservedType: "Unexpected reserved type %0",
  1086. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1087. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1088. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1089. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1090. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1091. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1092. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1093. UnterminatedFlowComment: "Unterminated flow-comment"
  1094. });
  1095. function isEsModuleType(bodyElement) {
  1096. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1097. }
  1098. function hasTypeImportKind(node) {
  1099. return node.importKind === "type" || node.importKind === "typeof";
  1100. }
  1101. function isMaybeDefaultImport(state) {
  1102. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1103. }
  1104. const exportSuggestions = {
  1105. const: "declare export var",
  1106. let: "declare export var",
  1107. type: "export type",
  1108. interface: "export interface"
  1109. };
  1110. function partition(list, test) {
  1111. const list1 = [];
  1112. const list2 = [];
  1113. for (let i = 0; i < list.length; i++) {
  1114. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1115. }
  1116. return [list1, list2];
  1117. }
  1118. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1119. var flow = (superClass => class extends superClass {
  1120. constructor(options, input) {
  1121. super(options, input);
  1122. this.flowPragma = undefined;
  1123. }
  1124. shouldParseTypes() {
  1125. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1126. }
  1127. shouldParseEnums() {
  1128. return !!this.getPluginOption("flow", "enums");
  1129. }
  1130. finishToken(type, val) {
  1131. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1132. if (this.flowPragma === undefined) {
  1133. this.flowPragma = null;
  1134. }
  1135. }
  1136. return super.finishToken(type, val);
  1137. }
  1138. addComment(comment) {
  1139. if (this.flowPragma === undefined) {
  1140. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1141. if (!matches) ; else if (matches[1] === "flow") {
  1142. this.flowPragma = "flow";
  1143. } else if (matches[1] === "noflow") {
  1144. this.flowPragma = "noflow";
  1145. } else {
  1146. throw new Error("Unexpected flow pragma");
  1147. }
  1148. }
  1149. return super.addComment(comment);
  1150. }
  1151. flowParseTypeInitialiser(tok) {
  1152. const oldInType = this.state.inType;
  1153. this.state.inType = true;
  1154. this.expect(tok || types.colon);
  1155. const type = this.flowParseType();
  1156. this.state.inType = oldInType;
  1157. return type;
  1158. }
  1159. flowParsePredicate() {
  1160. const node = this.startNode();
  1161. const moduloLoc = this.state.startLoc;
  1162. const moduloPos = this.state.start;
  1163. this.expect(types.modulo);
  1164. const checksLoc = this.state.startLoc;
  1165. this.expectContextual("checks");
  1166. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1167. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1168. }
  1169. if (this.eat(types.parenL)) {
  1170. node.value = this.parseExpression();
  1171. this.expect(types.parenR);
  1172. return this.finishNode(node, "DeclaredPredicate");
  1173. } else {
  1174. return this.finishNode(node, "InferredPredicate");
  1175. }
  1176. }
  1177. flowParseTypeAndPredicateInitialiser() {
  1178. const oldInType = this.state.inType;
  1179. this.state.inType = true;
  1180. this.expect(types.colon);
  1181. let type = null;
  1182. let predicate = null;
  1183. if (this.match(types.modulo)) {
  1184. this.state.inType = oldInType;
  1185. predicate = this.flowParsePredicate();
  1186. } else {
  1187. type = this.flowParseType();
  1188. this.state.inType = oldInType;
  1189. if (this.match(types.modulo)) {
  1190. predicate = this.flowParsePredicate();
  1191. }
  1192. }
  1193. return [type, predicate];
  1194. }
  1195. flowParseDeclareClass(node) {
  1196. this.next();
  1197. this.flowParseInterfaceish(node, true);
  1198. return this.finishNode(node, "DeclareClass");
  1199. }
  1200. flowParseDeclareFunction(node) {
  1201. this.next();
  1202. const id = node.id = this.parseIdentifier();
  1203. const typeNode = this.startNode();
  1204. const typeContainer = this.startNode();
  1205. if (this.isRelational("<")) {
  1206. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1207. } else {
  1208. typeNode.typeParameters = null;
  1209. }
  1210. this.expect(types.parenL);
  1211. const tmp = this.flowParseFunctionTypeParams();
  1212. typeNode.params = tmp.params;
  1213. typeNode.rest = tmp.rest;
  1214. this.expect(types.parenR);
  1215. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1216. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1217. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1218. this.resetEndLocation(id);
  1219. this.semicolon();
  1220. return this.finishNode(node, "DeclareFunction");
  1221. }
  1222. flowParseDeclare(node, insideModule) {
  1223. if (this.match(types._class)) {
  1224. return this.flowParseDeclareClass(node);
  1225. } else if (this.match(types._function)) {
  1226. return this.flowParseDeclareFunction(node);
  1227. } else if (this.match(types._var)) {
  1228. return this.flowParseDeclareVariable(node);
  1229. } else if (this.eatContextual("module")) {
  1230. if (this.match(types.dot)) {
  1231. return this.flowParseDeclareModuleExports(node);
  1232. } else {
  1233. if (insideModule) {
  1234. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1235. }
  1236. return this.flowParseDeclareModule(node);
  1237. }
  1238. } else if (this.isContextual("type")) {
  1239. return this.flowParseDeclareTypeAlias(node);
  1240. } else if (this.isContextual("opaque")) {
  1241. return this.flowParseDeclareOpaqueType(node);
  1242. } else if (this.isContextual("interface")) {
  1243. return this.flowParseDeclareInterface(node);
  1244. } else if (this.match(types._export)) {
  1245. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1246. } else {
  1247. throw this.unexpected();
  1248. }
  1249. }
  1250. flowParseDeclareVariable(node) {
  1251. this.next();
  1252. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1253. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1254. this.semicolon();
  1255. return this.finishNode(node, "DeclareVariable");
  1256. }
  1257. flowParseDeclareModule(node) {
  1258. this.scope.enter(SCOPE_OTHER);
  1259. if (this.match(types.string)) {
  1260. node.id = this.parseExprAtom();
  1261. } else {
  1262. node.id = this.parseIdentifier();
  1263. }
  1264. const bodyNode = node.body = this.startNode();
  1265. const body = bodyNode.body = [];
  1266. this.expect(types.braceL);
  1267. while (!this.match(types.braceR)) {
  1268. let bodyNode = this.startNode();
  1269. if (this.match(types._import)) {
  1270. this.next();
  1271. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1272. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1273. }
  1274. this.parseImport(bodyNode);
  1275. } else {
  1276. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1277. bodyNode = this.flowParseDeclare(bodyNode, true);
  1278. }
  1279. body.push(bodyNode);
  1280. }
  1281. this.scope.exit();
  1282. this.expect(types.braceR);
  1283. this.finishNode(bodyNode, "BlockStatement");
  1284. let kind = null;
  1285. let hasModuleExport = false;
  1286. body.forEach(bodyElement => {
  1287. if (isEsModuleType(bodyElement)) {
  1288. if (kind === "CommonJS") {
  1289. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1290. }
  1291. kind = "ES";
  1292. } else if (bodyElement.type === "DeclareModuleExports") {
  1293. if (hasModuleExport) {
  1294. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1295. }
  1296. if (kind === "ES") {
  1297. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1298. }
  1299. kind = "CommonJS";
  1300. hasModuleExport = true;
  1301. }
  1302. });
  1303. node.kind = kind || "CommonJS";
  1304. return this.finishNode(node, "DeclareModule");
  1305. }
  1306. flowParseDeclareExportDeclaration(node, insideModule) {
  1307. this.expect(types._export);
  1308. if (this.eat(types._default)) {
  1309. if (this.match(types._function) || this.match(types._class)) {
  1310. node.declaration = this.flowParseDeclare(this.startNode());
  1311. } else {
  1312. node.declaration = this.flowParseType();
  1313. this.semicolon();
  1314. }
  1315. node.default = true;
  1316. return this.finishNode(node, "DeclareExportDeclaration");
  1317. } else {
  1318. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1319. const label = this.state.value;
  1320. const suggestion = exportSuggestions[label];
  1321. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1322. }
  1323. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1324. node.declaration = this.flowParseDeclare(this.startNode());
  1325. node.default = false;
  1326. return this.finishNode(node, "DeclareExportDeclaration");
  1327. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1328. node = this.parseExport(node);
  1329. if (node.type === "ExportNamedDeclaration") {
  1330. node.type = "ExportDeclaration";
  1331. node.default = false;
  1332. delete node.exportKind;
  1333. }
  1334. node.type = "Declare" + node.type;
  1335. return node;
  1336. }
  1337. }
  1338. throw this.unexpected();
  1339. }
  1340. flowParseDeclareModuleExports(node) {
  1341. this.next();
  1342. this.expectContextual("exports");
  1343. node.typeAnnotation = this.flowParseTypeAnnotation();
  1344. this.semicolon();
  1345. return this.finishNode(node, "DeclareModuleExports");
  1346. }
  1347. flowParseDeclareTypeAlias(node) {
  1348. this.next();
  1349. this.flowParseTypeAlias(node);
  1350. node.type = "DeclareTypeAlias";
  1351. return node;
  1352. }
  1353. flowParseDeclareOpaqueType(node) {
  1354. this.next();
  1355. this.flowParseOpaqueType(node, true);
  1356. node.type = "DeclareOpaqueType";
  1357. return node;
  1358. }
  1359. flowParseDeclareInterface(node) {
  1360. this.next();
  1361. this.flowParseInterfaceish(node);
  1362. return this.finishNode(node, "DeclareInterface");
  1363. }
  1364. flowParseInterfaceish(node, isClass = false) {
  1365. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1366. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1367. if (this.isRelational("<")) {
  1368. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1369. } else {
  1370. node.typeParameters = null;
  1371. }
  1372. node.extends = [];
  1373. node.implements = [];
  1374. node.mixins = [];
  1375. if (this.eat(types._extends)) {
  1376. do {
  1377. node.extends.push(this.flowParseInterfaceExtends());
  1378. } while (!isClass && this.eat(types.comma));
  1379. }
  1380. if (this.isContextual("mixins")) {
  1381. this.next();
  1382. do {
  1383. node.mixins.push(this.flowParseInterfaceExtends());
  1384. } while (this.eat(types.comma));
  1385. }
  1386. if (this.isContextual("implements")) {
  1387. this.next();
  1388. do {
  1389. node.implements.push(this.flowParseInterfaceExtends());
  1390. } while (this.eat(types.comma));
  1391. }
  1392. node.body = this.flowParseObjectType({
  1393. allowStatic: isClass,
  1394. allowExact: false,
  1395. allowSpread: false,
  1396. allowProto: isClass,
  1397. allowInexact: false
  1398. });
  1399. }
  1400. flowParseInterfaceExtends() {
  1401. const node = this.startNode();
  1402. node.id = this.flowParseQualifiedTypeIdentifier();
  1403. if (this.isRelational("<")) {
  1404. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1405. } else {
  1406. node.typeParameters = null;
  1407. }
  1408. return this.finishNode(node, "InterfaceExtends");
  1409. }
  1410. flowParseInterface(node) {
  1411. this.flowParseInterfaceish(node);
  1412. return this.finishNode(node, "InterfaceDeclaration");
  1413. }
  1414. checkNotUnderscore(word) {
  1415. if (word === "_") {
  1416. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1417. }
  1418. }
  1419. checkReservedType(word, startLoc, declaration) {
  1420. if (!reservedTypes.has(word)) return;
  1421. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1422. }
  1423. flowParseRestrictedIdentifier(liberal, declaration) {
  1424. this.checkReservedType(this.state.value, this.state.start, declaration);
  1425. return this.parseIdentifier(liberal);
  1426. }
  1427. flowParseTypeAlias(node) {
  1428. node.id = this.flowParseRestrictedIdentifier(false, true);
  1429. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1430. if (this.isRelational("<")) {
  1431. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1432. } else {
  1433. node.typeParameters = null;
  1434. }
  1435. node.right = this.flowParseTypeInitialiser(types.eq);
  1436. this.semicolon();
  1437. return this.finishNode(node, "TypeAlias");
  1438. }
  1439. flowParseOpaqueType(node, declare) {
  1440. this.expectContextual("type");
  1441. node.id = this.flowParseRestrictedIdentifier(true, true);
  1442. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1443. if (this.isRelational("<")) {
  1444. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1445. } else {
  1446. node.typeParameters = null;
  1447. }
  1448. node.supertype = null;
  1449. if (this.match(types.colon)) {
  1450. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1451. }
  1452. node.impltype = null;
  1453. if (!declare) {
  1454. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1455. }
  1456. this.semicolon();
  1457. return this.finishNode(node, "OpaqueType");
  1458. }
  1459. flowParseTypeParameter(requireDefault = false) {
  1460. const nodeStart = this.state.start;
  1461. const node = this.startNode();
  1462. const variance = this.flowParseVariance();
  1463. const ident = this.flowParseTypeAnnotatableIdentifier();
  1464. node.name = ident.name;
  1465. node.variance = variance;
  1466. node.bound = ident.typeAnnotation;
  1467. if (this.match(types.eq)) {
  1468. this.eat(types.eq);
  1469. node.default = this.flowParseType();
  1470. } else {
  1471. if (requireDefault) {
  1472. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1473. }
  1474. }
  1475. return this.finishNode(node, "TypeParameter");
  1476. }
  1477. flowParseTypeParameterDeclaration() {
  1478. const oldInType = this.state.inType;
  1479. const node = this.startNode();
  1480. node.params = [];
  1481. this.state.inType = true;
  1482. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1483. this.next();
  1484. } else {
  1485. this.unexpected();
  1486. }
  1487. let defaultRequired = false;
  1488. do {
  1489. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1490. node.params.push(typeParameter);
  1491. if (typeParameter.default) {
  1492. defaultRequired = true;
  1493. }
  1494. if (!this.isRelational(">")) {
  1495. this.expect(types.comma);
  1496. }
  1497. } while (!this.isRelational(">"));
  1498. this.expectRelational(">");
  1499. this.state.inType = oldInType;
  1500. return this.finishNode(node, "TypeParameterDeclaration");
  1501. }
  1502. flowParseTypeParameterInstantiation() {
  1503. const node = this.startNode();
  1504. const oldInType = this.state.inType;
  1505. node.params = [];
  1506. this.state.inType = true;
  1507. this.expectRelational("<");
  1508. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1509. this.state.noAnonFunctionType = false;
  1510. while (!this.isRelational(">")) {
  1511. node.params.push(this.flowParseType());
  1512. if (!this.isRelational(">")) {
  1513. this.expect(types.comma);
  1514. }
  1515. }
  1516. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1517. this.expectRelational(">");
  1518. this.state.inType = oldInType;
  1519. return this.finishNode(node, "TypeParameterInstantiation");
  1520. }
  1521. flowParseTypeParameterInstantiationCallOrNew() {
  1522. const node = this.startNode();
  1523. const oldInType = this.state.inType;
  1524. node.params = [];
  1525. this.state.inType = true;
  1526. this.expectRelational("<");
  1527. while (!this.isRelational(">")) {
  1528. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1529. if (!this.isRelational(">")) {
  1530. this.expect(types.comma);
  1531. }
  1532. }
  1533. this.expectRelational(">");
  1534. this.state.inType = oldInType;
  1535. return this.finishNode(node, "TypeParameterInstantiation");
  1536. }
  1537. flowParseInterfaceType() {
  1538. const node = this.startNode();
  1539. this.expectContextual("interface");
  1540. node.extends = [];
  1541. if (this.eat(types._extends)) {
  1542. do {
  1543. node.extends.push(this.flowParseInterfaceExtends());
  1544. } while (this.eat(types.comma));
  1545. }
  1546. node.body = this.flowParseObjectType({
  1547. allowStatic: false,
  1548. allowExact: false,
  1549. allowSpread: false,
  1550. allowProto: false,
  1551. allowInexact: false
  1552. });
  1553. return this.finishNode(node, "InterfaceTypeAnnotation");
  1554. }
  1555. flowParseObjectPropertyKey() {
  1556. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1557. }
  1558. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1559. node.static = isStatic;
  1560. if (this.lookahead().type === types.colon) {
  1561. node.id = this.flowParseObjectPropertyKey();
  1562. node.key = this.flowParseTypeInitialiser();
  1563. } else {
  1564. node.id = null;
  1565. node.key = this.flowParseType();
  1566. }
  1567. this.expect(types.bracketR);
  1568. node.value = this.flowParseTypeInitialiser();
  1569. node.variance = variance;
  1570. return this.finishNode(node, "ObjectTypeIndexer");
  1571. }
  1572. flowParseObjectTypeInternalSlot(node, isStatic) {
  1573. node.static = isStatic;
  1574. node.id = this.flowParseObjectPropertyKey();
  1575. this.expect(types.bracketR);
  1576. this.expect(types.bracketR);
  1577. if (this.isRelational("<") || this.match(types.parenL)) {
  1578. node.method = true;
  1579. node.optional = false;
  1580. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1581. } else {
  1582. node.method = false;
  1583. if (this.eat(types.question)) {
  1584. node.optional = true;
  1585. }
  1586. node.value = this.flowParseTypeInitialiser();
  1587. }
  1588. return this.finishNode(node, "ObjectTypeInternalSlot");
  1589. }
  1590. flowParseObjectTypeMethodish(node) {
  1591. node.params = [];
  1592. node.rest = null;
  1593. node.typeParameters = null;
  1594. if (this.isRelational("<")) {
  1595. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1596. }
  1597. this.expect(types.parenL);
  1598. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1599. node.params.push(this.flowParseFunctionTypeParam());
  1600. if (!this.match(types.parenR)) {
  1601. this.expect(types.comma);
  1602. }
  1603. }
  1604. if (this.eat(types.ellipsis)) {
  1605. node.rest = this.flowParseFunctionTypeParam();
  1606. }
  1607. this.expect(types.parenR);
  1608. node.returnType = this.flowParseTypeInitialiser();
  1609. return this.finishNode(node, "FunctionTypeAnnotation");
  1610. }
  1611. flowParseObjectTypeCallProperty(node, isStatic) {
  1612. const valueNode = this.startNode();
  1613. node.static = isStatic;
  1614. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1615. return this.finishNode(node, "ObjectTypeCallProperty");
  1616. }
  1617. flowParseObjectType({
  1618. allowStatic,
  1619. allowExact,
  1620. allowSpread,
  1621. allowProto,
  1622. allowInexact
  1623. }) {
  1624. const oldInType = this.state.inType;
  1625. this.state.inType = true;
  1626. const nodeStart = this.startNode();
  1627. nodeStart.callProperties = [];
  1628. nodeStart.properties = [];
  1629. nodeStart.indexers = [];
  1630. nodeStart.internalSlots = [];
  1631. let endDelim;
  1632. let exact;
  1633. let inexact = false;
  1634. if (allowExact && this.match(types.braceBarL)) {
  1635. this.expect(types.braceBarL);
  1636. endDelim = types.braceBarR;
  1637. exact = true;
  1638. } else {
  1639. this.expect(types.braceL);
  1640. endDelim = types.braceR;
  1641. exact = false;
  1642. }
  1643. nodeStart.exact = exact;
  1644. while (!this.match(endDelim)) {
  1645. let isStatic = false;
  1646. let protoStart = null;
  1647. let inexactStart = null;
  1648. const node = this.startNode();
  1649. if (allowProto && this.isContextual("proto")) {
  1650. const lookahead = this.lookahead();
  1651. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1652. this.next();
  1653. protoStart = this.state.start;
  1654. allowStatic = false;
  1655. }
  1656. }
  1657. if (allowStatic && this.isContextual("static")) {
  1658. const lookahead = this.lookahead();
  1659. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1660. this.next();
  1661. isStatic = true;
  1662. }
  1663. }
  1664. const variance = this.flowParseVariance();
  1665. if (this.eat(types.bracketL)) {
  1666. if (protoStart != null) {
  1667. this.unexpected(protoStart);
  1668. }
  1669. if (this.eat(types.bracketL)) {
  1670. if (variance) {
  1671. this.unexpected(variance.start);
  1672. }
  1673. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1674. } else {
  1675. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1676. }
  1677. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1678. if (protoStart != null) {
  1679. this.unexpected(protoStart);
  1680. }
  1681. if (variance) {
  1682. this.unexpected(variance.start);
  1683. }
  1684. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1685. } else {
  1686. let kind = "init";
  1687. if (this.isContextual("get") || this.isContextual("set")) {
  1688. const lookahead = this.lookahead();
  1689. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1690. kind = this.state.value;
  1691. this.next();
  1692. }
  1693. }
  1694. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1695. if (propOrInexact === null) {
  1696. inexact = true;
  1697. inexactStart = this.state.lastTokStart;
  1698. } else {
  1699. nodeStart.properties.push(propOrInexact);
  1700. }
  1701. }
  1702. this.flowObjectTypeSemicolon();
  1703. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1704. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  1705. }
  1706. }
  1707. this.expect(endDelim);
  1708. if (allowSpread) {
  1709. nodeStart.inexact = inexact;
  1710. }
  1711. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1712. this.state.inType = oldInType;
  1713. return out;
  1714. }
  1715. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1716. if (this.eat(types.ellipsis)) {
  1717. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1718. if (isInexactToken) {
  1719. if (!allowSpread) {
  1720. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  1721. } else if (!allowInexact) {
  1722. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  1723. }
  1724. if (variance) {
  1725. this.raise(variance.start, FlowErrors.InexactVariance);
  1726. }
  1727. return null;
  1728. }
  1729. if (!allowSpread) {
  1730. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  1731. }
  1732. if (protoStart != null) {
  1733. this.unexpected(protoStart);
  1734. }
  1735. if (variance) {
  1736. this.raise(variance.start, FlowErrors.SpreadVariance);
  1737. }
  1738. node.argument = this.flowParseType();
  1739. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1740. } else {
  1741. node.key = this.flowParseObjectPropertyKey();
  1742. node.static = isStatic;
  1743. node.proto = protoStart != null;
  1744. node.kind = kind;
  1745. let optional = false;
  1746. if (this.isRelational("<") || this.match(types.parenL)) {
  1747. node.method = true;
  1748. if (protoStart != null) {
  1749. this.unexpected(protoStart);
  1750. }
  1751. if (variance) {
  1752. this.unexpected(variance.start);
  1753. }
  1754. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1755. if (kind === "get" || kind === "set") {
  1756. this.flowCheckGetterSetterParams(node);
  1757. }
  1758. } else {
  1759. if (kind !== "init") this.unexpected();
  1760. node.method = false;
  1761. if (this.eat(types.question)) {
  1762. optional = true;
  1763. }
  1764. node.value = this.flowParseTypeInitialiser();
  1765. node.variance = variance;
  1766. }
  1767. node.optional = optional;
  1768. return this.finishNode(node, "ObjectTypeProperty");
  1769. }
  1770. }
  1771. flowCheckGetterSetterParams(property) {
  1772. const paramCount = property.kind === "get" ? 0 : 1;
  1773. const start = property.start;
  1774. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1775. if (length !== paramCount) {
  1776. if (property.kind === "get") {
  1777. this.raise(start, Errors.BadGetterArity);
  1778. } else {
  1779. this.raise(start, Errors.BadSetterArity);
  1780. }
  1781. }
  1782. if (property.kind === "set" && property.value.rest) {
  1783. this.raise(start, Errors.BadSetterRestParameter);
  1784. }
  1785. }
  1786. flowObjectTypeSemicolon() {
  1787. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1788. this.unexpected();
  1789. }
  1790. }
  1791. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1792. startPos = startPos || this.state.start;
  1793. startLoc = startLoc || this.state.startLoc;
  1794. let node = id || this.flowParseRestrictedIdentifier(true);
  1795. while (this.eat(types.dot)) {
  1796. const node2 = this.startNodeAt(startPos, startLoc);
  1797. node2.qualification = node;
  1798. node2.id = this.flowParseRestrictedIdentifier(true);
  1799. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1800. }
  1801. return node;
  1802. }
  1803. flowParseGenericType(startPos, startLoc, id) {
  1804. const node = this.startNodeAt(startPos, startLoc);
  1805. node.typeParameters = null;
  1806. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1807. if (this.isRelational("<")) {
  1808. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1809. }
  1810. return this.finishNode(node, "GenericTypeAnnotation");
  1811. }
  1812. flowParseTypeofType() {
  1813. const node = this.startNode();
  1814. this.expect(types._typeof);
  1815. node.argument = this.flowParsePrimaryType();
  1816. return this.finishNode(node, "TypeofTypeAnnotation");
  1817. }
  1818. flowParseTupleType() {
  1819. const node = this.startNode();
  1820. node.types = [];
  1821. this.expect(types.bracketL);
  1822. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1823. node.types.push(this.flowParseType());
  1824. if (this.match(types.bracketR)) break;
  1825. this.expect(types.comma);
  1826. }
  1827. this.expect(types.bracketR);
  1828. return this.finishNode(node, "TupleTypeAnnotation");
  1829. }
  1830. flowParseFunctionTypeParam() {
  1831. let name = null;
  1832. let optional = false;
  1833. let typeAnnotation = null;
  1834. const node = this.startNode();
  1835. const lh = this.lookahead();
  1836. if (lh.type === types.colon || lh.type === types.question) {
  1837. name = this.parseIdentifier();
  1838. if (this.eat(types.question)) {
  1839. optional = true;
  1840. }
  1841. typeAnnotation = this.flowParseTypeInitialiser();
  1842. } else {
  1843. typeAnnotation = this.flowParseType();
  1844. }
  1845. node.name = name;
  1846. node.optional = optional;
  1847. node.typeAnnotation = typeAnnotation;
  1848. return this.finishNode(node, "FunctionTypeParam");
  1849. }
  1850. reinterpretTypeAsFunctionTypeParam(type) {
  1851. const node = this.startNodeAt(type.start, type.loc.start);
  1852. node.name = null;
  1853. node.optional = false;
  1854. node.typeAnnotation = type;
  1855. return this.finishNode(node, "FunctionTypeParam");
  1856. }
  1857. flowParseFunctionTypeParams(params = []) {
  1858. let rest = null;
  1859. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1860. params.push(this.flowParseFunctionTypeParam());
  1861. if (!this.match(types.parenR)) {
  1862. this.expect(types.comma);
  1863. }
  1864. }
  1865. if (this.eat(types.ellipsis)) {
  1866. rest = this.flowParseFunctionTypeParam();
  1867. }
  1868. return {
  1869. params,
  1870. rest
  1871. };
  1872. }
  1873. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1874. switch (id.name) {
  1875. case "any":
  1876. return this.finishNode(node, "AnyTypeAnnotation");
  1877. case "bool":
  1878. case "boolean":
  1879. return this.finishNode(node, "BooleanTypeAnnotation");
  1880. case "mixed":
  1881. return this.finishNode(node, "MixedTypeAnnotation");
  1882. case "empty":
  1883. return this.finishNode(node, "EmptyTypeAnnotation");
  1884. case "number":
  1885. return this.finishNode(node, "NumberTypeAnnotation");
  1886. case "string":
  1887. return this.finishNode(node, "StringTypeAnnotation");
  1888. case "symbol":
  1889. return this.finishNode(node, "SymbolTypeAnnotation");
  1890. default:
  1891. this.checkNotUnderscore(id.name);
  1892. return this.flowParseGenericType(startPos, startLoc, id);
  1893. }
  1894. }
  1895. flowParsePrimaryType() {
  1896. const startPos = this.state.start;
  1897. const startLoc = this.state.startLoc;
  1898. const node = this.startNode();
  1899. let tmp;
  1900. let type;
  1901. let isGroupedType = false;
  1902. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1903. switch (this.state.type) {
  1904. case types.name:
  1905. if (this.isContextual("interface")) {
  1906. return this.flowParseInterfaceType();
  1907. }
  1908. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1909. case types.braceL:
  1910. return this.flowParseObjectType({
  1911. allowStatic: false,
  1912. allowExact: false,
  1913. allowSpread: true,
  1914. allowProto: false,
  1915. allowInexact: true
  1916. });
  1917. case types.braceBarL:
  1918. return this.flowParseObjectType({
  1919. allowStatic: false,
  1920. allowExact: true,
  1921. allowSpread: true,
  1922. allowProto: false,
  1923. allowInexact: false
  1924. });
  1925. case types.bracketL:
  1926. this.state.noAnonFunctionType = false;
  1927. type = this.flowParseTupleType();
  1928. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1929. return type;
  1930. case types.relational:
  1931. if (this.state.value === "<") {
  1932. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1933. this.expect(types.parenL);
  1934. tmp = this.flowParseFunctionTypeParams();
  1935. node.params = tmp.params;
  1936. node.rest = tmp.rest;
  1937. this.expect(types.parenR);
  1938. this.expect(types.arrow);
  1939. node.returnType = this.flowParseType();
  1940. return this.finishNode(node, "FunctionTypeAnnotation");
  1941. }
  1942. break;
  1943. case types.parenL:
  1944. this.next();
  1945. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1946. if (this.match(types.name)) {
  1947. const token = this.lookahead().type;
  1948. isGroupedType = token !== types.question && token !== types.colon;
  1949. } else {
  1950. isGroupedType = true;
  1951. }
  1952. }
  1953. if (isGroupedType) {
  1954. this.state.noAnonFunctionType = false;
  1955. type = this.flowParseType();
  1956. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1957. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  1958. this.expect(types.parenR);
  1959. return type;
  1960. } else {
  1961. this.eat(types.comma);
  1962. }
  1963. }
  1964. if (type) {
  1965. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  1966. } else {
  1967. tmp = this.flowParseFunctionTypeParams();
  1968. }
  1969. node.params = tmp.params;
  1970. node.rest = tmp.rest;
  1971. this.expect(types.parenR);
  1972. this.expect(types.arrow);
  1973. node.returnType = this.flowParseType();
  1974. node.typeParameters = null;
  1975. return this.finishNode(node, "FunctionTypeAnnotation");
  1976. case types.string:
  1977. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  1978. case types._true:
  1979. case types._false:
  1980. node.value = this.match(types._true);
  1981. this.next();
  1982. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  1983. case types.plusMin:
  1984. if (this.state.value === "-") {
  1985. this.next();
  1986. if (this.match(types.num)) {
  1987. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  1988. }
  1989. if (this.match(types.bigint)) {
  1990. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  1991. }
  1992. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  1993. }
  1994. throw this.unexpected();
  1995. case types.num:
  1996. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  1997. case types.bigint:
  1998. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  1999. case types._void:
  2000. this.next();
  2001. return this.finishNode(node, "VoidTypeAnnotation");
  2002. case types._null:
  2003. this.next();
  2004. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2005. case types._this:
  2006. this.next();
  2007. return this.finishNode(node, "ThisTypeAnnotation");
  2008. case types.star:
  2009. this.next();
  2010. return this.finishNode(node, "ExistsTypeAnnotation");
  2011. default:
  2012. if (this.state.type.keyword === "typeof") {
  2013. return this.flowParseTypeofType();
  2014. } else if (this.state.type.keyword) {
  2015. const label = this.state.type.label;
  2016. this.next();
  2017. return super.createIdentifier(node, label);
  2018. }
  2019. }
  2020. throw this.unexpected();
  2021. }
  2022. flowParsePostfixType() {
  2023. const startPos = this.state.start,
  2024. startLoc = this.state.startLoc;
  2025. let type = this.flowParsePrimaryType();
  2026. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2027. const node = this.startNodeAt(startPos, startLoc);
  2028. node.elementType = type;
  2029. this.expect(types.bracketL);
  2030. this.expect(types.bracketR);
  2031. type = this.finishNode(node, "ArrayTypeAnnotation");
  2032. }
  2033. return type;
  2034. }
  2035. flowParsePrefixType() {
  2036. const node = this.startNode();
  2037. if (this.eat(types.question)) {
  2038. node.typeAnnotation = this.flowParsePrefixType();
  2039. return this.finishNode(node, "NullableTypeAnnotation");
  2040. } else {
  2041. return this.flowParsePostfixType();
  2042. }
  2043. }
  2044. flowParseAnonFunctionWithoutParens() {
  2045. const param = this.flowParsePrefixType();
  2046. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2047. const node = this.startNodeAt(param.start, param.loc.start);
  2048. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2049. node.rest = null;
  2050. node.returnType = this.flowParseType();
  2051. node.typeParameters = null;
  2052. return this.finishNode(node, "FunctionTypeAnnotation");
  2053. }
  2054. return param;
  2055. }
  2056. flowParseIntersectionType() {
  2057. const node = this.startNode();
  2058. this.eat(types.bitwiseAND);
  2059. const type = this.flowParseAnonFunctionWithoutParens();
  2060. node.types = [type];
  2061. while (this.eat(types.bitwiseAND)) {
  2062. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2063. }
  2064. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2065. }
  2066. flowParseUnionType() {
  2067. const node = this.startNode();
  2068. this.eat(types.bitwiseOR);
  2069. const type = this.flowParseIntersectionType();
  2070. node.types = [type];
  2071. while (this.eat(types.bitwiseOR)) {
  2072. node.types.push(this.flowParseIntersectionType());
  2073. }
  2074. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2075. }
  2076. flowParseType() {
  2077. const oldInType = this.state.inType;
  2078. this.state.inType = true;
  2079. const type = this.flowParseUnionType();
  2080. this.state.inType = oldInType;
  2081. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2082. return type;
  2083. }
  2084. flowParseTypeOrImplicitInstantiation() {
  2085. if (this.state.type === types.name && this.state.value === "_") {
  2086. const startPos = this.state.start;
  2087. const startLoc = this.state.startLoc;
  2088. const node = this.parseIdentifier();
  2089. return this.flowParseGenericType(startPos, startLoc, node);
  2090. } else {
  2091. return this.flowParseType();
  2092. }
  2093. }
  2094. flowParseTypeAnnotation() {
  2095. const node = this.startNode();
  2096. node.typeAnnotation = this.flowParseTypeInitialiser();
  2097. return this.finishNode(node, "TypeAnnotation");
  2098. }
  2099. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2100. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2101. if (this.match(types.colon)) {
  2102. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2103. this.resetEndLocation(ident);
  2104. }
  2105. return ident;
  2106. }
  2107. typeCastToParameter(node) {
  2108. node.expression.typeAnnotation = node.typeAnnotation;
  2109. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2110. return node.expression;
  2111. }
  2112. flowParseVariance() {
  2113. let variance = null;
  2114. if (this.match(types.plusMin)) {
  2115. variance = this.startNode();
  2116. if (this.state.value === "+") {
  2117. variance.kind = "plus";
  2118. } else {
  2119. variance.kind = "minus";
  2120. }
  2121. this.next();
  2122. this.finishNode(variance, "Variance");
  2123. }
  2124. return variance;
  2125. }
  2126. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2127. if (allowExpressionBody) {
  2128. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2129. }
  2130. return super.parseFunctionBody(node, false, isMethod);
  2131. }
  2132. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2133. if (this.match(types.colon)) {
  2134. const typeNode = this.startNode();
  2135. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2136. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2137. }
  2138. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2139. }
  2140. parseStatement(context, topLevel) {
  2141. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2142. const node = this.startNode();
  2143. this.next();
  2144. return this.flowParseInterface(node);
  2145. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2146. const node = this.startNode();
  2147. this.next();
  2148. return this.flowParseEnumDeclaration(node);
  2149. } else {
  2150. const stmt = super.parseStatement(context, topLevel);
  2151. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2152. this.flowPragma = null;
  2153. }
  2154. return stmt;
  2155. }
  2156. }
  2157. parseExpressionStatement(node, expr) {
  2158. if (expr.type === "Identifier") {
  2159. if (expr.name === "declare") {
  2160. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2161. return this.flowParseDeclare(node);
  2162. }
  2163. } else if (this.match(types.name)) {
  2164. if (expr.name === "interface") {
  2165. return this.flowParseInterface(node);
  2166. } else if (expr.name === "type") {
  2167. return this.flowParseTypeAlias(node);
  2168. } else if (expr.name === "opaque") {
  2169. return this.flowParseOpaqueType(node, false);
  2170. }
  2171. }
  2172. }
  2173. return super.parseExpressionStatement(node, expr);
  2174. }
  2175. shouldParseExportDeclaration() {
  2176. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2177. }
  2178. isExportDefaultSpecifier() {
  2179. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2180. return false;
  2181. }
  2182. return super.isExportDefaultSpecifier();
  2183. }
  2184. parseExportDefaultExpression() {
  2185. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2186. const node = this.startNode();
  2187. this.next();
  2188. return this.flowParseEnumDeclaration(node);
  2189. }
  2190. return super.parseExportDefaultExpression();
  2191. }
  2192. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  2193. if (!this.match(types.question)) return expr;
  2194. if (refNeedsArrowPos) {
  2195. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  2196. if (!result.node) {
  2197. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2198. return expr;
  2199. }
  2200. if (result.error) this.state = result.failState;
  2201. return result.node;
  2202. }
  2203. this.expect(types.question);
  2204. const state = this.state.clone();
  2205. const originalNoArrowAt = this.state.noArrowAt;
  2206. const node = this.startNodeAt(startPos, startLoc);
  2207. let {
  2208. consequent,
  2209. failed
  2210. } = this.tryParseConditionalConsequent();
  2211. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2212. if (failed || invalid.length > 0) {
  2213. const noArrowAt = [...originalNoArrowAt];
  2214. if (invalid.length > 0) {
  2215. this.state = state;
  2216. this.state.noArrowAt = noArrowAt;
  2217. for (let i = 0; i < invalid.length; i++) {
  2218. noArrowAt.push(invalid[i].start);
  2219. }
  2220. ({
  2221. consequent,
  2222. failed
  2223. } = this.tryParseConditionalConsequent());
  2224. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2225. }
  2226. if (failed && valid.length > 1) {
  2227. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2228. }
  2229. if (failed && valid.length === 1) {
  2230. this.state = state;
  2231. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2232. ({
  2233. consequent,
  2234. failed
  2235. } = this.tryParseConditionalConsequent());
  2236. }
  2237. }
  2238. this.getArrowLikeExpressions(consequent, true);
  2239. this.state.noArrowAt = originalNoArrowAt;
  2240. this.expect(types.colon);
  2241. node.test = expr;
  2242. node.consequent = consequent;
  2243. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(noIn, undefined, undefined, undefined));
  2244. return this.finishNode(node, "ConditionalExpression");
  2245. }
  2246. tryParseConditionalConsequent() {
  2247. this.state.noArrowParamsConversionAt.push(this.state.start);
  2248. const consequent = this.parseMaybeAssign();
  2249. const failed = !this.match(types.colon);
  2250. this.state.noArrowParamsConversionAt.pop();
  2251. return {
  2252. consequent,
  2253. failed
  2254. };
  2255. }
  2256. getArrowLikeExpressions(node, disallowInvalid) {
  2257. const stack = [node];
  2258. const arrows = [];
  2259. while (stack.length !== 0) {
  2260. const node = stack.pop();
  2261. if (node.type === "ArrowFunctionExpression") {
  2262. if (node.typeParameters || !node.returnType) {
  2263. this.finishArrowValidation(node);
  2264. } else {
  2265. arrows.push(node);
  2266. }
  2267. stack.push(node.body);
  2268. } else if (node.type === "ConditionalExpression") {
  2269. stack.push(node.consequent);
  2270. stack.push(node.alternate);
  2271. }
  2272. }
  2273. if (disallowInvalid) {
  2274. arrows.forEach(node => this.finishArrowValidation(node));
  2275. return [arrows, []];
  2276. }
  2277. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2278. }
  2279. finishArrowValidation(node) {
  2280. var _node$extra;
  2281. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma);
  2282. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2283. super.checkParams(node, false, true);
  2284. this.scope.exit();
  2285. }
  2286. forwardNoArrowParamsConversionAt(node, parse) {
  2287. let result;
  2288. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2289. this.state.noArrowParamsConversionAt.push(this.state.start);
  2290. result = parse();
  2291. this.state.noArrowParamsConversionAt.pop();
  2292. } else {
  2293. result = parse();
  2294. }
  2295. return result;
  2296. }
  2297. parseParenItem(node, startPos, startLoc) {
  2298. node = super.parseParenItem(node, startPos, startLoc);
  2299. if (this.eat(types.question)) {
  2300. node.optional = true;
  2301. this.resetEndLocation(node);
  2302. }
  2303. if (this.match(types.colon)) {
  2304. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2305. typeCastNode.expression = node;
  2306. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2307. return this.finishNode(typeCastNode, "TypeCastExpression");
  2308. }
  2309. return node;
  2310. }
  2311. assertModuleNodeAllowed(node) {
  2312. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2313. return;
  2314. }
  2315. super.assertModuleNodeAllowed(node);
  2316. }
  2317. parseExport(node) {
  2318. const decl = super.parseExport(node);
  2319. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2320. decl.exportKind = decl.exportKind || "value";
  2321. }
  2322. return decl;
  2323. }
  2324. parseExportDeclaration(node) {
  2325. if (this.isContextual("type")) {
  2326. node.exportKind = "type";
  2327. const declarationNode = this.startNode();
  2328. this.next();
  2329. if (this.match(types.braceL)) {
  2330. node.specifiers = this.parseExportSpecifiers();
  2331. this.parseExportFrom(node);
  2332. return null;
  2333. } else {
  2334. return this.flowParseTypeAlias(declarationNode);
  2335. }
  2336. } else if (this.isContextual("opaque")) {
  2337. node.exportKind = "type";
  2338. const declarationNode = this.startNode();
  2339. this.next();
  2340. return this.flowParseOpaqueType(declarationNode, false);
  2341. } else if (this.isContextual("interface")) {
  2342. node.exportKind = "type";
  2343. const declarationNode = this.startNode();
  2344. this.next();
  2345. return this.flowParseInterface(declarationNode);
  2346. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2347. node.exportKind = "value";
  2348. const declarationNode = this.startNode();
  2349. this.next();
  2350. return this.flowParseEnumDeclaration(declarationNode);
  2351. } else {
  2352. return super.parseExportDeclaration(node);
  2353. }
  2354. }
  2355. eatExportStar(node) {
  2356. if (super.eatExportStar(...arguments)) return true;
  2357. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2358. node.exportKind = "type";
  2359. this.next();
  2360. this.next();
  2361. return true;
  2362. }
  2363. return false;
  2364. }
  2365. maybeParseExportNamespaceSpecifier(node) {
  2366. const pos = this.state.start;
  2367. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2368. if (hasNamespace && node.exportKind === "type") {
  2369. this.unexpected(pos);
  2370. }
  2371. return hasNamespace;
  2372. }
  2373. parseClassId(node, isStatement, optionalId) {
  2374. super.parseClassId(node, isStatement, optionalId);
  2375. if (this.isRelational("<")) {
  2376. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2377. }
  2378. }
  2379. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  2380. const pos = this.state.start;
  2381. if (this.isContextual("declare")) {
  2382. if (this.parseClassMemberFromModifier(classBody, member)) {
  2383. return;
  2384. }
  2385. member.declare = true;
  2386. }
  2387. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  2388. if (member.declare) {
  2389. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  2390. this.raise(pos, FlowErrors.DeclareClassElement);
  2391. } else if (member.value) {
  2392. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2393. }
  2394. }
  2395. }
  2396. getTokenFromCode(code) {
  2397. const next = this.input.charCodeAt(this.state.pos + 1);
  2398. if (code === 123 && next === 124) {
  2399. return this.finishOp(types.braceBarL, 2);
  2400. } else if (this.state.inType && (code === 62 || code === 60)) {
  2401. return this.finishOp(types.relational, 1);
  2402. } else if (isIteratorStart(code, next)) {
  2403. this.state.isIterator = true;
  2404. return super.readWord();
  2405. } else {
  2406. return super.getTokenFromCode(code);
  2407. }
  2408. }
  2409. isAssignable(node, isBinding) {
  2410. switch (node.type) {
  2411. case "Identifier":
  2412. case "ObjectPattern":
  2413. case "ArrayPattern":
  2414. case "AssignmentPattern":
  2415. return true;
  2416. case "ObjectExpression":
  2417. {
  2418. const last = node.properties.length - 1;
  2419. return node.properties.every((prop, i) => {
  2420. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2421. });
  2422. }
  2423. case "ObjectProperty":
  2424. return this.isAssignable(node.value);
  2425. case "SpreadElement":
  2426. return this.isAssignable(node.argument);
  2427. case "ArrayExpression":
  2428. return node.elements.every(element => this.isAssignable(element));
  2429. case "AssignmentExpression":
  2430. return node.operator === "=";
  2431. case "ParenthesizedExpression":
  2432. case "TypeCastExpression":
  2433. return this.isAssignable(node.expression);
  2434. case "MemberExpression":
  2435. case "OptionalMemberExpression":
  2436. return !isBinding;
  2437. default:
  2438. return false;
  2439. }
  2440. }
  2441. toAssignable(node) {
  2442. if (node.type === "TypeCastExpression") {
  2443. return super.toAssignable(this.typeCastToParameter(node));
  2444. } else {
  2445. return super.toAssignable(node);
  2446. }
  2447. }
  2448. toAssignableList(exprList, trailingCommaPos) {
  2449. for (let i = 0; i < exprList.length; i++) {
  2450. const expr = exprList[i];
  2451. if (expr && expr.type === "TypeCastExpression") {
  2452. exprList[i] = this.typeCastToParameter(expr);
  2453. }
  2454. }
  2455. return super.toAssignableList(exprList, trailingCommaPos);
  2456. }
  2457. toReferencedList(exprList, isParenthesizedExpr) {
  2458. for (let i = 0; i < exprList.length; i++) {
  2459. const expr = exprList[i];
  2460. if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2461. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2462. }
  2463. }
  2464. return exprList;
  2465. }
  2466. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  2467. if (expr.type !== "TypeCastExpression") {
  2468. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  2469. }
  2470. }
  2471. parseClassProperty(node) {
  2472. if (this.match(types.colon)) {
  2473. node.typeAnnotation = this.flowParseTypeAnnotation();
  2474. }
  2475. return super.parseClassProperty(node);
  2476. }
  2477. parseClassPrivateProperty(node) {
  2478. if (this.match(types.colon)) {
  2479. node.typeAnnotation = this.flowParseTypeAnnotation();
  2480. }
  2481. return super.parseClassPrivateProperty(node);
  2482. }
  2483. isClassMethod() {
  2484. return this.isRelational("<") || super.isClassMethod();
  2485. }
  2486. isClassProperty() {
  2487. return this.match(types.colon) || super.isClassProperty();
  2488. }
  2489. isNonstaticConstructor(method) {
  2490. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2491. }
  2492. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2493. if (method.variance) {
  2494. this.unexpected(method.variance.start);
  2495. }
  2496. delete method.variance;
  2497. if (this.isRelational("<")) {
  2498. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2499. }
  2500. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2501. }
  2502. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2503. if (method.variance) {
  2504. this.unexpected(method.variance.start);
  2505. }
  2506. delete method.variance;
  2507. if (this.isRelational("<")) {
  2508. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2509. }
  2510. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2511. }
  2512. parseClassSuper(node) {
  2513. super.parseClassSuper(node);
  2514. if (node.superClass && this.isRelational("<")) {
  2515. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2516. }
  2517. if (this.isContextual("implements")) {
  2518. this.next();
  2519. const implemented = node.implements = [];
  2520. do {
  2521. const node = this.startNode();
  2522. node.id = this.flowParseRestrictedIdentifier(true);
  2523. if (this.isRelational("<")) {
  2524. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2525. } else {
  2526. node.typeParameters = null;
  2527. }
  2528. implemented.push(this.finishNode(node, "ClassImplements"));
  2529. } while (this.eat(types.comma));
  2530. }
  2531. }
  2532. parsePropertyName(node, isPrivateNameAllowed) {
  2533. const variance = this.flowParseVariance();
  2534. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2535. node.variance = variance;
  2536. return key;
  2537. }
  2538. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  2539. if (prop.variance) {
  2540. this.unexpected(prop.variance.start);
  2541. }
  2542. delete prop.variance;
  2543. let typeParameters;
  2544. if (this.isRelational("<")) {
  2545. typeParameters = this.flowParseTypeParameterDeclaration();
  2546. if (!this.match(types.parenL)) this.unexpected();
  2547. }
  2548. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  2549. if (typeParameters) {
  2550. (prop.value || prop).typeParameters = typeParameters;
  2551. }
  2552. }
  2553. parseAssignableListItemTypes(param) {
  2554. if (this.eat(types.question)) {
  2555. if (param.type !== "Identifier") {
  2556. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  2557. }
  2558. param.optional = true;
  2559. }
  2560. if (this.match(types.colon)) {
  2561. param.typeAnnotation = this.flowParseTypeAnnotation();
  2562. }
  2563. this.resetEndLocation(param);
  2564. return param;
  2565. }
  2566. parseMaybeDefault(startPos, startLoc, left) {
  2567. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2568. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2569. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  2570. }
  2571. return node;
  2572. }
  2573. shouldParseDefaultImport(node) {
  2574. if (!hasTypeImportKind(node)) {
  2575. return super.shouldParseDefaultImport(node);
  2576. }
  2577. return isMaybeDefaultImport(this.state);
  2578. }
  2579. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2580. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2581. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  2582. node.specifiers.push(this.finishNode(specifier, type));
  2583. }
  2584. maybeParseDefaultImportSpecifier(node) {
  2585. node.importKind = "value";
  2586. let kind = null;
  2587. if (this.match(types._typeof)) {
  2588. kind = "typeof";
  2589. } else if (this.isContextual("type")) {
  2590. kind = "type";
  2591. }
  2592. if (kind) {
  2593. const lh = this.lookahead();
  2594. if (kind === "type" && lh.type === types.star) {
  2595. this.unexpected(lh.start);
  2596. }
  2597. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2598. this.next();
  2599. node.importKind = kind;
  2600. }
  2601. }
  2602. return super.maybeParseDefaultImportSpecifier(node);
  2603. }
  2604. parseImportSpecifier(node) {
  2605. const specifier = this.startNode();
  2606. const firstIdentLoc = this.state.start;
  2607. const firstIdent = this.parseIdentifier(true);
  2608. let specifierTypeKind = null;
  2609. if (firstIdent.name === "type") {
  2610. specifierTypeKind = "type";
  2611. } else if (firstIdent.name === "typeof") {
  2612. specifierTypeKind = "typeof";
  2613. }
  2614. let isBinding = false;
  2615. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2616. const as_ident = this.parseIdentifier(true);
  2617. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2618. specifier.imported = as_ident;
  2619. specifier.importKind = specifierTypeKind;
  2620. specifier.local = as_ident.__clone();
  2621. } else {
  2622. specifier.imported = firstIdent;
  2623. specifier.importKind = null;
  2624. specifier.local = this.parseIdentifier();
  2625. }
  2626. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2627. specifier.imported = this.parseIdentifier(true);
  2628. specifier.importKind = specifierTypeKind;
  2629. if (this.eatContextual("as")) {
  2630. specifier.local = this.parseIdentifier();
  2631. } else {
  2632. isBinding = true;
  2633. specifier.local = specifier.imported.__clone();
  2634. }
  2635. } else {
  2636. isBinding = true;
  2637. specifier.imported = firstIdent;
  2638. specifier.importKind = null;
  2639. specifier.local = specifier.imported.__clone();
  2640. }
  2641. const nodeIsTypeImport = hasTypeImportKind(node);
  2642. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2643. if (nodeIsTypeImport && specifierIsTypeImport) {
  2644. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  2645. }
  2646. if (nodeIsTypeImport || specifierIsTypeImport) {
  2647. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2648. }
  2649. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2650. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2651. }
  2652. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2653. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2654. }
  2655. parseFunctionParams(node, allowModifiers) {
  2656. const kind = node.kind;
  2657. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2658. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2659. }
  2660. super.parseFunctionParams(node, allowModifiers);
  2661. }
  2662. parseVarId(decl, kind) {
  2663. super.parseVarId(decl, kind);
  2664. if (this.match(types.colon)) {
  2665. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2666. this.resetEndLocation(decl.id);
  2667. }
  2668. }
  2669. parseAsyncArrowFromCallExpression(node, call) {
  2670. if (this.match(types.colon)) {
  2671. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2672. this.state.noAnonFunctionType = true;
  2673. node.returnType = this.flowParseTypeAnnotation();
  2674. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2675. }
  2676. return super.parseAsyncArrowFromCallExpression(node, call);
  2677. }
  2678. shouldParseAsyncArrow() {
  2679. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2680. }
  2681. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  2682. let state = null;
  2683. let jsx;
  2684. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2685. state = this.state.clone();
  2686. jsx = this.tryParse(() => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  2687. if (!jsx.error) return jsx.node;
  2688. const {
  2689. context
  2690. } = this.state;
  2691. if (context[context.length - 1] === types$1.j_oTag) {
  2692. context.length -= 2;
  2693. } else if (context[context.length - 1] === types$1.j_expr) {
  2694. context.length -= 1;
  2695. }
  2696. }
  2697. if (jsx && jsx.error || this.isRelational("<")) {
  2698. state = state || this.state.clone();
  2699. let typeParameters;
  2700. const arrow = this.tryParse(() => {
  2701. typeParameters = this.flowParseTypeParameterDeclaration();
  2702. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  2703. arrowExpression.typeParameters = typeParameters;
  2704. this.resetStartLocationFromNode(arrowExpression, typeParameters);
  2705. return arrowExpression;
  2706. }, state);
  2707. const arrowExpression = arrow.node && arrow.node.type === "ArrowFunctionExpression" ? arrow.node : null;
  2708. if (!arrow.error && arrowExpression) return arrowExpression;
  2709. if (jsx && jsx.node) {
  2710. this.state = jsx.failState;
  2711. return jsx.node;
  2712. }
  2713. if (arrowExpression) {
  2714. this.state = arrow.failState;
  2715. return arrowExpression;
  2716. }
  2717. if (jsx && jsx.thrown) throw jsx.error;
  2718. if (arrow.thrown) throw arrow.error;
  2719. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  2720. }
  2721. return super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2722. }
  2723. parseArrow(node) {
  2724. if (this.match(types.colon)) {
  2725. const result = this.tryParse(() => {
  2726. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2727. this.state.noAnonFunctionType = true;
  2728. const typeNode = this.startNode();
  2729. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2730. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2731. if (this.canInsertSemicolon()) this.unexpected();
  2732. if (!this.match(types.arrow)) this.unexpected();
  2733. return typeNode;
  2734. });
  2735. if (result.thrown) return null;
  2736. if (result.error) this.state = result.failState;
  2737. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2738. }
  2739. return super.parseArrow(node);
  2740. }
  2741. shouldParseArrow() {
  2742. return this.match(types.colon) || super.shouldParseArrow();
  2743. }
  2744. setArrowFunctionParameters(node, params) {
  2745. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2746. node.params = params;
  2747. } else {
  2748. super.setArrowFunctionParameters(node, params);
  2749. }
  2750. }
  2751. checkParams(node, allowDuplicates, isArrowFunction) {
  2752. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2753. return;
  2754. }
  2755. return super.checkParams(...arguments);
  2756. }
  2757. parseParenAndDistinguishExpression(canBeArrow) {
  2758. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2759. }
  2760. parseSubscripts(base, startPos, startLoc, noCalls) {
  2761. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2762. this.next();
  2763. const node = this.startNodeAt(startPos, startLoc);
  2764. node.callee = base;
  2765. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2766. base = this.finishNode(node, "CallExpression");
  2767. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2768. const state = this.state.clone();
  2769. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2770. if (!arrow.error && !arrow.aborted) return arrow.node;
  2771. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2772. if (result.node && !result.error) return result.node;
  2773. if (arrow.node) {
  2774. this.state = arrow.failState;
  2775. return arrow.node;
  2776. }
  2777. if (result.node) {
  2778. this.state = result.failState;
  2779. return result.node;
  2780. }
  2781. throw arrow.error || result.error;
  2782. }
  2783. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2784. }
  2785. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2786. if (this.match(types.questionDot) && this.isLookaheadRelational("<")) {
  2787. subscriptState.optionalChainMember = true;
  2788. if (noCalls) {
  2789. subscriptState.stop = true;
  2790. return base;
  2791. }
  2792. this.next();
  2793. const node = this.startNodeAt(startPos, startLoc);
  2794. node.callee = base;
  2795. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2796. this.expect(types.parenL);
  2797. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2798. node.optional = true;
  2799. return this.finishCallExpression(node, true);
  2800. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2801. const node = this.startNodeAt(startPos, startLoc);
  2802. node.callee = base;
  2803. const result = this.tryParse(() => {
  2804. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2805. this.expect(types.parenL);
  2806. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2807. if (subscriptState.optionalChainMember) node.optional = false;
  2808. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2809. });
  2810. if (result.node) {
  2811. if (result.error) this.state = result.failState;
  2812. return result.node;
  2813. }
  2814. }
  2815. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2816. }
  2817. parseNewArguments(node) {
  2818. let targs = null;
  2819. if (this.shouldParseTypes() && this.isRelational("<")) {
  2820. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2821. }
  2822. node.typeArguments = targs;
  2823. super.parseNewArguments(node);
  2824. }
  2825. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2826. const node = this.startNodeAt(startPos, startLoc);
  2827. this.parseFunctionParams(node);
  2828. if (!this.parseArrow(node)) return;
  2829. return this.parseArrowExpression(node, undefined, true);
  2830. }
  2831. readToken_mult_modulo(code) {
  2832. const next = this.input.charCodeAt(this.state.pos + 1);
  2833. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2834. this.state.hasFlowComment = false;
  2835. this.state.pos += 2;
  2836. this.nextToken();
  2837. return;
  2838. }
  2839. super.readToken_mult_modulo(code);
  2840. }
  2841. readToken_pipe_amp(code) {
  2842. const next = this.input.charCodeAt(this.state.pos + 1);
  2843. if (code === 124 && next === 125) {
  2844. this.finishOp(types.braceBarR, 2);
  2845. return;
  2846. }
  2847. super.readToken_pipe_amp(code);
  2848. }
  2849. parseTopLevel(file, program) {
  2850. const fileNode = super.parseTopLevel(file, program);
  2851. if (this.state.hasFlowComment) {
  2852. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  2853. }
  2854. return fileNode;
  2855. }
  2856. skipBlockComment() {
  2857. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2858. if (this.state.hasFlowComment) {
  2859. this.unexpected(null, FlowErrors.NestedFlowComment);
  2860. }
  2861. this.hasFlowCommentCompletion();
  2862. this.state.pos += this.skipFlowComment();
  2863. this.state.hasFlowComment = true;
  2864. return;
  2865. }
  2866. if (this.state.hasFlowComment) {
  2867. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2868. if (end === -1) {
  2869. throw this.raise(this.state.pos - 2, Errors.UnterminatedComment);
  2870. }
  2871. this.state.pos = end + 3;
  2872. return;
  2873. }
  2874. super.skipBlockComment();
  2875. }
  2876. skipFlowComment() {
  2877. const {
  2878. pos
  2879. } = this.state;
  2880. let shiftToFirstNonWhiteSpace = 2;
  2881. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2882. shiftToFirstNonWhiteSpace++;
  2883. }
  2884. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2885. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2886. if (ch2 === 58 && ch3 === 58) {
  2887. return shiftToFirstNonWhiteSpace + 2;
  2888. }
  2889. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2890. return shiftToFirstNonWhiteSpace + 12;
  2891. }
  2892. if (ch2 === 58 && ch3 !== 58) {
  2893. return shiftToFirstNonWhiteSpace;
  2894. }
  2895. return false;
  2896. }
  2897. hasFlowCommentCompletion() {
  2898. const end = this.input.indexOf("*/", this.state.pos);
  2899. if (end === -1) {
  2900. throw this.raise(this.state.pos, Errors.UnterminatedComment);
  2901. }
  2902. }
  2903. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2904. enumName,
  2905. memberName
  2906. }) {
  2907. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  2908. }
  2909. flowEnumErrorInvalidMemberName(pos, {
  2910. enumName,
  2911. memberName
  2912. }) {
  2913. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  2914. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  2915. }
  2916. flowEnumErrorDuplicateMemberName(pos, {
  2917. enumName,
  2918. memberName
  2919. }) {
  2920. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  2921. }
  2922. flowEnumErrorInconsistentMemberValues(pos, {
  2923. enumName
  2924. }) {
  2925. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  2926. }
  2927. flowEnumErrorInvalidExplicitType(pos, {
  2928. enumName,
  2929. suppliedType
  2930. }) {
  2931. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  2932. }
  2933. flowEnumErrorInvalidMemberInitializer(pos, {
  2934. enumName,
  2935. explicitType,
  2936. memberName
  2937. }) {
  2938. let message = null;
  2939. switch (explicitType) {
  2940. case "boolean":
  2941. case "number":
  2942. case "string":
  2943. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  2944. break;
  2945. case "symbol":
  2946. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  2947. break;
  2948. default:
  2949. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  2950. }
  2951. return this.raise(pos, message, enumName, memberName, explicitType);
  2952. }
  2953. flowEnumErrorNumberMemberNotInitialized(pos, {
  2954. enumName,
  2955. memberName
  2956. }) {
  2957. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  2958. }
  2959. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  2960. enumName
  2961. }) {
  2962. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  2963. }
  2964. flowEnumMemberInit() {
  2965. const startPos = this.state.start;
  2966. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  2967. switch (this.state.type) {
  2968. case types.num:
  2969. {
  2970. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  2971. if (endOfInit()) {
  2972. return {
  2973. type: "number",
  2974. pos: literal.start,
  2975. value: literal
  2976. };
  2977. }
  2978. return {
  2979. type: "invalid",
  2980. pos: startPos
  2981. };
  2982. }
  2983. case types.string:
  2984. {
  2985. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  2986. if (endOfInit()) {
  2987. return {
  2988. type: "string",
  2989. pos: literal.start,
  2990. value: literal
  2991. };
  2992. }
  2993. return {
  2994. type: "invalid",
  2995. pos: startPos
  2996. };
  2997. }
  2998. case types._true:
  2999. case types._false:
  3000. {
  3001. const literal = this.parseBooleanLiteral();
  3002. if (endOfInit()) {
  3003. return {
  3004. type: "boolean",
  3005. pos: literal.start,
  3006. value: literal
  3007. };
  3008. }
  3009. return {
  3010. type: "invalid",
  3011. pos: startPos
  3012. };
  3013. }
  3014. default:
  3015. return {
  3016. type: "invalid",
  3017. pos: startPos
  3018. };
  3019. }
  3020. }
  3021. flowEnumMemberRaw() {
  3022. const pos = this.state.start;
  3023. const id = this.parseIdentifier(true);
  3024. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3025. type: "none",
  3026. pos
  3027. };
  3028. return {
  3029. id,
  3030. init
  3031. };
  3032. }
  3033. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3034. const {
  3035. explicitType
  3036. } = context;
  3037. if (explicitType === null) {
  3038. return;
  3039. }
  3040. if (explicitType !== expectedType) {
  3041. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3042. }
  3043. }
  3044. flowEnumMembers({
  3045. enumName,
  3046. explicitType
  3047. }) {
  3048. const seenNames = new Set();
  3049. const members = {
  3050. booleanMembers: [],
  3051. numberMembers: [],
  3052. stringMembers: [],
  3053. defaultedMembers: []
  3054. };
  3055. while (!this.match(types.braceR)) {
  3056. const memberNode = this.startNode();
  3057. const {
  3058. id,
  3059. init
  3060. } = this.flowEnumMemberRaw();
  3061. const memberName = id.name;
  3062. if (memberName === "") {
  3063. continue;
  3064. }
  3065. if (/^[a-z]/.test(memberName)) {
  3066. this.flowEnumErrorInvalidMemberName(id.start, {
  3067. enumName,
  3068. memberName
  3069. });
  3070. }
  3071. if (seenNames.has(memberName)) {
  3072. this.flowEnumErrorDuplicateMemberName(id.start, {
  3073. enumName,
  3074. memberName
  3075. });
  3076. }
  3077. seenNames.add(memberName);
  3078. const context = {
  3079. enumName,
  3080. explicitType,
  3081. memberName
  3082. };
  3083. memberNode.id = id;
  3084. switch (init.type) {
  3085. case "boolean":
  3086. {
  3087. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3088. memberNode.init = init.value;
  3089. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3090. break;
  3091. }
  3092. case "number":
  3093. {
  3094. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3095. memberNode.init = init.value;
  3096. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3097. break;
  3098. }
  3099. case "string":
  3100. {
  3101. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3102. memberNode.init = init.value;
  3103. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3104. break;
  3105. }
  3106. case "invalid":
  3107. {
  3108. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3109. }
  3110. case "none":
  3111. {
  3112. switch (explicitType) {
  3113. case "boolean":
  3114. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3115. break;
  3116. case "number":
  3117. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3118. break;
  3119. default:
  3120. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3121. }
  3122. }
  3123. }
  3124. if (!this.match(types.braceR)) {
  3125. this.expect(types.comma);
  3126. }
  3127. }
  3128. return members;
  3129. }
  3130. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3131. enumName
  3132. }) {
  3133. if (initializedMembers.length === 0) {
  3134. return defaultedMembers;
  3135. } else if (defaultedMembers.length === 0) {
  3136. return initializedMembers;
  3137. } else if (defaultedMembers.length > initializedMembers.length) {
  3138. for (let _i = 0; _i < initializedMembers.length; _i++) {
  3139. const member = initializedMembers[_i];
  3140. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3141. enumName
  3142. });
  3143. }
  3144. return defaultedMembers;
  3145. } else {
  3146. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  3147. const member = defaultedMembers[_i2];
  3148. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3149. enumName
  3150. });
  3151. }
  3152. return initializedMembers;
  3153. }
  3154. }
  3155. flowEnumParseExplicitType({
  3156. enumName
  3157. }) {
  3158. if (this.eatContextual("of")) {
  3159. if (!this.match(types.name)) {
  3160. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3161. enumName,
  3162. suppliedType: null
  3163. });
  3164. }
  3165. const {
  3166. value
  3167. } = this.state;
  3168. this.next();
  3169. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3170. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3171. enumName,
  3172. suppliedType: value
  3173. });
  3174. }
  3175. return value;
  3176. }
  3177. return null;
  3178. }
  3179. flowEnumBody(node, {
  3180. enumName,
  3181. nameLoc
  3182. }) {
  3183. const explicitType = this.flowEnumParseExplicitType({
  3184. enumName
  3185. });
  3186. this.expect(types.braceL);
  3187. const members = this.flowEnumMembers({
  3188. enumName,
  3189. explicitType
  3190. });
  3191. switch (explicitType) {
  3192. case "boolean":
  3193. node.explicitType = true;
  3194. node.members = members.booleanMembers;
  3195. this.expect(types.braceR);
  3196. return this.finishNode(node, "EnumBooleanBody");
  3197. case "number":
  3198. node.explicitType = true;
  3199. node.members = members.numberMembers;
  3200. this.expect(types.braceR);
  3201. return this.finishNode(node, "EnumNumberBody");
  3202. case "string":
  3203. node.explicitType = true;
  3204. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3205. enumName
  3206. });
  3207. this.expect(types.braceR);
  3208. return this.finishNode(node, "EnumStringBody");
  3209. case "symbol":
  3210. node.members = members.defaultedMembers;
  3211. this.expect(types.braceR);
  3212. return this.finishNode(node, "EnumSymbolBody");
  3213. default:
  3214. {
  3215. const empty = () => {
  3216. node.members = [];
  3217. this.expect(types.braceR);
  3218. return this.finishNode(node, "EnumStringBody");
  3219. };
  3220. node.explicitType = false;
  3221. const boolsLen = members.booleanMembers.length;
  3222. const numsLen = members.numberMembers.length;
  3223. const strsLen = members.stringMembers.length;
  3224. const defaultedLen = members.defaultedMembers.length;
  3225. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3226. return empty();
  3227. } else if (!boolsLen && !numsLen) {
  3228. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3229. enumName
  3230. });
  3231. this.expect(types.braceR);
  3232. return this.finishNode(node, "EnumStringBody");
  3233. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3234. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  3235. const member = _members$defaultedMem[_i3];
  3236. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3237. enumName,
  3238. memberName: member.id.name
  3239. });
  3240. }
  3241. node.members = members.booleanMembers;
  3242. this.expect(types.braceR);
  3243. return this.finishNode(node, "EnumBooleanBody");
  3244. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3245. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  3246. const member = _members$defaultedMem2[_i4];
  3247. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3248. enumName,
  3249. memberName: member.id.name
  3250. });
  3251. }
  3252. node.members = members.numberMembers;
  3253. this.expect(types.braceR);
  3254. return this.finishNode(node, "EnumNumberBody");
  3255. } else {
  3256. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3257. enumName
  3258. });
  3259. return empty();
  3260. }
  3261. }
  3262. }
  3263. }
  3264. flowParseEnumDeclaration(node) {
  3265. const id = this.parseIdentifier();
  3266. node.id = id;
  3267. node.body = this.flowEnumBody(this.startNode(), {
  3268. enumName: id.name,
  3269. nameLoc: id.start
  3270. });
  3271. return this.finishNode(node, "EnumDeclaration");
  3272. }
  3273. updateContext(prevType) {
  3274. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  3275. this.state.exprAllowed = false;
  3276. } else {
  3277. super.updateContext(prevType);
  3278. }
  3279. }
  3280. });
  3281. const entities = {
  3282. quot: "\u0022",
  3283. amp: "&",
  3284. apos: "\u0027",
  3285. lt: "<",
  3286. gt: ">",
  3287. nbsp: "\u00A0",
  3288. iexcl: "\u00A1",
  3289. cent: "\u00A2",
  3290. pound: "\u00A3",
  3291. curren: "\u00A4",
  3292. yen: "\u00A5",
  3293. brvbar: "\u00A6",
  3294. sect: "\u00A7",
  3295. uml: "\u00A8",
  3296. copy: "\u00A9",
  3297. ordf: "\u00AA",
  3298. laquo: "\u00AB",
  3299. not: "\u00AC",
  3300. shy: "\u00AD",
  3301. reg: "\u00AE",
  3302. macr: "\u00AF",
  3303. deg: "\u00B0",
  3304. plusmn: "\u00B1",
  3305. sup2: "\u00B2",
  3306. sup3: "\u00B3",
  3307. acute: "\u00B4",
  3308. micro: "\u00B5",
  3309. para: "\u00B6",
  3310. middot: "\u00B7",
  3311. cedil: "\u00B8",
  3312. sup1: "\u00B9",
  3313. ordm: "\u00BA",
  3314. raquo: "\u00BB",
  3315. frac14: "\u00BC",
  3316. frac12: "\u00BD",
  3317. frac34: "\u00BE",
  3318. iquest: "\u00BF",
  3319. Agrave: "\u00C0",
  3320. Aacute: "\u00C1",
  3321. Acirc: "\u00C2",
  3322. Atilde: "\u00C3",
  3323. Auml: "\u00C4",
  3324. Aring: "\u00C5",
  3325. AElig: "\u00C6",
  3326. Ccedil: "\u00C7",
  3327. Egrave: "\u00C8",
  3328. Eacute: "\u00C9",
  3329. Ecirc: "\u00CA",
  3330. Euml: "\u00CB",
  3331. Igrave: "\u00CC",
  3332. Iacute: "\u00CD",
  3333. Icirc: "\u00CE",
  3334. Iuml: "\u00CF",
  3335. ETH: "\u00D0",
  3336. Ntilde: "\u00D1",
  3337. Ograve: "\u00D2",
  3338. Oacute: "\u00D3",
  3339. Ocirc: "\u00D4",
  3340. Otilde: "\u00D5",
  3341. Ouml: "\u00D6",
  3342. times: "\u00D7",
  3343. Oslash: "\u00D8",
  3344. Ugrave: "\u00D9",
  3345. Uacute: "\u00DA",
  3346. Ucirc: "\u00DB",
  3347. Uuml: "\u00DC",
  3348. Yacute: "\u00DD",
  3349. THORN: "\u00DE",
  3350. szlig: "\u00DF",
  3351. agrave: "\u00E0",
  3352. aacute: "\u00E1",
  3353. acirc: "\u00E2",
  3354. atilde: "\u00E3",
  3355. auml: "\u00E4",
  3356. aring: "\u00E5",
  3357. aelig: "\u00E6",
  3358. ccedil: "\u00E7",
  3359. egrave: "\u00E8",
  3360. eacute: "\u00E9",
  3361. ecirc: "\u00EA",
  3362. euml: "\u00EB",
  3363. igrave: "\u00EC",
  3364. iacute: "\u00ED",
  3365. icirc: "\u00EE",
  3366. iuml: "\u00EF",
  3367. eth: "\u00F0",
  3368. ntilde: "\u00F1",
  3369. ograve: "\u00F2",
  3370. oacute: "\u00F3",
  3371. ocirc: "\u00F4",
  3372. otilde: "\u00F5",
  3373. ouml: "\u00F6",
  3374. divide: "\u00F7",
  3375. oslash: "\u00F8",
  3376. ugrave: "\u00F9",
  3377. uacute: "\u00FA",
  3378. ucirc: "\u00FB",
  3379. uuml: "\u00FC",
  3380. yacute: "\u00FD",
  3381. thorn: "\u00FE",
  3382. yuml: "\u00FF",
  3383. OElig: "\u0152",
  3384. oelig: "\u0153",
  3385. Scaron: "\u0160",
  3386. scaron: "\u0161",
  3387. Yuml: "\u0178",
  3388. fnof: "\u0192",
  3389. circ: "\u02C6",
  3390. tilde: "\u02DC",
  3391. Alpha: "\u0391",
  3392. Beta: "\u0392",
  3393. Gamma: "\u0393",
  3394. Delta: "\u0394",
  3395. Epsilon: "\u0395",
  3396. Zeta: "\u0396",
  3397. Eta: "\u0397",
  3398. Theta: "\u0398",
  3399. Iota: "\u0399",
  3400. Kappa: "\u039A",
  3401. Lambda: "\u039B",
  3402. Mu: "\u039C",
  3403. Nu: "\u039D",
  3404. Xi: "\u039E",
  3405. Omicron: "\u039F",
  3406. Pi: "\u03A0",
  3407. Rho: "\u03A1",
  3408. Sigma: "\u03A3",
  3409. Tau: "\u03A4",
  3410. Upsilon: "\u03A5",
  3411. Phi: "\u03A6",
  3412. Chi: "\u03A7",
  3413. Psi: "\u03A8",
  3414. Omega: "\u03A9",
  3415. alpha: "\u03B1",
  3416. beta: "\u03B2",
  3417. gamma: "\u03B3",
  3418. delta: "\u03B4",
  3419. epsilon: "\u03B5",
  3420. zeta: "\u03B6",
  3421. eta: "\u03B7",
  3422. theta: "\u03B8",
  3423. iota: "\u03B9",
  3424. kappa: "\u03BA",
  3425. lambda: "\u03BB",
  3426. mu: "\u03BC",
  3427. nu: "\u03BD",
  3428. xi: "\u03BE",
  3429. omicron: "\u03BF",
  3430. pi: "\u03C0",
  3431. rho: "\u03C1",
  3432. sigmaf: "\u03C2",
  3433. sigma: "\u03C3",
  3434. tau: "\u03C4",
  3435. upsilon: "\u03C5",
  3436. phi: "\u03C6",
  3437. chi: "\u03C7",
  3438. psi: "\u03C8",
  3439. omega: "\u03C9",
  3440. thetasym: "\u03D1",
  3441. upsih: "\u03D2",
  3442. piv: "\u03D6",
  3443. ensp: "\u2002",
  3444. emsp: "\u2003",
  3445. thinsp: "\u2009",
  3446. zwnj: "\u200C",
  3447. zwj: "\u200D",
  3448. lrm: "\u200E",
  3449. rlm: "\u200F",
  3450. ndash: "\u2013",
  3451. mdash: "\u2014",
  3452. lsquo: "\u2018",
  3453. rsquo: "\u2019",
  3454. sbquo: "\u201A",
  3455. ldquo: "\u201C",
  3456. rdquo: "\u201D",
  3457. bdquo: "\u201E",
  3458. dagger: "\u2020",
  3459. Dagger: "\u2021",
  3460. bull: "\u2022",
  3461. hellip: "\u2026",
  3462. permil: "\u2030",
  3463. prime: "\u2032",
  3464. Prime: "\u2033",
  3465. lsaquo: "\u2039",
  3466. rsaquo: "\u203A",
  3467. oline: "\u203E",
  3468. frasl: "\u2044",
  3469. euro: "\u20AC",
  3470. image: "\u2111",
  3471. weierp: "\u2118",
  3472. real: "\u211C",
  3473. trade: "\u2122",
  3474. alefsym: "\u2135",
  3475. larr: "\u2190",
  3476. uarr: "\u2191",
  3477. rarr: "\u2192",
  3478. darr: "\u2193",
  3479. harr: "\u2194",
  3480. crarr: "\u21B5",
  3481. lArr: "\u21D0",
  3482. uArr: "\u21D1",
  3483. rArr: "\u21D2",
  3484. dArr: "\u21D3",
  3485. hArr: "\u21D4",
  3486. forall: "\u2200",
  3487. part: "\u2202",
  3488. exist: "\u2203",
  3489. empty: "\u2205",
  3490. nabla: "\u2207",
  3491. isin: "\u2208",
  3492. notin: "\u2209",
  3493. ni: "\u220B",
  3494. prod: "\u220F",
  3495. sum: "\u2211",
  3496. minus: "\u2212",
  3497. lowast: "\u2217",
  3498. radic: "\u221A",
  3499. prop: "\u221D",
  3500. infin: "\u221E",
  3501. ang: "\u2220",
  3502. and: "\u2227",
  3503. or: "\u2228",
  3504. cap: "\u2229",
  3505. cup: "\u222A",
  3506. int: "\u222B",
  3507. there4: "\u2234",
  3508. sim: "\u223C",
  3509. cong: "\u2245",
  3510. asymp: "\u2248",
  3511. ne: "\u2260",
  3512. equiv: "\u2261",
  3513. le: "\u2264",
  3514. ge: "\u2265",
  3515. sub: "\u2282",
  3516. sup: "\u2283",
  3517. nsub: "\u2284",
  3518. sube: "\u2286",
  3519. supe: "\u2287",
  3520. oplus: "\u2295",
  3521. otimes: "\u2297",
  3522. perp: "\u22A5",
  3523. sdot: "\u22C5",
  3524. lceil: "\u2308",
  3525. rceil: "\u2309",
  3526. lfloor: "\u230A",
  3527. rfloor: "\u230B",
  3528. lang: "\u2329",
  3529. rang: "\u232A",
  3530. loz: "\u25CA",
  3531. spades: "\u2660",
  3532. clubs: "\u2663",
  3533. hearts: "\u2665",
  3534. diams: "\u2666"
  3535. };
  3536. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3537. const DECIMAL_NUMBER = /^\d+$/;
  3538. const JsxErrors = Object.freeze({
  3539. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3540. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3541. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3542. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3543. UnterminatedJsxContent: "Unterminated JSX contents",
  3544. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3545. });
  3546. types$1.j_oTag = new TokContext("<tag", false);
  3547. types$1.j_cTag = new TokContext("</tag", false);
  3548. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3549. types.jsxName = new TokenType("jsxName");
  3550. types.jsxText = new TokenType("jsxText", {
  3551. beforeExpr: true
  3552. });
  3553. types.jsxTagStart = new TokenType("jsxTagStart", {
  3554. startsExpr: true
  3555. });
  3556. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3557. types.jsxTagStart.updateContext = function () {
  3558. this.state.context.push(types$1.j_expr);
  3559. this.state.context.push(types$1.j_oTag);
  3560. this.state.exprAllowed = false;
  3561. };
  3562. types.jsxTagEnd.updateContext = function (prevType) {
  3563. const out = this.state.context.pop();
  3564. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3565. this.state.context.pop();
  3566. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3567. } else {
  3568. this.state.exprAllowed = true;
  3569. }
  3570. };
  3571. function isFragment(object) {
  3572. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3573. }
  3574. function getQualifiedJSXName(object) {
  3575. if (object.type === "JSXIdentifier") {
  3576. return object.name;
  3577. }
  3578. if (object.type === "JSXNamespacedName") {
  3579. return object.namespace.name + ":" + object.name.name;
  3580. }
  3581. if (object.type === "JSXMemberExpression") {
  3582. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3583. }
  3584. throw new Error("Node had unexpected type: " + object.type);
  3585. }
  3586. var jsx = (superClass => class extends superClass {
  3587. jsxReadToken() {
  3588. let out = "";
  3589. let chunkStart = this.state.pos;
  3590. for (;;) {
  3591. if (this.state.pos >= this.length) {
  3592. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  3593. }
  3594. const ch = this.input.charCodeAt(this.state.pos);
  3595. switch (ch) {
  3596. case 60:
  3597. case 123:
  3598. if (this.state.pos === this.state.start) {
  3599. if (ch === 60 && this.state.exprAllowed) {
  3600. ++this.state.pos;
  3601. return this.finishToken(types.jsxTagStart);
  3602. }
  3603. return super.getTokenFromCode(ch);
  3604. }
  3605. out += this.input.slice(chunkStart, this.state.pos);
  3606. return this.finishToken(types.jsxText, out);
  3607. case 38:
  3608. out += this.input.slice(chunkStart, this.state.pos);
  3609. out += this.jsxReadEntity();
  3610. chunkStart = this.state.pos;
  3611. break;
  3612. default:
  3613. if (isNewLine(ch)) {
  3614. out += this.input.slice(chunkStart, this.state.pos);
  3615. out += this.jsxReadNewLine(true);
  3616. chunkStart = this.state.pos;
  3617. } else {
  3618. ++this.state.pos;
  3619. }
  3620. }
  3621. }
  3622. }
  3623. jsxReadNewLine(normalizeCRLF) {
  3624. const ch = this.input.charCodeAt(this.state.pos);
  3625. let out;
  3626. ++this.state.pos;
  3627. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3628. ++this.state.pos;
  3629. out = normalizeCRLF ? "\n" : "\r\n";
  3630. } else {
  3631. out = String.fromCharCode(ch);
  3632. }
  3633. ++this.state.curLine;
  3634. this.state.lineStart = this.state.pos;
  3635. return out;
  3636. }
  3637. jsxReadString(quote) {
  3638. let out = "";
  3639. let chunkStart = ++this.state.pos;
  3640. for (;;) {
  3641. if (this.state.pos >= this.length) {
  3642. throw this.raise(this.state.start, Errors.UnterminatedString);
  3643. }
  3644. const ch = this.input.charCodeAt(this.state.pos);
  3645. if (ch === quote) break;
  3646. if (ch === 38) {
  3647. out += this.input.slice(chunkStart, this.state.pos);
  3648. out += this.jsxReadEntity();
  3649. chunkStart = this.state.pos;
  3650. } else if (isNewLine(ch)) {
  3651. out += this.input.slice(chunkStart, this.state.pos);
  3652. out += this.jsxReadNewLine(false);
  3653. chunkStart = this.state.pos;
  3654. } else {
  3655. ++this.state.pos;
  3656. }
  3657. }
  3658. out += this.input.slice(chunkStart, this.state.pos++);
  3659. return this.finishToken(types.string, out);
  3660. }
  3661. jsxReadEntity() {
  3662. let str = "";
  3663. let count = 0;
  3664. let entity;
  3665. let ch = this.input[this.state.pos];
  3666. const startPos = ++this.state.pos;
  3667. while (this.state.pos < this.length && count++ < 10) {
  3668. ch = this.input[this.state.pos++];
  3669. if (ch === ";") {
  3670. if (str[0] === "#") {
  3671. if (str[1] === "x") {
  3672. str = str.substr(2);
  3673. if (HEX_NUMBER.test(str)) {
  3674. entity = String.fromCodePoint(parseInt(str, 16));
  3675. }
  3676. } else {
  3677. str = str.substr(1);
  3678. if (DECIMAL_NUMBER.test(str)) {
  3679. entity = String.fromCodePoint(parseInt(str, 10));
  3680. }
  3681. }
  3682. } else {
  3683. entity = entities[str];
  3684. }
  3685. break;
  3686. }
  3687. str += ch;
  3688. }
  3689. if (!entity) {
  3690. this.state.pos = startPos;
  3691. return "&";
  3692. }
  3693. return entity;
  3694. }
  3695. jsxReadWord() {
  3696. let ch;
  3697. const start = this.state.pos;
  3698. do {
  3699. ch = this.input.charCodeAt(++this.state.pos);
  3700. } while (isIdentifierChar(ch) || ch === 45);
  3701. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3702. }
  3703. jsxParseIdentifier() {
  3704. const node = this.startNode();
  3705. if (this.match(types.jsxName)) {
  3706. node.name = this.state.value;
  3707. } else if (this.state.type.keyword) {
  3708. node.name = this.state.type.keyword;
  3709. } else {
  3710. this.unexpected();
  3711. }
  3712. this.next();
  3713. return this.finishNode(node, "JSXIdentifier");
  3714. }
  3715. jsxParseNamespacedName() {
  3716. const startPos = this.state.start;
  3717. const startLoc = this.state.startLoc;
  3718. const name = this.jsxParseIdentifier();
  3719. if (!this.eat(types.colon)) return name;
  3720. const node = this.startNodeAt(startPos, startLoc);
  3721. node.namespace = name;
  3722. node.name = this.jsxParseIdentifier();
  3723. return this.finishNode(node, "JSXNamespacedName");
  3724. }
  3725. jsxParseElementName() {
  3726. const startPos = this.state.start;
  3727. const startLoc = this.state.startLoc;
  3728. let node = this.jsxParseNamespacedName();
  3729. if (node.type === "JSXNamespacedName") {
  3730. return node;
  3731. }
  3732. while (this.eat(types.dot)) {
  3733. const newNode = this.startNodeAt(startPos, startLoc);
  3734. newNode.object = node;
  3735. newNode.property = this.jsxParseIdentifier();
  3736. node = this.finishNode(newNode, "JSXMemberExpression");
  3737. }
  3738. return node;
  3739. }
  3740. jsxParseAttributeValue() {
  3741. let node;
  3742. switch (this.state.type) {
  3743. case types.braceL:
  3744. node = this.startNode();
  3745. this.next();
  3746. node = this.jsxParseExpressionContainer(node);
  3747. if (node.expression.type === "JSXEmptyExpression") {
  3748. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  3749. }
  3750. return node;
  3751. case types.jsxTagStart:
  3752. case types.string:
  3753. return this.parseExprAtom();
  3754. default:
  3755. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  3756. }
  3757. }
  3758. jsxParseEmptyExpression() {
  3759. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3760. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3761. }
  3762. jsxParseSpreadChild(node) {
  3763. this.next();
  3764. node.expression = this.parseExpression();
  3765. this.expect(types.braceR);
  3766. return this.finishNode(node, "JSXSpreadChild");
  3767. }
  3768. jsxParseExpressionContainer(node) {
  3769. if (this.match(types.braceR)) {
  3770. node.expression = this.jsxParseEmptyExpression();
  3771. } else {
  3772. node.expression = this.parseExpression();
  3773. }
  3774. this.expect(types.braceR);
  3775. return this.finishNode(node, "JSXExpressionContainer");
  3776. }
  3777. jsxParseAttribute() {
  3778. const node = this.startNode();
  3779. if (this.eat(types.braceL)) {
  3780. this.expect(types.ellipsis);
  3781. node.argument = this.parseMaybeAssign();
  3782. this.expect(types.braceR);
  3783. return this.finishNode(node, "JSXSpreadAttribute");
  3784. }
  3785. node.name = this.jsxParseNamespacedName();
  3786. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3787. return this.finishNode(node, "JSXAttribute");
  3788. }
  3789. jsxParseOpeningElementAt(startPos, startLoc) {
  3790. const node = this.startNodeAt(startPos, startLoc);
  3791. if (this.match(types.jsxTagEnd)) {
  3792. this.expect(types.jsxTagEnd);
  3793. return this.finishNode(node, "JSXOpeningFragment");
  3794. }
  3795. node.name = this.jsxParseElementName();
  3796. return this.jsxParseOpeningElementAfterName(node);
  3797. }
  3798. jsxParseOpeningElementAfterName(node) {
  3799. const attributes = [];
  3800. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3801. attributes.push(this.jsxParseAttribute());
  3802. }
  3803. node.attributes = attributes;
  3804. node.selfClosing = this.eat(types.slash);
  3805. this.expect(types.jsxTagEnd);
  3806. return this.finishNode(node, "JSXOpeningElement");
  3807. }
  3808. jsxParseClosingElementAt(startPos, startLoc) {
  3809. const node = this.startNodeAt(startPos, startLoc);
  3810. if (this.match(types.jsxTagEnd)) {
  3811. this.expect(types.jsxTagEnd);
  3812. return this.finishNode(node, "JSXClosingFragment");
  3813. }
  3814. node.name = this.jsxParseElementName();
  3815. this.expect(types.jsxTagEnd);
  3816. return this.finishNode(node, "JSXClosingElement");
  3817. }
  3818. jsxParseElementAt(startPos, startLoc) {
  3819. const node = this.startNodeAt(startPos, startLoc);
  3820. const children = [];
  3821. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3822. let closingElement = null;
  3823. if (!openingElement.selfClosing) {
  3824. contents: for (;;) {
  3825. switch (this.state.type) {
  3826. case types.jsxTagStart:
  3827. startPos = this.state.start;
  3828. startLoc = this.state.startLoc;
  3829. this.next();
  3830. if (this.eat(types.slash)) {
  3831. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3832. break contents;
  3833. }
  3834. children.push(this.jsxParseElementAt(startPos, startLoc));
  3835. break;
  3836. case types.jsxText:
  3837. children.push(this.parseExprAtom());
  3838. break;
  3839. case types.braceL:
  3840. {
  3841. const node = this.startNode();
  3842. this.next();
  3843. if (this.match(types.ellipsis)) {
  3844. children.push(this.jsxParseSpreadChild(node));
  3845. } else {
  3846. children.push(this.jsxParseExpressionContainer(node));
  3847. }
  3848. break;
  3849. }
  3850. default:
  3851. throw this.unexpected();
  3852. }
  3853. }
  3854. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3855. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  3856. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3857. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3858. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3859. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3860. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3861. }
  3862. }
  3863. }
  3864. if (isFragment(openingElement)) {
  3865. node.openingFragment = openingElement;
  3866. node.closingFragment = closingElement;
  3867. } else {
  3868. node.openingElement = openingElement;
  3869. node.closingElement = closingElement;
  3870. }
  3871. node.children = children;
  3872. if (this.isRelational("<")) {
  3873. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  3874. }
  3875. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3876. }
  3877. jsxParseElement() {
  3878. const startPos = this.state.start;
  3879. const startLoc = this.state.startLoc;
  3880. this.next();
  3881. return this.jsxParseElementAt(startPos, startLoc);
  3882. }
  3883. parseExprAtom(refExpressionErrors) {
  3884. if (this.match(types.jsxText)) {
  3885. return this.parseLiteral(this.state.value, "JSXText");
  3886. } else if (this.match(types.jsxTagStart)) {
  3887. return this.jsxParseElement();
  3888. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3889. this.finishToken(types.jsxTagStart);
  3890. return this.jsxParseElement();
  3891. } else {
  3892. return super.parseExprAtom(refExpressionErrors);
  3893. }
  3894. }
  3895. getTokenFromCode(code) {
  3896. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  3897. const context = this.curContext();
  3898. if (context === types$1.j_expr) {
  3899. return this.jsxReadToken();
  3900. }
  3901. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  3902. if (isIdentifierStart(code)) {
  3903. return this.jsxReadWord();
  3904. }
  3905. if (code === 62) {
  3906. ++this.state.pos;
  3907. return this.finishToken(types.jsxTagEnd);
  3908. }
  3909. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  3910. return this.jsxReadString(code);
  3911. }
  3912. }
  3913. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  3914. ++this.state.pos;
  3915. return this.finishToken(types.jsxTagStart);
  3916. }
  3917. return super.getTokenFromCode(code);
  3918. }
  3919. updateContext(prevType) {
  3920. if (this.match(types.braceL)) {
  3921. const curContext = this.curContext();
  3922. if (curContext === types$1.j_oTag) {
  3923. this.state.context.push(types$1.braceExpression);
  3924. } else if (curContext === types$1.j_expr) {
  3925. this.state.context.push(types$1.templateQuasi);
  3926. } else {
  3927. super.updateContext(prevType);
  3928. }
  3929. this.state.exprAllowed = true;
  3930. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  3931. this.state.context.length -= 2;
  3932. this.state.context.push(types$1.j_cTag);
  3933. this.state.exprAllowed = false;
  3934. } else {
  3935. return super.updateContext(prevType);
  3936. }
  3937. }
  3938. });
  3939. class Scope {
  3940. constructor(flags) {
  3941. this.var = [];
  3942. this.lexical = [];
  3943. this.functions = [];
  3944. this.flags = flags;
  3945. }
  3946. }
  3947. class ScopeHandler {
  3948. constructor(raise, inModule) {
  3949. this.scopeStack = [];
  3950. this.undefinedExports = new Map();
  3951. this.undefinedPrivateNames = new Map();
  3952. this.raise = raise;
  3953. this.inModule = inModule;
  3954. }
  3955. get inFunction() {
  3956. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  3957. }
  3958. get allowSuper() {
  3959. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  3960. }
  3961. get allowDirectSuper() {
  3962. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  3963. }
  3964. get inClass() {
  3965. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  3966. }
  3967. get inNonArrowFunction() {
  3968. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  3969. }
  3970. get treatFunctionsAsVar() {
  3971. return this.treatFunctionsAsVarInScope(this.currentScope());
  3972. }
  3973. createScope(flags) {
  3974. return new Scope(flags);
  3975. }
  3976. enter(flags) {
  3977. this.scopeStack.push(this.createScope(flags));
  3978. }
  3979. exit() {
  3980. this.scopeStack.pop();
  3981. }
  3982. treatFunctionsAsVarInScope(scope) {
  3983. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  3984. }
  3985. declareName(name, bindingType, pos) {
  3986. let scope = this.currentScope();
  3987. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  3988. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3989. if (bindingType & BIND_SCOPE_FUNCTION) {
  3990. scope.functions.push(name);
  3991. } else {
  3992. scope.lexical.push(name);
  3993. }
  3994. if (bindingType & BIND_SCOPE_LEXICAL) {
  3995. this.maybeExportDefined(scope, name);
  3996. }
  3997. } else if (bindingType & BIND_SCOPE_VAR) {
  3998. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  3999. scope = this.scopeStack[i];
  4000. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4001. scope.var.push(name);
  4002. this.maybeExportDefined(scope, name);
  4003. if (scope.flags & SCOPE_VAR) break;
  4004. }
  4005. }
  4006. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4007. this.undefinedExports.delete(name);
  4008. }
  4009. }
  4010. maybeExportDefined(scope, name) {
  4011. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4012. this.undefinedExports.delete(name);
  4013. }
  4014. }
  4015. checkRedeclarationInScope(scope, name, bindingType, pos) {
  4016. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  4017. this.raise(pos, Errors.VarRedeclaration, name);
  4018. }
  4019. }
  4020. isRedeclaredInScope(scope, name, bindingType) {
  4021. if (!(bindingType & BIND_KIND_VALUE)) return false;
  4022. if (bindingType & BIND_SCOPE_LEXICAL) {
  4023. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  4024. }
  4025. if (bindingType & BIND_SCOPE_FUNCTION) {
  4026. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  4027. }
  4028. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  4029. }
  4030. checkLocalExport(id) {
  4031. 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) {
  4032. this.undefinedExports.set(id.name, id.start);
  4033. }
  4034. }
  4035. currentScope() {
  4036. return this.scopeStack[this.scopeStack.length - 1];
  4037. }
  4038. currentVarScope() {
  4039. for (let i = this.scopeStack.length - 1;; i--) {
  4040. const scope = this.scopeStack[i];
  4041. if (scope.flags & SCOPE_VAR) {
  4042. return scope;
  4043. }
  4044. }
  4045. }
  4046. currentThisScope() {
  4047. for (let i = this.scopeStack.length - 1;; i--) {
  4048. const scope = this.scopeStack[i];
  4049. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  4050. return scope;
  4051. }
  4052. }
  4053. }
  4054. }
  4055. class TypeScriptScope extends Scope {
  4056. constructor(...args) {
  4057. super(...args);
  4058. this.types = [];
  4059. this.enums = [];
  4060. this.constEnums = [];
  4061. this.classes = [];
  4062. this.exportOnlyBindings = [];
  4063. }
  4064. }
  4065. class TypeScriptScopeHandler extends ScopeHandler {
  4066. createScope(flags) {
  4067. return new TypeScriptScope(flags);
  4068. }
  4069. declareName(name, bindingType, pos) {
  4070. const scope = this.currentScope();
  4071. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4072. this.maybeExportDefined(scope, name);
  4073. scope.exportOnlyBindings.push(name);
  4074. return;
  4075. }
  4076. super.declareName(...arguments);
  4077. if (bindingType & BIND_KIND_TYPE) {
  4078. if (!(bindingType & BIND_KIND_VALUE)) {
  4079. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4080. this.maybeExportDefined(scope, name);
  4081. }
  4082. scope.types.push(name);
  4083. }
  4084. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4085. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4086. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4087. }
  4088. isRedeclaredInScope(scope, name, bindingType) {
  4089. if (scope.enums.indexOf(name) > -1) {
  4090. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4091. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4092. const wasConst = scope.constEnums.indexOf(name) > -1;
  4093. return isConst !== wasConst;
  4094. }
  4095. return true;
  4096. }
  4097. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4098. if (scope.lexical.indexOf(name) > -1) {
  4099. return !!(bindingType & BIND_KIND_VALUE);
  4100. } else {
  4101. return false;
  4102. }
  4103. }
  4104. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4105. return true;
  4106. }
  4107. return super.isRedeclaredInScope(...arguments);
  4108. }
  4109. checkLocalExport(id) {
  4110. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4111. super.checkLocalExport(id);
  4112. }
  4113. }
  4114. }
  4115. const PARAM = 0b000,
  4116. PARAM_YIELD = 0b001,
  4117. PARAM_AWAIT = 0b010,
  4118. PARAM_RETURN = 0b100;
  4119. class ProductionParameterHandler {
  4120. constructor() {
  4121. this.stacks = [];
  4122. }
  4123. enter(flags) {
  4124. this.stacks.push(flags);
  4125. }
  4126. exit() {
  4127. this.stacks.pop();
  4128. }
  4129. currentFlags() {
  4130. return this.stacks[this.stacks.length - 1];
  4131. }
  4132. get hasAwait() {
  4133. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4134. }
  4135. get hasYield() {
  4136. return (this.currentFlags() & PARAM_YIELD) > 0;
  4137. }
  4138. get hasReturn() {
  4139. return (this.currentFlags() & PARAM_RETURN) > 0;
  4140. }
  4141. }
  4142. function functionFlags(isAsync, isGenerator) {
  4143. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4144. }
  4145. function nonNull(x) {
  4146. if (x == null) {
  4147. throw new Error(`Unexpected ${x} value.`);
  4148. }
  4149. return x;
  4150. }
  4151. function assert(x) {
  4152. if (!x) {
  4153. throw new Error("Assert fail");
  4154. }
  4155. }
  4156. const TSErrors = Object.freeze({
  4157. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4158. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4159. DeclareClassFieldHasInitializer: "'declare' class fields cannot have an initializer",
  4160. DuplicateModifier: "Duplicate modifier: '%0'",
  4161. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4162. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4163. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4164. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4165. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4166. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4167. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4168. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4169. TemplateTypeHasSubstitution: "Template literal types cannot have any substitution",
  4170. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4171. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4172. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4173. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4174. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4175. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4176. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4177. });
  4178. function keywordTypeFromName(value) {
  4179. switch (value) {
  4180. case "any":
  4181. return "TSAnyKeyword";
  4182. case "boolean":
  4183. return "TSBooleanKeyword";
  4184. case "bigint":
  4185. return "TSBigIntKeyword";
  4186. case "never":
  4187. return "TSNeverKeyword";
  4188. case "number":
  4189. return "TSNumberKeyword";
  4190. case "object":
  4191. return "TSObjectKeyword";
  4192. case "string":
  4193. return "TSStringKeyword";
  4194. case "symbol":
  4195. return "TSSymbolKeyword";
  4196. case "undefined":
  4197. return "TSUndefinedKeyword";
  4198. case "unknown":
  4199. return "TSUnknownKeyword";
  4200. default:
  4201. return undefined;
  4202. }
  4203. }
  4204. var typescript = (superClass => class extends superClass {
  4205. getScopeHandler() {
  4206. return TypeScriptScopeHandler;
  4207. }
  4208. tsIsIdentifier() {
  4209. return this.match(types.name);
  4210. }
  4211. tsNextTokenCanFollowModifier() {
  4212. this.next();
  4213. 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);
  4214. }
  4215. tsParseModifier(allowedModifiers) {
  4216. if (!this.match(types.name)) {
  4217. return undefined;
  4218. }
  4219. const modifier = this.state.value;
  4220. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4221. return modifier;
  4222. }
  4223. return undefined;
  4224. }
  4225. tsParseModifiers(modified, allowedModifiers) {
  4226. for (;;) {
  4227. const startPos = this.state.start;
  4228. const modifier = this.tsParseModifier(allowedModifiers);
  4229. if (!modifier) break;
  4230. if (Object.hasOwnProperty.call(modified, modifier)) {
  4231. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4232. }
  4233. modified[modifier] = true;
  4234. }
  4235. }
  4236. tsIsListTerminator(kind) {
  4237. switch (kind) {
  4238. case "EnumMembers":
  4239. case "TypeMembers":
  4240. return this.match(types.braceR);
  4241. case "HeritageClauseElement":
  4242. return this.match(types.braceL);
  4243. case "TupleElementTypes":
  4244. return this.match(types.bracketR);
  4245. case "TypeParametersOrArguments":
  4246. return this.isRelational(">");
  4247. }
  4248. throw new Error("Unreachable");
  4249. }
  4250. tsParseList(kind, parseElement) {
  4251. const result = [];
  4252. while (!this.tsIsListTerminator(kind)) {
  4253. result.push(parseElement());
  4254. }
  4255. return result;
  4256. }
  4257. tsParseDelimitedList(kind, parseElement) {
  4258. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4259. }
  4260. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4261. const result = [];
  4262. for (;;) {
  4263. if (this.tsIsListTerminator(kind)) {
  4264. break;
  4265. }
  4266. const element = parseElement();
  4267. if (element == null) {
  4268. return undefined;
  4269. }
  4270. result.push(element);
  4271. if (this.eat(types.comma)) {
  4272. continue;
  4273. }
  4274. if (this.tsIsListTerminator(kind)) {
  4275. break;
  4276. }
  4277. if (expectSuccess) {
  4278. this.expect(types.comma);
  4279. }
  4280. return undefined;
  4281. }
  4282. return result;
  4283. }
  4284. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4285. if (!skipFirstToken) {
  4286. if (bracket) {
  4287. this.expect(types.bracketL);
  4288. } else {
  4289. this.expectRelational("<");
  4290. }
  4291. }
  4292. const result = this.tsParseDelimitedList(kind, parseElement);
  4293. if (bracket) {
  4294. this.expect(types.bracketR);
  4295. } else {
  4296. this.expectRelational(">");
  4297. }
  4298. return result;
  4299. }
  4300. tsParseImportType() {
  4301. const node = this.startNode();
  4302. this.expect(types._import);
  4303. this.expect(types.parenL);
  4304. if (!this.match(types.string)) {
  4305. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4306. }
  4307. node.argument = this.parseExprAtom();
  4308. this.expect(types.parenR);
  4309. if (this.eat(types.dot)) {
  4310. node.qualifier = this.tsParseEntityName(true);
  4311. }
  4312. if (this.isRelational("<")) {
  4313. node.typeParameters = this.tsParseTypeArguments();
  4314. }
  4315. return this.finishNode(node, "TSImportType");
  4316. }
  4317. tsParseEntityName(allowReservedWords) {
  4318. let entity = this.parseIdentifier();
  4319. while (this.eat(types.dot)) {
  4320. const node = this.startNodeAtNode(entity);
  4321. node.left = entity;
  4322. node.right = this.parseIdentifier(allowReservedWords);
  4323. entity = this.finishNode(node, "TSQualifiedName");
  4324. }
  4325. return entity;
  4326. }
  4327. tsParseTypeReference() {
  4328. const node = this.startNode();
  4329. node.typeName = this.tsParseEntityName(false);
  4330. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4331. node.typeParameters = this.tsParseTypeArguments();
  4332. }
  4333. return this.finishNode(node, "TSTypeReference");
  4334. }
  4335. tsParseThisTypePredicate(lhs) {
  4336. this.next();
  4337. const node = this.startNodeAtNode(lhs);
  4338. node.parameterName = lhs;
  4339. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4340. return this.finishNode(node, "TSTypePredicate");
  4341. }
  4342. tsParseThisTypeNode() {
  4343. const node = this.startNode();
  4344. this.next();
  4345. return this.finishNode(node, "TSThisType");
  4346. }
  4347. tsParseTypeQuery() {
  4348. const node = this.startNode();
  4349. this.expect(types._typeof);
  4350. if (this.match(types._import)) {
  4351. node.exprName = this.tsParseImportType();
  4352. } else {
  4353. node.exprName = this.tsParseEntityName(true);
  4354. }
  4355. return this.finishNode(node, "TSTypeQuery");
  4356. }
  4357. tsParseTypeParameter() {
  4358. const node = this.startNode();
  4359. node.name = this.parseIdentifierName(node.start);
  4360. node.constraint = this.tsEatThenParseType(types._extends);
  4361. node.default = this.tsEatThenParseType(types.eq);
  4362. return this.finishNode(node, "TSTypeParameter");
  4363. }
  4364. tsTryParseTypeParameters() {
  4365. if (this.isRelational("<")) {
  4366. return this.tsParseTypeParameters();
  4367. }
  4368. }
  4369. tsParseTypeParameters() {
  4370. const node = this.startNode();
  4371. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4372. this.next();
  4373. } else {
  4374. this.unexpected();
  4375. }
  4376. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4377. return this.finishNode(node, "TSTypeParameterDeclaration");
  4378. }
  4379. tsTryNextParseConstantContext() {
  4380. if (this.lookahead().type === types._const) {
  4381. this.next();
  4382. return this.tsParseTypeReference();
  4383. }
  4384. return null;
  4385. }
  4386. tsFillSignature(returnToken, signature) {
  4387. const returnTokenRequired = returnToken === types.arrow;
  4388. signature.typeParameters = this.tsTryParseTypeParameters();
  4389. this.expect(types.parenL);
  4390. signature.parameters = this.tsParseBindingListForSignature();
  4391. if (returnTokenRequired) {
  4392. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4393. } else if (this.match(returnToken)) {
  4394. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4395. }
  4396. }
  4397. tsParseBindingListForSignature() {
  4398. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4399. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4400. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4401. }
  4402. return pattern;
  4403. });
  4404. }
  4405. tsParseTypeMemberSemicolon() {
  4406. if (!this.eat(types.comma)) {
  4407. this.semicolon();
  4408. }
  4409. }
  4410. tsParseSignatureMember(kind, node) {
  4411. this.tsFillSignature(types.colon, node);
  4412. this.tsParseTypeMemberSemicolon();
  4413. return this.finishNode(node, kind);
  4414. }
  4415. tsIsUnambiguouslyIndexSignature() {
  4416. this.next();
  4417. return this.eat(types.name) && this.match(types.colon);
  4418. }
  4419. tsTryParseIndexSignature(node) {
  4420. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4421. return undefined;
  4422. }
  4423. this.expect(types.bracketL);
  4424. const id = this.parseIdentifier();
  4425. id.typeAnnotation = this.tsParseTypeAnnotation();
  4426. this.resetEndLocation(id);
  4427. this.expect(types.bracketR);
  4428. node.parameters = [id];
  4429. const type = this.tsTryParseTypeAnnotation();
  4430. if (type) node.typeAnnotation = type;
  4431. this.tsParseTypeMemberSemicolon();
  4432. return this.finishNode(node, "TSIndexSignature");
  4433. }
  4434. tsParsePropertyOrMethodSignature(node, readonly) {
  4435. if (this.eat(types.question)) node.optional = true;
  4436. const nodeAny = node;
  4437. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  4438. const method = nodeAny;
  4439. this.tsFillSignature(types.colon, method);
  4440. this.tsParseTypeMemberSemicolon();
  4441. return this.finishNode(method, "TSMethodSignature");
  4442. } else {
  4443. const property = nodeAny;
  4444. if (readonly) property.readonly = true;
  4445. const type = this.tsTryParseTypeAnnotation();
  4446. if (type) property.typeAnnotation = type;
  4447. this.tsParseTypeMemberSemicolon();
  4448. return this.finishNode(property, "TSPropertySignature");
  4449. }
  4450. }
  4451. tsParseTypeMember() {
  4452. const node = this.startNode();
  4453. if (this.match(types.parenL) || this.isRelational("<")) {
  4454. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4455. }
  4456. if (this.match(types._new)) {
  4457. const id = this.startNode();
  4458. this.next();
  4459. if (this.match(types.parenL) || this.isRelational("<")) {
  4460. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4461. } else {
  4462. node.key = this.createIdentifier(id, "new");
  4463. return this.tsParsePropertyOrMethodSignature(node, false);
  4464. }
  4465. }
  4466. const readonly = !!this.tsParseModifier(["readonly"]);
  4467. const idx = this.tsTryParseIndexSignature(node);
  4468. if (idx) {
  4469. if (readonly) node.readonly = true;
  4470. return idx;
  4471. }
  4472. this.parsePropertyName(node, false);
  4473. return this.tsParsePropertyOrMethodSignature(node, readonly);
  4474. }
  4475. tsParseTypeLiteral() {
  4476. const node = this.startNode();
  4477. node.members = this.tsParseObjectTypeMembers();
  4478. return this.finishNode(node, "TSTypeLiteral");
  4479. }
  4480. tsParseObjectTypeMembers() {
  4481. this.expect(types.braceL);
  4482. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4483. this.expect(types.braceR);
  4484. return members;
  4485. }
  4486. tsIsStartOfMappedType() {
  4487. this.next();
  4488. if (this.eat(types.plusMin)) {
  4489. return this.isContextual("readonly");
  4490. }
  4491. if (this.isContextual("readonly")) {
  4492. this.next();
  4493. }
  4494. if (!this.match(types.bracketL)) {
  4495. return false;
  4496. }
  4497. this.next();
  4498. if (!this.tsIsIdentifier()) {
  4499. return false;
  4500. }
  4501. this.next();
  4502. return this.match(types._in);
  4503. }
  4504. tsParseMappedTypeParameter() {
  4505. const node = this.startNode();
  4506. node.name = this.parseIdentifierName(node.start);
  4507. node.constraint = this.tsExpectThenParseType(types._in);
  4508. return this.finishNode(node, "TSTypeParameter");
  4509. }
  4510. tsParseMappedType() {
  4511. const node = this.startNode();
  4512. this.expect(types.braceL);
  4513. if (this.match(types.plusMin)) {
  4514. node.readonly = this.state.value;
  4515. this.next();
  4516. this.expectContextual("readonly");
  4517. } else if (this.eatContextual("readonly")) {
  4518. node.readonly = true;
  4519. }
  4520. this.expect(types.bracketL);
  4521. node.typeParameter = this.tsParseMappedTypeParameter();
  4522. this.expect(types.bracketR);
  4523. if (this.match(types.plusMin)) {
  4524. node.optional = this.state.value;
  4525. this.next();
  4526. this.expect(types.question);
  4527. } else if (this.eat(types.question)) {
  4528. node.optional = true;
  4529. }
  4530. node.typeAnnotation = this.tsTryParseType();
  4531. this.semicolon();
  4532. this.expect(types.braceR);
  4533. return this.finishNode(node, "TSMappedType");
  4534. }
  4535. tsParseTupleType() {
  4536. const node = this.startNode();
  4537. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4538. let seenOptionalElement = false;
  4539. node.elementTypes.forEach(elementNode => {
  4540. if (elementNode.type === "TSOptionalType") {
  4541. seenOptionalElement = true;
  4542. } else if (seenOptionalElement && elementNode.type !== "TSRestType") {
  4543. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4544. }
  4545. });
  4546. return this.finishNode(node, "TSTupleType");
  4547. }
  4548. tsParseTupleElementType() {
  4549. if (this.match(types.ellipsis)) {
  4550. const restNode = this.startNode();
  4551. this.next();
  4552. restNode.typeAnnotation = this.tsParseType();
  4553. if (this.match(types.comma) && this.lookaheadCharCode() !== 93) {
  4554. this.raiseRestNotLast(this.state.start);
  4555. }
  4556. return this.finishNode(restNode, "TSRestType");
  4557. }
  4558. const type = this.tsParseType();
  4559. if (this.eat(types.question)) {
  4560. const optionalTypeNode = this.startNodeAtNode(type);
  4561. optionalTypeNode.typeAnnotation = type;
  4562. return this.finishNode(optionalTypeNode, "TSOptionalType");
  4563. }
  4564. return type;
  4565. }
  4566. tsParseParenthesizedType() {
  4567. const node = this.startNode();
  4568. this.expect(types.parenL);
  4569. node.typeAnnotation = this.tsParseType();
  4570. this.expect(types.parenR);
  4571. return this.finishNode(node, "TSParenthesizedType");
  4572. }
  4573. tsParseFunctionOrConstructorType(type) {
  4574. const node = this.startNode();
  4575. if (type === "TSConstructorType") {
  4576. this.expect(types._new);
  4577. }
  4578. this.tsFillSignature(types.arrow, node);
  4579. return this.finishNode(node, type);
  4580. }
  4581. tsParseLiteralTypeNode() {
  4582. const node = this.startNode();
  4583. node.literal = (() => {
  4584. switch (this.state.type) {
  4585. case types.num:
  4586. case types.string:
  4587. case types._true:
  4588. case types._false:
  4589. return this.parseExprAtom();
  4590. default:
  4591. throw this.unexpected();
  4592. }
  4593. })();
  4594. return this.finishNode(node, "TSLiteralType");
  4595. }
  4596. tsParseTemplateLiteralType() {
  4597. const node = this.startNode();
  4598. const templateNode = this.parseTemplate(false);
  4599. if (templateNode.expressions.length > 0) {
  4600. this.raise(templateNode.expressions[0].start, TSErrors.TemplateTypeHasSubstitution);
  4601. }
  4602. node.literal = templateNode;
  4603. return this.finishNode(node, "TSLiteralType");
  4604. }
  4605. tsParseThisTypeOrThisTypePredicate() {
  4606. const thisKeyword = this.tsParseThisTypeNode();
  4607. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4608. return this.tsParseThisTypePredicate(thisKeyword);
  4609. } else {
  4610. return thisKeyword;
  4611. }
  4612. }
  4613. tsParseNonArrayType() {
  4614. switch (this.state.type) {
  4615. case types.name:
  4616. case types._void:
  4617. case types._null:
  4618. {
  4619. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4620. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4621. const node = this.startNode();
  4622. this.next();
  4623. return this.finishNode(node, type);
  4624. }
  4625. return this.tsParseTypeReference();
  4626. }
  4627. case types.string:
  4628. case types.num:
  4629. case types._true:
  4630. case types._false:
  4631. return this.tsParseLiteralTypeNode();
  4632. case types.plusMin:
  4633. if (this.state.value === "-") {
  4634. const node = this.startNode();
  4635. if (this.lookahead().type !== types.num) {
  4636. throw this.unexpected();
  4637. }
  4638. node.literal = this.parseMaybeUnary();
  4639. return this.finishNode(node, "TSLiteralType");
  4640. }
  4641. break;
  4642. case types._this:
  4643. return this.tsParseThisTypeOrThisTypePredicate();
  4644. case types._typeof:
  4645. return this.tsParseTypeQuery();
  4646. case types._import:
  4647. return this.tsParseImportType();
  4648. case types.braceL:
  4649. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4650. case types.bracketL:
  4651. return this.tsParseTupleType();
  4652. case types.parenL:
  4653. return this.tsParseParenthesizedType();
  4654. case types.backQuote:
  4655. return this.tsParseTemplateLiteralType();
  4656. }
  4657. throw this.unexpected();
  4658. }
  4659. tsParseArrayTypeOrHigher() {
  4660. let type = this.tsParseNonArrayType();
  4661. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4662. if (this.match(types.bracketR)) {
  4663. const node = this.startNodeAtNode(type);
  4664. node.elementType = type;
  4665. this.expect(types.bracketR);
  4666. type = this.finishNode(node, "TSArrayType");
  4667. } else {
  4668. const node = this.startNodeAtNode(type);
  4669. node.objectType = type;
  4670. node.indexType = this.tsParseType();
  4671. this.expect(types.bracketR);
  4672. type = this.finishNode(node, "TSIndexedAccessType");
  4673. }
  4674. }
  4675. return type;
  4676. }
  4677. tsParseTypeOperator(operator) {
  4678. const node = this.startNode();
  4679. this.expectContextual(operator);
  4680. node.operator = operator;
  4681. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4682. if (operator === "readonly") {
  4683. this.tsCheckTypeAnnotationForReadOnly(node);
  4684. }
  4685. return this.finishNode(node, "TSTypeOperator");
  4686. }
  4687. tsCheckTypeAnnotationForReadOnly(node) {
  4688. switch (node.typeAnnotation.type) {
  4689. case "TSTupleType":
  4690. case "TSArrayType":
  4691. return;
  4692. default:
  4693. this.raise(node.start, TSErrors.UnexpectedReadonly);
  4694. }
  4695. }
  4696. tsParseInferType() {
  4697. const node = this.startNode();
  4698. this.expectContextual("infer");
  4699. const typeParameter = this.startNode();
  4700. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4701. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4702. return this.finishNode(node, "TSInferType");
  4703. }
  4704. tsParseTypeOperatorOrHigher() {
  4705. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4706. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4707. }
  4708. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4709. this.eat(operator);
  4710. let type = parseConstituentType();
  4711. if (this.match(operator)) {
  4712. const types = [type];
  4713. while (this.eat(operator)) {
  4714. types.push(parseConstituentType());
  4715. }
  4716. const node = this.startNodeAtNode(type);
  4717. node.types = types;
  4718. type = this.finishNode(node, kind);
  4719. }
  4720. return type;
  4721. }
  4722. tsParseIntersectionTypeOrHigher() {
  4723. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4724. }
  4725. tsParseUnionTypeOrHigher() {
  4726. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4727. }
  4728. tsIsStartOfFunctionType() {
  4729. if (this.isRelational("<")) {
  4730. return true;
  4731. }
  4732. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4733. }
  4734. tsSkipParameterStart() {
  4735. if (this.match(types.name) || this.match(types._this)) {
  4736. this.next();
  4737. return true;
  4738. }
  4739. if (this.match(types.braceL)) {
  4740. let braceStackCounter = 1;
  4741. this.next();
  4742. while (braceStackCounter > 0) {
  4743. if (this.match(types.braceL)) {
  4744. ++braceStackCounter;
  4745. } else if (this.match(types.braceR)) {
  4746. --braceStackCounter;
  4747. }
  4748. this.next();
  4749. }
  4750. return true;
  4751. }
  4752. if (this.match(types.bracketL)) {
  4753. let braceStackCounter = 1;
  4754. this.next();
  4755. while (braceStackCounter > 0) {
  4756. if (this.match(types.bracketL)) {
  4757. ++braceStackCounter;
  4758. } else if (this.match(types.bracketR)) {
  4759. --braceStackCounter;
  4760. }
  4761. this.next();
  4762. }
  4763. return true;
  4764. }
  4765. return false;
  4766. }
  4767. tsIsUnambiguouslyStartOfFunctionType() {
  4768. this.next();
  4769. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4770. return true;
  4771. }
  4772. if (this.tsSkipParameterStart()) {
  4773. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4774. return true;
  4775. }
  4776. if (this.match(types.parenR)) {
  4777. this.next();
  4778. if (this.match(types.arrow)) {
  4779. return true;
  4780. }
  4781. }
  4782. }
  4783. return false;
  4784. }
  4785. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4786. return this.tsInType(() => {
  4787. const t = this.startNode();
  4788. this.expect(returnToken);
  4789. const asserts = this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4790. if (asserts && this.match(types._this)) {
  4791. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4792. if (thisTypePredicate.type === "TSThisType") {
  4793. const node = this.startNodeAtNode(t);
  4794. node.parameterName = thisTypePredicate;
  4795. node.asserts = true;
  4796. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4797. } else {
  4798. thisTypePredicate.asserts = true;
  4799. }
  4800. t.typeAnnotation = thisTypePredicate;
  4801. return this.finishNode(t, "TSTypeAnnotation");
  4802. }
  4803. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4804. if (!typePredicateVariable) {
  4805. if (!asserts) {
  4806. return this.tsParseTypeAnnotation(false, t);
  4807. }
  4808. const node = this.startNodeAtNode(t);
  4809. node.parameterName = this.parseIdentifier();
  4810. node.asserts = asserts;
  4811. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4812. return this.finishNode(t, "TSTypeAnnotation");
  4813. }
  4814. const type = this.tsParseTypeAnnotation(false);
  4815. const node = this.startNodeAtNode(t);
  4816. node.parameterName = typePredicateVariable;
  4817. node.typeAnnotation = type;
  4818. node.asserts = asserts;
  4819. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4820. return this.finishNode(t, "TSTypeAnnotation");
  4821. });
  4822. }
  4823. tsTryParseTypeOrTypePredicateAnnotation() {
  4824. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4825. }
  4826. tsTryParseTypeAnnotation() {
  4827. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4828. }
  4829. tsTryParseType() {
  4830. return this.tsEatThenParseType(types.colon);
  4831. }
  4832. tsParseTypePredicatePrefix() {
  4833. const id = this.parseIdentifier();
  4834. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4835. this.next();
  4836. return id;
  4837. }
  4838. }
  4839. tsParseTypePredicateAsserts() {
  4840. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4841. return false;
  4842. }
  4843. const containsEsc = this.state.containsEsc;
  4844. this.next();
  4845. if (!this.match(types.name) && !this.match(types._this)) {
  4846. return false;
  4847. }
  4848. if (containsEsc) {
  4849. this.raise(this.state.lastTokStart, Errors.InvalidEscapedReservedWord, "asserts");
  4850. }
  4851. return true;
  4852. }
  4853. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  4854. this.tsInType(() => {
  4855. if (eatColon) this.expect(types.colon);
  4856. t.typeAnnotation = this.tsParseType();
  4857. });
  4858. return this.finishNode(t, "TSTypeAnnotation");
  4859. }
  4860. tsParseType() {
  4861. assert(this.state.inType);
  4862. const type = this.tsParseNonConditionalType();
  4863. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  4864. return type;
  4865. }
  4866. const node = this.startNodeAtNode(type);
  4867. node.checkType = type;
  4868. node.extendsType = this.tsParseNonConditionalType();
  4869. this.expect(types.question);
  4870. node.trueType = this.tsParseType();
  4871. this.expect(types.colon);
  4872. node.falseType = this.tsParseType();
  4873. return this.finishNode(node, "TSConditionalType");
  4874. }
  4875. tsParseNonConditionalType() {
  4876. if (this.tsIsStartOfFunctionType()) {
  4877. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  4878. }
  4879. if (this.match(types._new)) {
  4880. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  4881. }
  4882. return this.tsParseUnionTypeOrHigher();
  4883. }
  4884. tsParseTypeAssertion() {
  4885. const node = this.startNode();
  4886. const _const = this.tsTryNextParseConstantContext();
  4887. node.typeAnnotation = _const || this.tsNextThenParseType();
  4888. this.expectRelational(">");
  4889. node.expression = this.parseMaybeUnary();
  4890. return this.finishNode(node, "TSTypeAssertion");
  4891. }
  4892. tsParseHeritageClause(descriptor) {
  4893. const originalStart = this.state.start;
  4894. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  4895. if (!delimitedList.length) {
  4896. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  4897. }
  4898. return delimitedList;
  4899. }
  4900. tsParseExpressionWithTypeArguments() {
  4901. const node = this.startNode();
  4902. node.expression = this.tsParseEntityName(false);
  4903. if (this.isRelational("<")) {
  4904. node.typeParameters = this.tsParseTypeArguments();
  4905. }
  4906. return this.finishNode(node, "TSExpressionWithTypeArguments");
  4907. }
  4908. tsParseInterfaceDeclaration(node) {
  4909. node.id = this.parseIdentifier();
  4910. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  4911. node.typeParameters = this.tsTryParseTypeParameters();
  4912. if (this.eat(types._extends)) {
  4913. node.extends = this.tsParseHeritageClause("extends");
  4914. }
  4915. const body = this.startNode();
  4916. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  4917. node.body = this.finishNode(body, "TSInterfaceBody");
  4918. return this.finishNode(node, "TSInterfaceDeclaration");
  4919. }
  4920. tsParseTypeAliasDeclaration(node) {
  4921. node.id = this.parseIdentifier();
  4922. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  4923. node.typeParameters = this.tsTryParseTypeParameters();
  4924. node.typeAnnotation = this.tsExpectThenParseType(types.eq);
  4925. this.semicolon();
  4926. return this.finishNode(node, "TSTypeAliasDeclaration");
  4927. }
  4928. tsInNoContext(cb) {
  4929. const oldContext = this.state.context;
  4930. this.state.context = [oldContext[0]];
  4931. try {
  4932. return cb();
  4933. } finally {
  4934. this.state.context = oldContext;
  4935. }
  4936. }
  4937. tsInType(cb) {
  4938. const oldInType = this.state.inType;
  4939. this.state.inType = true;
  4940. try {
  4941. return cb();
  4942. } finally {
  4943. this.state.inType = oldInType;
  4944. }
  4945. }
  4946. tsEatThenParseType(token) {
  4947. return !this.match(token) ? undefined : this.tsNextThenParseType();
  4948. }
  4949. tsExpectThenParseType(token) {
  4950. return this.tsDoThenParseType(() => this.expect(token));
  4951. }
  4952. tsNextThenParseType() {
  4953. return this.tsDoThenParseType(() => this.next());
  4954. }
  4955. tsDoThenParseType(cb) {
  4956. return this.tsInType(() => {
  4957. cb();
  4958. return this.tsParseType();
  4959. });
  4960. }
  4961. tsParseEnumMember() {
  4962. const node = this.startNode();
  4963. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  4964. if (this.eat(types.eq)) {
  4965. node.initializer = this.parseMaybeAssign();
  4966. }
  4967. return this.finishNode(node, "TSEnumMember");
  4968. }
  4969. tsParseEnumDeclaration(node, isConst) {
  4970. if (isConst) node.const = true;
  4971. node.id = this.parseIdentifier();
  4972. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  4973. this.expect(types.braceL);
  4974. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  4975. this.expect(types.braceR);
  4976. return this.finishNode(node, "TSEnumDeclaration");
  4977. }
  4978. tsParseModuleBlock() {
  4979. const node = this.startNode();
  4980. this.scope.enter(SCOPE_OTHER);
  4981. this.expect(types.braceL);
  4982. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  4983. this.scope.exit();
  4984. return this.finishNode(node, "TSModuleBlock");
  4985. }
  4986. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  4987. node.id = this.parseIdentifier();
  4988. if (!nested) {
  4989. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  4990. }
  4991. if (this.eat(types.dot)) {
  4992. const inner = this.startNode();
  4993. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  4994. node.body = inner;
  4995. } else {
  4996. this.scope.enter(SCOPE_TS_MODULE);
  4997. this.prodParam.enter(PARAM);
  4998. node.body = this.tsParseModuleBlock();
  4999. this.prodParam.exit();
  5000. this.scope.exit();
  5001. }
  5002. return this.finishNode(node, "TSModuleDeclaration");
  5003. }
  5004. tsParseAmbientExternalModuleDeclaration(node) {
  5005. if (this.isContextual("global")) {
  5006. node.global = true;
  5007. node.id = this.parseIdentifier();
  5008. } else if (this.match(types.string)) {
  5009. node.id = this.parseExprAtom();
  5010. } else {
  5011. this.unexpected();
  5012. }
  5013. if (this.match(types.braceL)) {
  5014. this.scope.enter(SCOPE_TS_MODULE);
  5015. this.prodParam.enter(PARAM);
  5016. node.body = this.tsParseModuleBlock();
  5017. this.prodParam.exit();
  5018. this.scope.exit();
  5019. } else {
  5020. this.semicolon();
  5021. }
  5022. return this.finishNode(node, "TSModuleDeclaration");
  5023. }
  5024. tsParseImportEqualsDeclaration(node, isExport) {
  5025. node.isExport = isExport || false;
  5026. node.id = this.parseIdentifier();
  5027. this.checkLVal(node.id, BIND_LEXICAL, undefined, "import equals declaration");
  5028. this.expect(types.eq);
  5029. node.moduleReference = this.tsParseModuleReference();
  5030. this.semicolon();
  5031. return this.finishNode(node, "TSImportEqualsDeclaration");
  5032. }
  5033. tsIsExternalModuleReference() {
  5034. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5035. }
  5036. tsParseModuleReference() {
  5037. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5038. }
  5039. tsParseExternalModuleReference() {
  5040. const node = this.startNode();
  5041. this.expectContextual("require");
  5042. this.expect(types.parenL);
  5043. if (!this.match(types.string)) {
  5044. throw this.unexpected();
  5045. }
  5046. node.expression = this.parseExprAtom();
  5047. this.expect(types.parenR);
  5048. return this.finishNode(node, "TSExternalModuleReference");
  5049. }
  5050. tsLookAhead(f) {
  5051. const state = this.state.clone();
  5052. const res = f();
  5053. this.state = state;
  5054. return res;
  5055. }
  5056. tsTryParseAndCatch(f) {
  5057. const result = this.tryParse(abort => f() || abort());
  5058. if (result.aborted || !result.node) return undefined;
  5059. if (result.error) this.state = result.failState;
  5060. return result.node;
  5061. }
  5062. tsTryParse(f) {
  5063. const state = this.state.clone();
  5064. const result = f();
  5065. if (result !== undefined && result !== false) {
  5066. return result;
  5067. } else {
  5068. this.state = state;
  5069. return undefined;
  5070. }
  5071. }
  5072. tsTryParseDeclare(nany) {
  5073. if (this.isLineTerminator()) {
  5074. return;
  5075. }
  5076. let starttype = this.state.type;
  5077. let kind;
  5078. if (this.isContextual("let")) {
  5079. starttype = types._var;
  5080. kind = "let";
  5081. }
  5082. switch (starttype) {
  5083. case types._function:
  5084. return this.parseFunctionStatement(nany, false, true);
  5085. case types._class:
  5086. nany.declare = true;
  5087. return this.parseClass(nany, true, false);
  5088. case types._const:
  5089. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5090. this.expect(types._const);
  5091. this.expectContextual("enum");
  5092. return this.tsParseEnumDeclaration(nany, true);
  5093. }
  5094. case types._var:
  5095. kind = kind || this.state.value;
  5096. return this.parseVarStatement(nany, kind);
  5097. case types.name:
  5098. {
  5099. const value = this.state.value;
  5100. if (value === "global") {
  5101. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5102. } else {
  5103. return this.tsParseDeclaration(nany, value, true);
  5104. }
  5105. }
  5106. }
  5107. }
  5108. tsTryParseExportDeclaration() {
  5109. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5110. }
  5111. tsParseExpressionStatement(node, expr) {
  5112. switch (expr.name) {
  5113. case "declare":
  5114. {
  5115. const declaration = this.tsTryParseDeclare(node);
  5116. if (declaration) {
  5117. declaration.declare = true;
  5118. return declaration;
  5119. }
  5120. break;
  5121. }
  5122. case "global":
  5123. if (this.match(types.braceL)) {
  5124. this.scope.enter(SCOPE_TS_MODULE);
  5125. this.prodParam.enter(PARAM);
  5126. const mod = node;
  5127. mod.global = true;
  5128. mod.id = expr;
  5129. mod.body = this.tsParseModuleBlock();
  5130. this.scope.exit();
  5131. this.prodParam.exit();
  5132. return this.finishNode(mod, "TSModuleDeclaration");
  5133. }
  5134. break;
  5135. default:
  5136. return this.tsParseDeclaration(node, expr.name, false);
  5137. }
  5138. }
  5139. tsParseDeclaration(node, value, next) {
  5140. switch (value) {
  5141. case "abstract":
  5142. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  5143. const cls = node;
  5144. cls.abstract = true;
  5145. if (next) {
  5146. this.next();
  5147. if (!this.match(types._class)) {
  5148. this.unexpected(null, types._class);
  5149. }
  5150. }
  5151. return this.parseClass(cls, true, false);
  5152. }
  5153. break;
  5154. case "enum":
  5155. if (next || this.match(types.name)) {
  5156. if (next) this.next();
  5157. return this.tsParseEnumDeclaration(node, false);
  5158. }
  5159. break;
  5160. case "interface":
  5161. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5162. if (next) this.next();
  5163. return this.tsParseInterfaceDeclaration(node);
  5164. }
  5165. break;
  5166. case "module":
  5167. if (next) this.next();
  5168. if (this.match(types.string)) {
  5169. return this.tsParseAmbientExternalModuleDeclaration(node);
  5170. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5171. return this.tsParseModuleOrNamespaceDeclaration(node);
  5172. }
  5173. break;
  5174. case "namespace":
  5175. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5176. if (next) this.next();
  5177. return this.tsParseModuleOrNamespaceDeclaration(node);
  5178. }
  5179. break;
  5180. case "type":
  5181. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5182. if (next) this.next();
  5183. return this.tsParseTypeAliasDeclaration(node);
  5184. }
  5185. break;
  5186. }
  5187. }
  5188. tsCheckLineTerminatorAndMatch(tokenType, next) {
  5189. return (next || this.match(tokenType)) && !this.isLineTerminator();
  5190. }
  5191. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5192. if (!this.isRelational("<")) {
  5193. return undefined;
  5194. }
  5195. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5196. const oldYieldPos = this.state.yieldPos;
  5197. const oldAwaitPos = this.state.awaitPos;
  5198. this.state.maybeInArrowParameters = true;
  5199. this.state.yieldPos = -1;
  5200. this.state.awaitPos = -1;
  5201. const res = this.tsTryParseAndCatch(() => {
  5202. const node = this.startNodeAt(startPos, startLoc);
  5203. node.typeParameters = this.tsParseTypeParameters();
  5204. super.parseFunctionParams(node);
  5205. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5206. this.expect(types.arrow);
  5207. return node;
  5208. });
  5209. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5210. this.state.yieldPos = oldYieldPos;
  5211. this.state.awaitPos = oldAwaitPos;
  5212. if (!res) {
  5213. return undefined;
  5214. }
  5215. return this.parseArrowExpression(res, null, true);
  5216. }
  5217. tsParseTypeArguments() {
  5218. const node = this.startNode();
  5219. node.params = this.tsInType(() => this.tsInNoContext(() => {
  5220. this.expectRelational("<");
  5221. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  5222. }));
  5223. this.state.exprAllowed = false;
  5224. this.expectRelational(">");
  5225. return this.finishNode(node, "TSTypeParameterInstantiation");
  5226. }
  5227. tsIsDeclarationStart() {
  5228. if (this.match(types.name)) {
  5229. switch (this.state.value) {
  5230. case "abstract":
  5231. case "declare":
  5232. case "enum":
  5233. case "interface":
  5234. case "module":
  5235. case "namespace":
  5236. case "type":
  5237. return true;
  5238. }
  5239. }
  5240. return false;
  5241. }
  5242. isExportDefaultSpecifier() {
  5243. if (this.tsIsDeclarationStart()) return false;
  5244. return super.isExportDefaultSpecifier();
  5245. }
  5246. parseAssignableListItem(allowModifiers, decorators) {
  5247. const startPos = this.state.start;
  5248. const startLoc = this.state.startLoc;
  5249. let accessibility;
  5250. let readonly = false;
  5251. if (allowModifiers) {
  5252. accessibility = this.parseAccessModifier();
  5253. readonly = !!this.tsParseModifier(["readonly"]);
  5254. }
  5255. const left = this.parseMaybeDefault();
  5256. this.parseAssignableListItemTypes(left);
  5257. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  5258. if (accessibility || readonly) {
  5259. const pp = this.startNodeAt(startPos, startLoc);
  5260. if (decorators.length) {
  5261. pp.decorators = decorators;
  5262. }
  5263. if (accessibility) pp.accessibility = accessibility;
  5264. if (readonly) pp.readonly = readonly;
  5265. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  5266. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  5267. }
  5268. pp.parameter = elt;
  5269. return this.finishNode(pp, "TSParameterProperty");
  5270. }
  5271. if (decorators.length) {
  5272. left.decorators = decorators;
  5273. }
  5274. return elt;
  5275. }
  5276. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5277. if (this.match(types.colon)) {
  5278. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5279. }
  5280. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  5281. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  5282. this.finishNode(node, bodilessType);
  5283. return;
  5284. }
  5285. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5286. }
  5287. registerFunctionStatementId(node) {
  5288. if (!node.body && node.id) {
  5289. this.checkLVal(node.id, BIND_TS_AMBIENT, null, "function name");
  5290. } else {
  5291. super.registerFunctionStatementId(...arguments);
  5292. }
  5293. }
  5294. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5295. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5296. this.state.exprAllowed = false;
  5297. this.next();
  5298. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5299. nonNullExpression.expression = base;
  5300. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5301. }
  5302. if (this.isRelational("<")) {
  5303. const result = this.tsTryParseAndCatch(() => {
  5304. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5305. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5306. if (asyncArrowFn) {
  5307. return asyncArrowFn;
  5308. }
  5309. }
  5310. const node = this.startNodeAt(startPos, startLoc);
  5311. node.callee = base;
  5312. const typeArguments = this.tsParseTypeArguments();
  5313. if (typeArguments) {
  5314. if (!noCalls && this.eat(types.parenL)) {
  5315. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5316. node.typeParameters = typeArguments;
  5317. return this.finishCallExpression(node, state.optionalChainMember);
  5318. } else if (this.match(types.backQuote)) {
  5319. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments);
  5320. }
  5321. }
  5322. this.unexpected();
  5323. });
  5324. if (result) return result;
  5325. }
  5326. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5327. }
  5328. parseNewArguments(node) {
  5329. if (this.isRelational("<")) {
  5330. const typeParameters = this.tsTryParseAndCatch(() => {
  5331. const args = this.tsParseTypeArguments();
  5332. if (!this.match(types.parenL)) this.unexpected();
  5333. return args;
  5334. });
  5335. if (typeParameters) {
  5336. node.typeParameters = typeParameters;
  5337. }
  5338. }
  5339. super.parseNewArguments(node);
  5340. }
  5341. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  5342. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5343. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5344. node.expression = left;
  5345. const _const = this.tsTryNextParseConstantContext();
  5346. if (_const) {
  5347. node.typeAnnotation = _const;
  5348. } else {
  5349. node.typeAnnotation = this.tsNextThenParseType();
  5350. }
  5351. this.finishNode(node, "TSAsExpression");
  5352. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  5353. }
  5354. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn);
  5355. }
  5356. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5357. checkDuplicateExports() {}
  5358. parseImport(node) {
  5359. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5360. const ahead = this.lookahead();
  5361. if (this.match(types.name) && ahead.type === types.eq) {
  5362. return this.tsParseImportEqualsDeclaration(node);
  5363. }
  5364. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  5365. node.importKind = "type";
  5366. this.next();
  5367. } else {
  5368. node.importKind = "value";
  5369. }
  5370. }
  5371. const importNode = super.parseImport(node);
  5372. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5373. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5374. }
  5375. return importNode;
  5376. }
  5377. parseExport(node) {
  5378. if (this.match(types._import)) {
  5379. this.expect(types._import);
  5380. return this.tsParseImportEqualsDeclaration(node, true);
  5381. } else if (this.eat(types.eq)) {
  5382. const assign = node;
  5383. assign.expression = this.parseExpression();
  5384. this.semicolon();
  5385. return this.finishNode(assign, "TSExportAssignment");
  5386. } else if (this.eatContextual("as")) {
  5387. const decl = node;
  5388. this.expectContextual("namespace");
  5389. decl.id = this.parseIdentifier();
  5390. this.semicolon();
  5391. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5392. } else {
  5393. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5394. this.next();
  5395. node.exportKind = "type";
  5396. } else {
  5397. node.exportKind = "value";
  5398. }
  5399. return super.parseExport(node);
  5400. }
  5401. }
  5402. isAbstractClass() {
  5403. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5404. }
  5405. parseExportDefaultExpression() {
  5406. if (this.isAbstractClass()) {
  5407. const cls = this.startNode();
  5408. this.next();
  5409. this.parseClass(cls, true, true);
  5410. cls.abstract = true;
  5411. return cls;
  5412. }
  5413. if (this.state.value === "interface") {
  5414. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5415. if (result) return result;
  5416. }
  5417. return super.parseExportDefaultExpression();
  5418. }
  5419. parseStatementContent(context, topLevel) {
  5420. if (this.state.type === types._const) {
  5421. const ahead = this.lookahead();
  5422. if (ahead.type === types.name && ahead.value === "enum") {
  5423. const node = this.startNode();
  5424. this.expect(types._const);
  5425. this.expectContextual("enum");
  5426. return this.tsParseEnumDeclaration(node, true);
  5427. }
  5428. }
  5429. return super.parseStatementContent(context, topLevel);
  5430. }
  5431. parseAccessModifier() {
  5432. return this.tsParseModifier(["public", "protected", "private"]);
  5433. }
  5434. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  5435. this.tsParseModifiers(member, ["declare"]);
  5436. const accessibility = this.parseAccessModifier();
  5437. if (accessibility) member.accessibility = accessibility;
  5438. this.tsParseModifiers(member, ["declare"]);
  5439. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  5440. }
  5441. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  5442. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5443. const idx = this.tsTryParseIndexSignature(member);
  5444. if (idx) {
  5445. classBody.body.push(idx);
  5446. if (member.abstract) {
  5447. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5448. }
  5449. if (isStatic) {
  5450. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5451. }
  5452. if (member.accessibility) {
  5453. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5454. }
  5455. return;
  5456. }
  5457. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  5458. }
  5459. parsePostMemberNameModifiers(methodOrProp) {
  5460. const optional = this.eat(types.question);
  5461. if (optional) methodOrProp.optional = true;
  5462. if (methodOrProp.readonly && this.match(types.parenL)) {
  5463. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5464. }
  5465. if (methodOrProp.declare && this.match(types.parenL)) {
  5466. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5467. }
  5468. }
  5469. parseExpressionStatement(node, expr) {
  5470. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5471. return decl || super.parseExpressionStatement(node, expr);
  5472. }
  5473. shouldParseExportDeclaration() {
  5474. if (this.tsIsDeclarationStart()) return true;
  5475. return super.shouldParseExportDeclaration();
  5476. }
  5477. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  5478. if (!refNeedsArrowPos || !this.match(types.question)) {
  5479. return super.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  5480. }
  5481. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  5482. if (!result.node) {
  5483. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5484. return expr;
  5485. }
  5486. if (result.error) this.state = result.failState;
  5487. return result.node;
  5488. }
  5489. parseParenItem(node, startPos, startLoc) {
  5490. node = super.parseParenItem(node, startPos, startLoc);
  5491. if (this.eat(types.question)) {
  5492. node.optional = true;
  5493. this.resetEndLocation(node);
  5494. }
  5495. if (this.match(types.colon)) {
  5496. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5497. typeCastNode.expression = node;
  5498. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5499. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5500. }
  5501. return node;
  5502. }
  5503. parseExportDeclaration(node) {
  5504. const startPos = this.state.start;
  5505. const startLoc = this.state.startLoc;
  5506. const isDeclare = this.eatContextual("declare");
  5507. let declaration;
  5508. if (this.match(types.name)) {
  5509. declaration = this.tsTryParseExportDeclaration();
  5510. }
  5511. if (!declaration) {
  5512. declaration = super.parseExportDeclaration(node);
  5513. }
  5514. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5515. node.exportKind = "type";
  5516. }
  5517. if (declaration && isDeclare) {
  5518. this.resetStartLocation(declaration, startPos, startLoc);
  5519. declaration.declare = true;
  5520. }
  5521. return declaration;
  5522. }
  5523. parseClassId(node, isStatement, optionalId) {
  5524. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5525. return;
  5526. }
  5527. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5528. const typeParameters = this.tsTryParseTypeParameters();
  5529. if (typeParameters) node.typeParameters = typeParameters;
  5530. }
  5531. parseClassPropertyAnnotation(node) {
  5532. if (!node.optional && this.eat(types.bang)) {
  5533. node.definite = true;
  5534. }
  5535. const type = this.tsTryParseTypeAnnotation();
  5536. if (type) node.typeAnnotation = type;
  5537. }
  5538. parseClassProperty(node) {
  5539. this.parseClassPropertyAnnotation(node);
  5540. if (node.declare && this.match(types.equal)) {
  5541. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5542. }
  5543. return super.parseClassProperty(node);
  5544. }
  5545. parseClassPrivateProperty(node) {
  5546. if (node.abstract) {
  5547. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  5548. }
  5549. if (node.accessibility) {
  5550. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  5551. }
  5552. this.parseClassPropertyAnnotation(node);
  5553. return super.parseClassPrivateProperty(node);
  5554. }
  5555. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5556. const typeParameters = this.tsTryParseTypeParameters();
  5557. if (typeParameters) method.typeParameters = typeParameters;
  5558. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5559. }
  5560. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5561. const typeParameters = this.tsTryParseTypeParameters();
  5562. if (typeParameters) method.typeParameters = typeParameters;
  5563. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5564. }
  5565. parseClassSuper(node) {
  5566. super.parseClassSuper(node);
  5567. if (node.superClass && this.isRelational("<")) {
  5568. node.superTypeParameters = this.tsParseTypeArguments();
  5569. }
  5570. if (this.eatContextual("implements")) {
  5571. node.implements = this.tsParseHeritageClause("implements");
  5572. }
  5573. }
  5574. parseObjPropValue(prop, ...args) {
  5575. const typeParameters = this.tsTryParseTypeParameters();
  5576. if (typeParameters) prop.typeParameters = typeParameters;
  5577. super.parseObjPropValue(prop, ...args);
  5578. }
  5579. parseFunctionParams(node, allowModifiers) {
  5580. const typeParameters = this.tsTryParseTypeParameters();
  5581. if (typeParameters) node.typeParameters = typeParameters;
  5582. super.parseFunctionParams(node, allowModifiers);
  5583. }
  5584. parseVarId(decl, kind) {
  5585. super.parseVarId(decl, kind);
  5586. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5587. decl.definite = true;
  5588. }
  5589. const type = this.tsTryParseTypeAnnotation();
  5590. if (type) {
  5591. decl.id.typeAnnotation = type;
  5592. this.resetEndLocation(decl.id);
  5593. }
  5594. }
  5595. parseAsyncArrowFromCallExpression(node, call) {
  5596. if (this.match(types.colon)) {
  5597. node.returnType = this.tsParseTypeAnnotation();
  5598. }
  5599. return super.parseAsyncArrowFromCallExpression(node, call);
  5600. }
  5601. parseMaybeAssign(...args) {
  5602. let state;
  5603. let jsx;
  5604. let typeCast;
  5605. if (this.match(types.jsxTagStart)) {
  5606. state = this.state.clone();
  5607. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5608. if (!jsx.error) return jsx.node;
  5609. const {
  5610. context
  5611. } = this.state;
  5612. if (context[context.length - 1] === types$1.j_oTag) {
  5613. context.length -= 2;
  5614. } else if (context[context.length - 1] === types$1.j_expr) {
  5615. context.length -= 1;
  5616. }
  5617. }
  5618. if (!(jsx && jsx.error) && !this.isRelational("<")) {
  5619. return super.parseMaybeAssign(...args);
  5620. }
  5621. let typeParameters;
  5622. state = state || this.state.clone();
  5623. const arrow = this.tryParse(abort => {
  5624. typeParameters = this.tsParseTypeParameters();
  5625. const expr = super.parseMaybeAssign(...args);
  5626. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5627. abort();
  5628. }
  5629. if (typeParameters && typeParameters.params.length !== 0) {
  5630. this.resetStartLocationFromNode(expr, typeParameters);
  5631. }
  5632. expr.typeParameters = typeParameters;
  5633. return expr;
  5634. }, state);
  5635. if (!arrow.error && !arrow.aborted) return arrow.node;
  5636. if (!jsx) {
  5637. assert(!this.hasPlugin("jsx"));
  5638. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5639. if (!typeCast.error) return typeCast.node;
  5640. }
  5641. if (jsx && jsx.node) {
  5642. this.state = jsx.failState;
  5643. return jsx.node;
  5644. }
  5645. if (arrow.node) {
  5646. this.state = arrow.failState;
  5647. return arrow.node;
  5648. }
  5649. if (typeCast && typeCast.node) {
  5650. this.state = typeCast.failState;
  5651. return typeCast.node;
  5652. }
  5653. if (jsx && jsx.thrown) throw jsx.error;
  5654. if (arrow.thrown) throw arrow.error;
  5655. if (typeCast && typeCast.thrown) throw typeCast.error;
  5656. throw jsx && jsx.error || arrow.error || typeCast && typeCast.error;
  5657. }
  5658. parseMaybeUnary(refExpressionErrors) {
  5659. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5660. return this.tsParseTypeAssertion();
  5661. } else {
  5662. return super.parseMaybeUnary(refExpressionErrors);
  5663. }
  5664. }
  5665. parseArrow(node) {
  5666. if (this.match(types.colon)) {
  5667. const result = this.tryParse(abort => {
  5668. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5669. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5670. return returnType;
  5671. });
  5672. if (result.aborted) return;
  5673. if (!result.thrown) {
  5674. if (result.error) this.state = result.failState;
  5675. node.returnType = result.node;
  5676. }
  5677. }
  5678. return super.parseArrow(node);
  5679. }
  5680. parseAssignableListItemTypes(param) {
  5681. if (this.eat(types.question)) {
  5682. if (param.type !== "Identifier") {
  5683. this.raise(param.start, TSErrors.PatternIsOptional);
  5684. }
  5685. param.optional = true;
  5686. }
  5687. const type = this.tsTryParseTypeAnnotation();
  5688. if (type) param.typeAnnotation = type;
  5689. this.resetEndLocation(param);
  5690. return param;
  5691. }
  5692. toAssignable(node) {
  5693. switch (node.type) {
  5694. case "TSTypeCastExpression":
  5695. return super.toAssignable(this.typeCastToParameter(node));
  5696. case "TSParameterProperty":
  5697. return super.toAssignable(node);
  5698. case "TSAsExpression":
  5699. case "TSNonNullExpression":
  5700. case "TSTypeAssertion":
  5701. node.expression = this.toAssignable(node.expression);
  5702. return node;
  5703. default:
  5704. return super.toAssignable(node);
  5705. }
  5706. }
  5707. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  5708. switch (expr.type) {
  5709. case "TSTypeCastExpression":
  5710. return;
  5711. case "TSParameterProperty":
  5712. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  5713. return;
  5714. case "TSAsExpression":
  5715. case "TSNonNullExpression":
  5716. case "TSTypeAssertion":
  5717. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  5718. return;
  5719. default:
  5720. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  5721. return;
  5722. }
  5723. }
  5724. parseBindingAtom() {
  5725. switch (this.state.type) {
  5726. case types._this:
  5727. return this.parseIdentifier(true);
  5728. default:
  5729. return super.parseBindingAtom();
  5730. }
  5731. }
  5732. parseMaybeDecoratorArguments(expr) {
  5733. if (this.isRelational("<")) {
  5734. const typeArguments = this.tsParseTypeArguments();
  5735. if (this.match(types.parenL)) {
  5736. const call = super.parseMaybeDecoratorArguments(expr);
  5737. call.typeParameters = typeArguments;
  5738. return call;
  5739. }
  5740. this.unexpected(this.state.start, types.parenL);
  5741. }
  5742. return super.parseMaybeDecoratorArguments(expr);
  5743. }
  5744. isClassMethod() {
  5745. return this.isRelational("<") || super.isClassMethod();
  5746. }
  5747. isClassProperty() {
  5748. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5749. }
  5750. parseMaybeDefault(...args) {
  5751. const node = super.parseMaybeDefault(...args);
  5752. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5753. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  5754. }
  5755. return node;
  5756. }
  5757. getTokenFromCode(code) {
  5758. if (this.state.inType && (code === 62 || code === 60)) {
  5759. return this.finishOp(types.relational, 1);
  5760. } else {
  5761. return super.getTokenFromCode(code);
  5762. }
  5763. }
  5764. toAssignableList(exprList) {
  5765. for (let i = 0; i < exprList.length; i++) {
  5766. const expr = exprList[i];
  5767. if (!expr) continue;
  5768. switch (expr.type) {
  5769. case "TSTypeCastExpression":
  5770. exprList[i] = this.typeCastToParameter(expr);
  5771. break;
  5772. case "TSAsExpression":
  5773. case "TSTypeAssertion":
  5774. if (!this.state.maybeInArrowParameters) {
  5775. exprList[i] = this.typeCastToParameter(expr);
  5776. } else {
  5777. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  5778. }
  5779. break;
  5780. }
  5781. }
  5782. return super.toAssignableList(...arguments);
  5783. }
  5784. typeCastToParameter(node) {
  5785. node.expression.typeAnnotation = node.typeAnnotation;
  5786. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5787. return node.expression;
  5788. }
  5789. toReferencedList(exprList, isInParens) {
  5790. for (let i = 0; i < exprList.length; i++) {
  5791. const expr = exprList[i];
  5792. if (expr && expr.type === "TSTypeCastExpression") {
  5793. this.raise(expr.start, TSErrors.UnexpectedTypeAnnotation);
  5794. }
  5795. }
  5796. return exprList;
  5797. }
  5798. shouldParseArrow() {
  5799. return this.match(types.colon) || super.shouldParseArrow();
  5800. }
  5801. shouldParseAsyncArrow() {
  5802. return this.match(types.colon) || super.shouldParseAsyncArrow();
  5803. }
  5804. canHaveLeadingDecorator() {
  5805. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  5806. }
  5807. jsxParseOpeningElementAfterName(node) {
  5808. if (this.isRelational("<")) {
  5809. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  5810. if (typeArguments) node.typeParameters = typeArguments;
  5811. }
  5812. return super.jsxParseOpeningElementAfterName(node);
  5813. }
  5814. getGetterSetterExpectedParamCount(method) {
  5815. const baseCount = super.getGetterSetterExpectedParamCount(method);
  5816. const firstParam = method.params[0];
  5817. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  5818. return hasContextParam ? baseCount + 1 : baseCount;
  5819. }
  5820. });
  5821. types.placeholder = new TokenType("%%", {
  5822. startsExpr: true
  5823. });
  5824. var placeholders = (superClass => class extends superClass {
  5825. parsePlaceholder(expectedNode) {
  5826. if (this.match(types.placeholder)) {
  5827. const node = this.startNode();
  5828. this.next();
  5829. this.assertNoSpace("Unexpected space in placeholder.");
  5830. node.name = super.parseIdentifier(true);
  5831. this.assertNoSpace("Unexpected space in placeholder.");
  5832. this.expect(types.placeholder);
  5833. return this.finishPlaceholder(node, expectedNode);
  5834. }
  5835. }
  5836. finishPlaceholder(node, expectedNode) {
  5837. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  5838. node.expectedNode = expectedNode;
  5839. return isFinished ? node : this.finishNode(node, "Placeholder");
  5840. }
  5841. getTokenFromCode(code) {
  5842. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  5843. return this.finishOp(types.placeholder, 2);
  5844. }
  5845. return super.getTokenFromCode(...arguments);
  5846. }
  5847. parseExprAtom() {
  5848. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  5849. }
  5850. parseIdentifier() {
  5851. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  5852. }
  5853. checkReservedWord(word) {
  5854. if (word !== undefined) super.checkReservedWord(...arguments);
  5855. }
  5856. parseBindingAtom() {
  5857. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  5858. }
  5859. checkLVal(expr) {
  5860. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  5861. }
  5862. toAssignable(node) {
  5863. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  5864. node.expectedNode = "Pattern";
  5865. return node;
  5866. }
  5867. return super.toAssignable(...arguments);
  5868. }
  5869. verifyBreakContinue(node) {
  5870. if (node.label && node.label.type === "Placeholder") return;
  5871. super.verifyBreakContinue(...arguments);
  5872. }
  5873. parseExpressionStatement(node, expr) {
  5874. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  5875. return super.parseExpressionStatement(...arguments);
  5876. }
  5877. if (this.match(types.colon)) {
  5878. const stmt = node;
  5879. stmt.label = this.finishPlaceholder(expr, "Identifier");
  5880. this.next();
  5881. stmt.body = this.parseStatement("label");
  5882. return this.finishNode(stmt, "LabeledStatement");
  5883. }
  5884. this.semicolon();
  5885. node.name = expr.name;
  5886. return this.finishPlaceholder(node, "Statement");
  5887. }
  5888. parseBlock() {
  5889. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  5890. }
  5891. parseFunctionId() {
  5892. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  5893. }
  5894. parseClass(node, isStatement, optionalId) {
  5895. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  5896. this.next();
  5897. this.takeDecorators(node);
  5898. const placeholder = this.parsePlaceholder("Identifier");
  5899. if (placeholder) {
  5900. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  5901. node.id = placeholder;
  5902. } else if (optionalId || !isStatement) {
  5903. node.id = null;
  5904. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  5905. return this.finishNode(node, type);
  5906. } else {
  5907. this.unexpected(null, "A class name is required");
  5908. }
  5909. } else {
  5910. this.parseClassId(node, isStatement, optionalId);
  5911. }
  5912. this.parseClassSuper(node);
  5913. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass);
  5914. return this.finishNode(node, type);
  5915. }
  5916. parseExport(node) {
  5917. const placeholder = this.parsePlaceholder("Identifier");
  5918. if (!placeholder) return super.parseExport(...arguments);
  5919. if (!this.isContextual("from") && !this.match(types.comma)) {
  5920. node.specifiers = [];
  5921. node.source = null;
  5922. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  5923. return this.finishNode(node, "ExportNamedDeclaration");
  5924. }
  5925. this.expectPlugin("exportDefaultFrom");
  5926. const specifier = this.startNode();
  5927. specifier.exported = placeholder;
  5928. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  5929. return super.parseExport(node);
  5930. }
  5931. maybeParseExportDefaultSpecifier(node) {
  5932. if (node.specifiers && node.specifiers.length > 0) {
  5933. return true;
  5934. }
  5935. return super.maybeParseExportDefaultSpecifier(...arguments);
  5936. }
  5937. checkExport(node) {
  5938. const {
  5939. specifiers
  5940. } = node;
  5941. if (specifiers && specifiers.length) {
  5942. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  5943. }
  5944. super.checkExport(node);
  5945. node.specifiers = specifiers;
  5946. }
  5947. parseImport(node) {
  5948. const placeholder = this.parsePlaceholder("Identifier");
  5949. if (!placeholder) return super.parseImport(...arguments);
  5950. node.specifiers = [];
  5951. if (!this.isContextual("from") && !this.match(types.comma)) {
  5952. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  5953. this.semicolon();
  5954. return this.finishNode(node, "ImportDeclaration");
  5955. }
  5956. const specifier = this.startNodeAtNode(placeholder);
  5957. specifier.local = placeholder;
  5958. this.finishNode(specifier, "ImportDefaultSpecifier");
  5959. node.specifiers.push(specifier);
  5960. if (this.eat(types.comma)) {
  5961. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  5962. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  5963. }
  5964. this.expectContextual("from");
  5965. node.source = this.parseImportSource();
  5966. this.semicolon();
  5967. return this.finishNode(node, "ImportDeclaration");
  5968. }
  5969. parseImportSource() {
  5970. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  5971. }
  5972. });
  5973. var v8intrinsic = (superClass => class extends superClass {
  5974. parseV8Intrinsic() {
  5975. if (this.match(types.modulo)) {
  5976. const v8IntrinsicStart = this.state.start;
  5977. const node = this.startNode();
  5978. this.eat(types.modulo);
  5979. if (this.match(types.name)) {
  5980. const name = this.parseIdentifierName(this.state.start);
  5981. const identifier = this.createIdentifier(node, name);
  5982. identifier.type = "V8IntrinsicIdentifier";
  5983. if (this.match(types.parenL)) {
  5984. return identifier;
  5985. }
  5986. }
  5987. this.unexpected(v8IntrinsicStart);
  5988. }
  5989. }
  5990. parseExprAtom() {
  5991. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  5992. }
  5993. });
  5994. function hasPlugin(plugins, name) {
  5995. return plugins.some(plugin => {
  5996. if (Array.isArray(plugin)) {
  5997. return plugin[0] === name;
  5998. } else {
  5999. return plugin === name;
  6000. }
  6001. });
  6002. }
  6003. function getPluginOption(plugins, name, option) {
  6004. const plugin = plugins.find(plugin => {
  6005. if (Array.isArray(plugin)) {
  6006. return plugin[0] === name;
  6007. } else {
  6008. return plugin === name;
  6009. }
  6010. });
  6011. if (plugin && Array.isArray(plugin)) {
  6012. return plugin[1][option];
  6013. }
  6014. return null;
  6015. }
  6016. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6017. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6018. function validatePlugins(plugins) {
  6019. if (hasPlugin(plugins, "decorators")) {
  6020. if (hasPlugin(plugins, "decorators-legacy")) {
  6021. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6022. }
  6023. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6024. if (decoratorsBeforeExport == null) {
  6025. 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'.");
  6026. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6027. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6028. }
  6029. }
  6030. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6031. throw new Error("Cannot combine flow and typescript plugins.");
  6032. }
  6033. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6034. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6035. }
  6036. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6037. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6038. }
  6039. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6040. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6041. }
  6042. }
  6043. const mixinPlugins = {
  6044. estree,
  6045. jsx,
  6046. flow,
  6047. typescript,
  6048. v8intrinsic,
  6049. placeholders
  6050. };
  6051. const mixinPluginNames = Object.keys(mixinPlugins);
  6052. const defaultOptions = {
  6053. sourceType: "script",
  6054. sourceFilename: undefined,
  6055. startLine: 1,
  6056. allowAwaitOutsideFunction: false,
  6057. allowReturnOutsideFunction: false,
  6058. allowImportExportEverywhere: false,
  6059. allowSuperOutsideMethod: false,
  6060. allowUndeclaredExports: false,
  6061. plugins: [],
  6062. strictMode: null,
  6063. ranges: false,
  6064. tokens: false,
  6065. createParenthesizedExpressions: false,
  6066. errorRecovery: false
  6067. };
  6068. function getOptions(opts) {
  6069. const options = {};
  6070. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  6071. const key = _Object$keys[_i];
  6072. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6073. }
  6074. return options;
  6075. }
  6076. class State {
  6077. constructor() {
  6078. this.errors = [];
  6079. this.potentialArrowAt = -1;
  6080. this.noArrowAt = [];
  6081. this.noArrowParamsConversionAt = [];
  6082. this.inParameters = false;
  6083. this.maybeInArrowParameters = false;
  6084. this.maybeInAsyncArrowHead = false;
  6085. this.inPipeline = false;
  6086. this.inType = false;
  6087. this.noAnonFunctionType = false;
  6088. this.inPropertyName = false;
  6089. this.hasFlowComment = false;
  6090. this.isIterator = false;
  6091. this.topicContext = {
  6092. maxNumOfResolvableTopics: 0,
  6093. maxTopicIndex: null
  6094. };
  6095. this.soloAwait = false;
  6096. this.inFSharpPipelineDirectBody = false;
  6097. this.labels = [];
  6098. this.decoratorStack = [[]];
  6099. this.yieldPos = -1;
  6100. this.awaitPos = -1;
  6101. this.comments = [];
  6102. this.trailingComments = [];
  6103. this.leadingComments = [];
  6104. this.commentStack = [];
  6105. this.commentPreviousNode = null;
  6106. this.pos = 0;
  6107. this.lineStart = 0;
  6108. this.type = types.eof;
  6109. this.value = null;
  6110. this.start = 0;
  6111. this.end = 0;
  6112. this.lastTokEndLoc = null;
  6113. this.lastTokStartLoc = null;
  6114. this.lastTokStart = 0;
  6115. this.lastTokEnd = 0;
  6116. this.context = [types$1.braceStatement];
  6117. this.exprAllowed = true;
  6118. this.containsEsc = false;
  6119. this.octalPositions = [];
  6120. this.exportedIdentifiers = [];
  6121. this.tokensLength = 0;
  6122. }
  6123. init(options) {
  6124. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6125. this.curLine = options.startLine;
  6126. this.startLoc = this.endLoc = this.curPosition();
  6127. }
  6128. curPosition() {
  6129. return new Position(this.curLine, this.pos - this.lineStart);
  6130. }
  6131. clone(skipArrays) {
  6132. const state = new State();
  6133. const keys = Object.keys(this);
  6134. for (let i = 0, length = keys.length; i < length; i++) {
  6135. const key = keys[i];
  6136. let val = this[key];
  6137. if (!skipArrays && Array.isArray(val)) {
  6138. val = val.slice();
  6139. }
  6140. state[key] = val;
  6141. }
  6142. return state;
  6143. }
  6144. }
  6145. var _isDigit = function isDigit(code) {
  6146. return code >= 48 && code <= 57;
  6147. };
  6148. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6149. const forbiddenNumericSeparatorSiblings = {
  6150. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6151. hex: [46, 88, 95, 120]
  6152. };
  6153. const allowedNumericSeparatorSiblings = {};
  6154. allowedNumericSeparatorSiblings.bin = [48, 49];
  6155. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6156. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6157. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6158. class Token {
  6159. constructor(state) {
  6160. this.type = state.type;
  6161. this.value = state.value;
  6162. this.start = state.start;
  6163. this.end = state.end;
  6164. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  6165. }
  6166. }
  6167. class Tokenizer extends LocationParser {
  6168. constructor(options, input) {
  6169. super();
  6170. this.tokens = [];
  6171. this.state = new State();
  6172. this.state.init(options);
  6173. this.input = input;
  6174. this.length = input.length;
  6175. this.isLookahead = false;
  6176. }
  6177. pushToken(token) {
  6178. this.tokens.length = this.state.tokensLength;
  6179. this.tokens.push(token);
  6180. ++this.state.tokensLength;
  6181. }
  6182. next() {
  6183. if (!this.isLookahead) {
  6184. this.checkKeywordEscapes();
  6185. if (this.options.tokens) {
  6186. this.pushToken(new Token(this.state));
  6187. }
  6188. }
  6189. this.state.lastTokEnd = this.state.end;
  6190. this.state.lastTokStart = this.state.start;
  6191. this.state.lastTokEndLoc = this.state.endLoc;
  6192. this.state.lastTokStartLoc = this.state.startLoc;
  6193. this.nextToken();
  6194. }
  6195. eat(type) {
  6196. if (this.match(type)) {
  6197. this.next();
  6198. return true;
  6199. } else {
  6200. return false;
  6201. }
  6202. }
  6203. match(type) {
  6204. return this.state.type === type;
  6205. }
  6206. lookahead() {
  6207. const old = this.state;
  6208. this.state = old.clone(true);
  6209. this.isLookahead = true;
  6210. this.next();
  6211. this.isLookahead = false;
  6212. const curr = this.state;
  6213. this.state = old;
  6214. return curr;
  6215. }
  6216. nextTokenStart() {
  6217. const thisTokEnd = this.state.pos;
  6218. skipWhiteSpace.lastIndex = thisTokEnd;
  6219. const skip = skipWhiteSpace.exec(this.input);
  6220. return thisTokEnd + skip[0].length;
  6221. }
  6222. lookaheadCharCode() {
  6223. return this.input.charCodeAt(this.nextTokenStart());
  6224. }
  6225. setStrict(strict) {
  6226. this.state.strict = strict;
  6227. if (!this.match(types.num) && !this.match(types.string)) return;
  6228. this.state.pos = this.state.start;
  6229. while (this.state.pos < this.state.lineStart) {
  6230. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  6231. --this.state.curLine;
  6232. }
  6233. this.nextToken();
  6234. }
  6235. curContext() {
  6236. return this.state.context[this.state.context.length - 1];
  6237. }
  6238. nextToken() {
  6239. const curContext = this.curContext();
  6240. if (!curContext || !curContext.preserveSpace) this.skipSpace();
  6241. this.state.octalPositions = [];
  6242. this.state.start = this.state.pos;
  6243. this.state.startLoc = this.state.curPosition();
  6244. if (this.state.pos >= this.length) {
  6245. this.finishToken(types.eof);
  6246. return;
  6247. }
  6248. const override = curContext == null ? void 0 : curContext.override;
  6249. if (override) {
  6250. override(this);
  6251. } else {
  6252. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6253. }
  6254. }
  6255. pushComment(block, text, start, end, startLoc, endLoc) {
  6256. const comment = {
  6257. type: block ? "CommentBlock" : "CommentLine",
  6258. value: text,
  6259. start: start,
  6260. end: end,
  6261. loc: new SourceLocation(startLoc, endLoc)
  6262. };
  6263. if (this.options.tokens) this.pushToken(comment);
  6264. this.state.comments.push(comment);
  6265. this.addComment(comment);
  6266. }
  6267. skipBlockComment() {
  6268. const startLoc = this.state.curPosition();
  6269. const start = this.state.pos;
  6270. const end = this.input.indexOf("*/", this.state.pos + 2);
  6271. if (end === -1) throw this.raise(start, Errors.UnterminatedComment);
  6272. this.state.pos = end + 2;
  6273. lineBreakG.lastIndex = start;
  6274. let match;
  6275. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6276. ++this.state.curLine;
  6277. this.state.lineStart = match.index + match[0].length;
  6278. }
  6279. if (this.isLookahead) return;
  6280. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6281. }
  6282. skipLineComment(startSkip) {
  6283. const start = this.state.pos;
  6284. const startLoc = this.state.curPosition();
  6285. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6286. if (this.state.pos < this.length) {
  6287. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6288. ch = this.input.charCodeAt(this.state.pos);
  6289. }
  6290. }
  6291. if (this.isLookahead) return;
  6292. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6293. }
  6294. skipSpace() {
  6295. loop: while (this.state.pos < this.length) {
  6296. const ch = this.input.charCodeAt(this.state.pos);
  6297. switch (ch) {
  6298. case 32:
  6299. case 160:
  6300. case 9:
  6301. ++this.state.pos;
  6302. break;
  6303. case 13:
  6304. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6305. ++this.state.pos;
  6306. }
  6307. case 10:
  6308. case 8232:
  6309. case 8233:
  6310. ++this.state.pos;
  6311. ++this.state.curLine;
  6312. this.state.lineStart = this.state.pos;
  6313. break;
  6314. case 47:
  6315. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6316. case 42:
  6317. this.skipBlockComment();
  6318. break;
  6319. case 47:
  6320. this.skipLineComment(2);
  6321. break;
  6322. default:
  6323. break loop;
  6324. }
  6325. break;
  6326. default:
  6327. if (isWhitespace(ch)) {
  6328. ++this.state.pos;
  6329. } else {
  6330. break loop;
  6331. }
  6332. }
  6333. }
  6334. }
  6335. finishToken(type, val) {
  6336. this.state.end = this.state.pos;
  6337. this.state.endLoc = this.state.curPosition();
  6338. const prevType = this.state.type;
  6339. this.state.type = type;
  6340. this.state.value = val;
  6341. if (!this.isLookahead) this.updateContext(prevType);
  6342. }
  6343. readToken_numberSign() {
  6344. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6345. return;
  6346. }
  6347. const nextPos = this.state.pos + 1;
  6348. const next = this.input.charCodeAt(nextPos);
  6349. if (next >= 48 && next <= 57) {
  6350. throw this.raise(this.state.pos, Errors.UnexpectedDigitAfterHash);
  6351. }
  6352. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  6353. this.expectPlugin("recordAndTuple");
  6354. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6355. throw this.raise(this.state.pos, next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType);
  6356. }
  6357. if (next === 123) {
  6358. this.finishToken(types.braceHashL);
  6359. } else {
  6360. this.finishToken(types.bracketHashL);
  6361. }
  6362. this.state.pos += 2;
  6363. } else {
  6364. this.finishOp(types.hash, 1);
  6365. }
  6366. }
  6367. readToken_dot() {
  6368. const next = this.input.charCodeAt(this.state.pos + 1);
  6369. if (next >= 48 && next <= 57) {
  6370. this.readNumber(true);
  6371. return;
  6372. }
  6373. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6374. this.state.pos += 3;
  6375. this.finishToken(types.ellipsis);
  6376. } else {
  6377. ++this.state.pos;
  6378. this.finishToken(types.dot);
  6379. }
  6380. }
  6381. readToken_slash() {
  6382. if (this.state.exprAllowed && !this.state.inType) {
  6383. ++this.state.pos;
  6384. this.readRegexp();
  6385. return;
  6386. }
  6387. const next = this.input.charCodeAt(this.state.pos + 1);
  6388. if (next === 61) {
  6389. this.finishOp(types.assign, 2);
  6390. } else {
  6391. this.finishOp(types.slash, 1);
  6392. }
  6393. }
  6394. readToken_interpreter() {
  6395. if (this.state.pos !== 0 || this.length < 2) return false;
  6396. let ch = this.input.charCodeAt(this.state.pos + 1);
  6397. if (ch !== 33) return false;
  6398. const start = this.state.pos;
  6399. this.state.pos += 1;
  6400. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6401. ch = this.input.charCodeAt(this.state.pos);
  6402. }
  6403. const value = this.input.slice(start + 2, this.state.pos);
  6404. this.finishToken(types.interpreterDirective, value);
  6405. return true;
  6406. }
  6407. readToken_mult_modulo(code) {
  6408. let type = code === 42 ? types.star : types.modulo;
  6409. let width = 1;
  6410. let next = this.input.charCodeAt(this.state.pos + 1);
  6411. const exprAllowed = this.state.exprAllowed;
  6412. if (code === 42 && next === 42) {
  6413. width++;
  6414. next = this.input.charCodeAt(this.state.pos + 2);
  6415. type = types.exponent;
  6416. }
  6417. if (next === 61 && !exprAllowed) {
  6418. width++;
  6419. type = types.assign;
  6420. }
  6421. this.finishOp(type, width);
  6422. }
  6423. readToken_pipe_amp(code) {
  6424. const next = this.input.charCodeAt(this.state.pos + 1);
  6425. if (next === code) {
  6426. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6427. this.finishOp(types.assign, 3);
  6428. } else {
  6429. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6430. }
  6431. return;
  6432. }
  6433. if (code === 124) {
  6434. if (next === 62) {
  6435. this.finishOp(types.pipeline, 2);
  6436. return;
  6437. }
  6438. if (this.hasPlugin("recordAndTuple") && next === 125) {
  6439. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6440. throw this.raise(this.state.pos, Errors.RecordExpressionBarIncorrectEndSyntaxType);
  6441. }
  6442. this.finishOp(types.braceBarR, 2);
  6443. return;
  6444. }
  6445. if (this.hasPlugin("recordAndTuple") && next === 93) {
  6446. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6447. throw this.raise(this.state.pos, Errors.TupleExpressionBarIncorrectEndSyntaxType);
  6448. }
  6449. this.finishOp(types.bracketBarR, 2);
  6450. return;
  6451. }
  6452. }
  6453. if (next === 61) {
  6454. this.finishOp(types.assign, 2);
  6455. return;
  6456. }
  6457. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6458. }
  6459. readToken_caret() {
  6460. const next = this.input.charCodeAt(this.state.pos + 1);
  6461. if (next === 61) {
  6462. this.finishOp(types.assign, 2);
  6463. } else {
  6464. this.finishOp(types.bitwiseXOR, 1);
  6465. }
  6466. }
  6467. readToken_plus_min(code) {
  6468. const next = this.input.charCodeAt(this.state.pos + 1);
  6469. if (next === code) {
  6470. 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)))) {
  6471. this.skipLineComment(3);
  6472. this.skipSpace();
  6473. this.nextToken();
  6474. return;
  6475. }
  6476. this.finishOp(types.incDec, 2);
  6477. return;
  6478. }
  6479. if (next === 61) {
  6480. this.finishOp(types.assign, 2);
  6481. } else {
  6482. this.finishOp(types.plusMin, 1);
  6483. }
  6484. }
  6485. readToken_lt_gt(code) {
  6486. const next = this.input.charCodeAt(this.state.pos + 1);
  6487. let size = 1;
  6488. if (next === code) {
  6489. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6490. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6491. this.finishOp(types.assign, size + 1);
  6492. return;
  6493. }
  6494. this.finishOp(types.bitShift, size);
  6495. return;
  6496. }
  6497. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6498. this.skipLineComment(4);
  6499. this.skipSpace();
  6500. this.nextToken();
  6501. return;
  6502. }
  6503. if (next === 61) {
  6504. size = 2;
  6505. }
  6506. this.finishOp(types.relational, size);
  6507. }
  6508. readToken_eq_excl(code) {
  6509. const next = this.input.charCodeAt(this.state.pos + 1);
  6510. if (next === 61) {
  6511. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6512. return;
  6513. }
  6514. if (code === 61 && next === 62) {
  6515. this.state.pos += 2;
  6516. this.finishToken(types.arrow);
  6517. return;
  6518. }
  6519. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6520. }
  6521. readToken_question() {
  6522. const next = this.input.charCodeAt(this.state.pos + 1);
  6523. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6524. if (next === 63 && !this.state.inType) {
  6525. if (next2 === 61) {
  6526. this.finishOp(types.assign, 3);
  6527. } else {
  6528. this.finishOp(types.nullishCoalescing, 2);
  6529. }
  6530. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6531. this.state.pos += 2;
  6532. this.finishToken(types.questionDot);
  6533. } else {
  6534. ++this.state.pos;
  6535. this.finishToken(types.question);
  6536. }
  6537. }
  6538. getTokenFromCode(code) {
  6539. switch (code) {
  6540. case 46:
  6541. this.readToken_dot();
  6542. return;
  6543. case 40:
  6544. ++this.state.pos;
  6545. this.finishToken(types.parenL);
  6546. return;
  6547. case 41:
  6548. ++this.state.pos;
  6549. this.finishToken(types.parenR);
  6550. return;
  6551. case 59:
  6552. ++this.state.pos;
  6553. this.finishToken(types.semi);
  6554. return;
  6555. case 44:
  6556. ++this.state.pos;
  6557. this.finishToken(types.comma);
  6558. return;
  6559. case 91:
  6560. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6561. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6562. throw this.raise(this.state.pos, Errors.TupleExpressionBarIncorrectStartSyntaxType);
  6563. }
  6564. this.finishToken(types.bracketBarL);
  6565. this.state.pos += 2;
  6566. } else {
  6567. ++this.state.pos;
  6568. this.finishToken(types.bracketL);
  6569. }
  6570. return;
  6571. case 93:
  6572. ++this.state.pos;
  6573. this.finishToken(types.bracketR);
  6574. return;
  6575. case 123:
  6576. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6577. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6578. throw this.raise(this.state.pos, Errors.RecordExpressionBarIncorrectStartSyntaxType);
  6579. }
  6580. this.finishToken(types.braceBarL);
  6581. this.state.pos += 2;
  6582. } else {
  6583. ++this.state.pos;
  6584. this.finishToken(types.braceL);
  6585. }
  6586. return;
  6587. case 125:
  6588. ++this.state.pos;
  6589. this.finishToken(types.braceR);
  6590. return;
  6591. case 58:
  6592. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6593. this.finishOp(types.doubleColon, 2);
  6594. } else {
  6595. ++this.state.pos;
  6596. this.finishToken(types.colon);
  6597. }
  6598. return;
  6599. case 63:
  6600. this.readToken_question();
  6601. return;
  6602. case 96:
  6603. ++this.state.pos;
  6604. this.finishToken(types.backQuote);
  6605. return;
  6606. case 48:
  6607. {
  6608. const next = this.input.charCodeAt(this.state.pos + 1);
  6609. if (next === 120 || next === 88) {
  6610. this.readRadixNumber(16);
  6611. return;
  6612. }
  6613. if (next === 111 || next === 79) {
  6614. this.readRadixNumber(8);
  6615. return;
  6616. }
  6617. if (next === 98 || next === 66) {
  6618. this.readRadixNumber(2);
  6619. return;
  6620. }
  6621. }
  6622. case 49:
  6623. case 50:
  6624. case 51:
  6625. case 52:
  6626. case 53:
  6627. case 54:
  6628. case 55:
  6629. case 56:
  6630. case 57:
  6631. this.readNumber(false);
  6632. return;
  6633. case 34:
  6634. case 39:
  6635. this.readString(code);
  6636. return;
  6637. case 47:
  6638. this.readToken_slash();
  6639. return;
  6640. case 37:
  6641. case 42:
  6642. this.readToken_mult_modulo(code);
  6643. return;
  6644. case 124:
  6645. case 38:
  6646. this.readToken_pipe_amp(code);
  6647. return;
  6648. case 94:
  6649. this.readToken_caret();
  6650. return;
  6651. case 43:
  6652. case 45:
  6653. this.readToken_plus_min(code);
  6654. return;
  6655. case 60:
  6656. case 62:
  6657. this.readToken_lt_gt(code);
  6658. return;
  6659. case 61:
  6660. case 33:
  6661. this.readToken_eq_excl(code);
  6662. return;
  6663. case 126:
  6664. this.finishOp(types.tilde, 1);
  6665. return;
  6666. case 64:
  6667. ++this.state.pos;
  6668. this.finishToken(types.at);
  6669. return;
  6670. case 35:
  6671. this.readToken_numberSign();
  6672. return;
  6673. case 92:
  6674. this.readWord();
  6675. return;
  6676. default:
  6677. if (isIdentifierStart(code)) {
  6678. this.readWord();
  6679. return;
  6680. }
  6681. }
  6682. throw this.raise(this.state.pos, Errors.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  6683. }
  6684. finishOp(type, size) {
  6685. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6686. this.state.pos += size;
  6687. this.finishToken(type, str);
  6688. }
  6689. readRegexp() {
  6690. const start = this.state.pos;
  6691. let escaped, inClass;
  6692. for (;;) {
  6693. if (this.state.pos >= this.length) {
  6694. throw this.raise(start, Errors.UnterminatedRegExp);
  6695. }
  6696. const ch = this.input.charAt(this.state.pos);
  6697. if (lineBreak.test(ch)) {
  6698. throw this.raise(start, Errors.UnterminatedRegExp);
  6699. }
  6700. if (escaped) {
  6701. escaped = false;
  6702. } else {
  6703. if (ch === "[") {
  6704. inClass = true;
  6705. } else if (ch === "]" && inClass) {
  6706. inClass = false;
  6707. } else if (ch === "/" && !inClass) {
  6708. break;
  6709. }
  6710. escaped = ch === "\\";
  6711. }
  6712. ++this.state.pos;
  6713. }
  6714. const content = this.input.slice(start, this.state.pos);
  6715. ++this.state.pos;
  6716. let mods = "";
  6717. while (this.state.pos < this.length) {
  6718. const char = this.input[this.state.pos];
  6719. const charCode = this.input.codePointAt(this.state.pos);
  6720. if (VALID_REGEX_FLAGS.has(char)) {
  6721. if (mods.indexOf(char) > -1) {
  6722. this.raise(this.state.pos + 1, Errors.DuplicateRegExpFlags);
  6723. }
  6724. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6725. this.raise(this.state.pos + 1, Errors.MalformedRegExpFlags);
  6726. } else {
  6727. break;
  6728. }
  6729. ++this.state.pos;
  6730. mods += char;
  6731. }
  6732. this.finishToken(types.regexp, {
  6733. pattern: content,
  6734. flags: mods
  6735. });
  6736. }
  6737. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6738. const start = this.state.pos;
  6739. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6740. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6741. let invalid = false;
  6742. let total = 0;
  6743. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  6744. const code = this.input.charCodeAt(this.state.pos);
  6745. let val;
  6746. if (this.hasPlugin("numericSeparator")) {
  6747. if (code === 95) {
  6748. const prev = this.input.charCodeAt(this.state.pos - 1);
  6749. const next = this.input.charCodeAt(this.state.pos + 1);
  6750. if (allowedSiblings.indexOf(next) === -1) {
  6751. this.raise(this.state.pos, Errors.UnexpectedNumericSeparator);
  6752. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  6753. this.raise(this.state.pos, Errors.UnexpectedNumericSeparator);
  6754. }
  6755. if (!allowNumSeparator) {
  6756. this.raise(this.state.pos, Errors.NumericSeparatorInEscapeSequence);
  6757. }
  6758. ++this.state.pos;
  6759. continue;
  6760. }
  6761. }
  6762. if (code >= 97) {
  6763. val = code - 97 + 10;
  6764. } else if (code >= 65) {
  6765. val = code - 65 + 10;
  6766. } else if (_isDigit(code)) {
  6767. val = code - 48;
  6768. } else {
  6769. val = Infinity;
  6770. }
  6771. if (val >= radix) {
  6772. if (this.options.errorRecovery && val <= 9) {
  6773. val = 0;
  6774. this.raise(this.state.start + i + 2, Errors.InvalidDigit, radix);
  6775. } else if (forceLen) {
  6776. val = 0;
  6777. invalid = true;
  6778. } else {
  6779. break;
  6780. }
  6781. }
  6782. ++this.state.pos;
  6783. total = total * radix + val;
  6784. }
  6785. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  6786. return null;
  6787. }
  6788. return total;
  6789. }
  6790. readRadixNumber(radix) {
  6791. const start = this.state.pos;
  6792. let isBigInt = false;
  6793. this.state.pos += 2;
  6794. const val = this.readInt(radix);
  6795. if (val == null) {
  6796. this.raise(this.state.start + 2, Errors.InvalidDigit, radix);
  6797. }
  6798. const next = this.input.charCodeAt(this.state.pos);
  6799. if (next === 95) {
  6800. this.expectPlugin("numericSeparator", this.state.pos);
  6801. }
  6802. if (next === 110) {
  6803. ++this.state.pos;
  6804. isBigInt = true;
  6805. }
  6806. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6807. throw this.raise(this.state.pos, Errors.NumberIdentifier);
  6808. }
  6809. if (isBigInt) {
  6810. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6811. this.finishToken(types.bigint, str);
  6812. return;
  6813. }
  6814. this.finishToken(types.num, val);
  6815. }
  6816. readNumber(startsWithDot) {
  6817. const start = this.state.pos;
  6818. let isFloat = false;
  6819. let isBigInt = false;
  6820. let isNonOctalDecimalInt = false;
  6821. if (!startsWithDot && this.readInt(10) === null) {
  6822. this.raise(start, Errors.InvalidNumber);
  6823. }
  6824. let octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  6825. if (octal) {
  6826. if (this.state.strict) {
  6827. this.raise(start, Errors.StrictOctalLiteral);
  6828. }
  6829. if (/[89]/.test(this.input.slice(start, this.state.pos))) {
  6830. octal = false;
  6831. isNonOctalDecimalInt = true;
  6832. }
  6833. }
  6834. let next = this.input.charCodeAt(this.state.pos);
  6835. if (next === 46 && !octal) {
  6836. ++this.state.pos;
  6837. this.readInt(10);
  6838. isFloat = true;
  6839. next = this.input.charCodeAt(this.state.pos);
  6840. }
  6841. if ((next === 69 || next === 101) && !octal) {
  6842. next = this.input.charCodeAt(++this.state.pos);
  6843. if (next === 43 || next === 45) {
  6844. ++this.state.pos;
  6845. }
  6846. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  6847. isFloat = true;
  6848. next = this.input.charCodeAt(this.state.pos);
  6849. }
  6850. if (this.hasPlugin("numericSeparator") && (octal || isNonOctalDecimalInt)) {
  6851. const underscorePos = this.input.slice(start, this.state.pos).indexOf("_");
  6852. if (underscorePos > 0) {
  6853. this.raise(underscorePos + start, Errors.ZeroDigitNumericSeparator);
  6854. }
  6855. }
  6856. if (next === 95) {
  6857. this.expectPlugin("numericSeparator", this.state.pos);
  6858. }
  6859. if (next === 110) {
  6860. if (isFloat || octal || isNonOctalDecimalInt) {
  6861. this.raise(start, "Invalid BigIntLiteral");
  6862. }
  6863. ++this.state.pos;
  6864. isBigInt = true;
  6865. }
  6866. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6867. throw this.raise(this.state.pos, Errors.NumberIdentifier);
  6868. }
  6869. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6870. if (isBigInt) {
  6871. this.finishToken(types.bigint, str);
  6872. return;
  6873. }
  6874. const val = octal ? parseInt(str, 8) : parseFloat(str);
  6875. this.finishToken(types.num, val);
  6876. }
  6877. readCodePoint(throwOnInvalid) {
  6878. const ch = this.input.charCodeAt(this.state.pos);
  6879. let code;
  6880. if (ch === 123) {
  6881. const codePos = ++this.state.pos;
  6882. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  6883. ++this.state.pos;
  6884. if (code !== null && code > 0x10ffff) {
  6885. if (throwOnInvalid) {
  6886. this.raise(codePos, Errors.InvalidCodePoint);
  6887. } else {
  6888. return null;
  6889. }
  6890. }
  6891. } else {
  6892. code = this.readHexChar(4, false, throwOnInvalid);
  6893. }
  6894. return code;
  6895. }
  6896. readString(quote) {
  6897. let out = "",
  6898. chunkStart = ++this.state.pos;
  6899. for (;;) {
  6900. if (this.state.pos >= this.length) {
  6901. throw this.raise(this.state.start, Errors.UnterminatedString);
  6902. }
  6903. const ch = this.input.charCodeAt(this.state.pos);
  6904. if (ch === quote) break;
  6905. if (ch === 92) {
  6906. out += this.input.slice(chunkStart, this.state.pos);
  6907. out += this.readEscapedChar(false);
  6908. chunkStart = this.state.pos;
  6909. } else if (ch === 8232 || ch === 8233) {
  6910. ++this.state.pos;
  6911. ++this.state.curLine;
  6912. this.state.lineStart = this.state.pos;
  6913. } else if (isNewLine(ch)) {
  6914. throw this.raise(this.state.start, Errors.UnterminatedString);
  6915. } else {
  6916. ++this.state.pos;
  6917. }
  6918. }
  6919. out += this.input.slice(chunkStart, this.state.pos++);
  6920. this.finishToken(types.string, out);
  6921. }
  6922. readTmplToken() {
  6923. let out = "",
  6924. chunkStart = this.state.pos,
  6925. containsInvalid = false;
  6926. for (;;) {
  6927. if (this.state.pos >= this.length) {
  6928. throw this.raise(this.state.start, Errors.UnterminatedTemplate);
  6929. }
  6930. const ch = this.input.charCodeAt(this.state.pos);
  6931. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  6932. if (this.state.pos === this.state.start && this.match(types.template)) {
  6933. if (ch === 36) {
  6934. this.state.pos += 2;
  6935. this.finishToken(types.dollarBraceL);
  6936. return;
  6937. } else {
  6938. ++this.state.pos;
  6939. this.finishToken(types.backQuote);
  6940. return;
  6941. }
  6942. }
  6943. out += this.input.slice(chunkStart, this.state.pos);
  6944. this.finishToken(types.template, containsInvalid ? null : out);
  6945. return;
  6946. }
  6947. if (ch === 92) {
  6948. out += this.input.slice(chunkStart, this.state.pos);
  6949. const escaped = this.readEscapedChar(true);
  6950. if (escaped === null) {
  6951. containsInvalid = true;
  6952. } else {
  6953. out += escaped;
  6954. }
  6955. chunkStart = this.state.pos;
  6956. } else if (isNewLine(ch)) {
  6957. out += this.input.slice(chunkStart, this.state.pos);
  6958. ++this.state.pos;
  6959. switch (ch) {
  6960. case 13:
  6961. if (this.input.charCodeAt(this.state.pos) === 10) {
  6962. ++this.state.pos;
  6963. }
  6964. case 10:
  6965. out += "\n";
  6966. break;
  6967. default:
  6968. out += String.fromCharCode(ch);
  6969. break;
  6970. }
  6971. ++this.state.curLine;
  6972. this.state.lineStart = this.state.pos;
  6973. chunkStart = this.state.pos;
  6974. } else {
  6975. ++this.state.pos;
  6976. }
  6977. }
  6978. }
  6979. readEscapedChar(inTemplate) {
  6980. const throwOnInvalid = !inTemplate;
  6981. const ch = this.input.charCodeAt(++this.state.pos);
  6982. ++this.state.pos;
  6983. switch (ch) {
  6984. case 110:
  6985. return "\n";
  6986. case 114:
  6987. return "\r";
  6988. case 120:
  6989. {
  6990. const code = this.readHexChar(2, false, throwOnInvalid);
  6991. return code === null ? null : String.fromCharCode(code);
  6992. }
  6993. case 117:
  6994. {
  6995. const code = this.readCodePoint(throwOnInvalid);
  6996. return code === null ? null : String.fromCodePoint(code);
  6997. }
  6998. case 116:
  6999. return "\t";
  7000. case 98:
  7001. return "\b";
  7002. case 118:
  7003. return "\u000b";
  7004. case 102:
  7005. return "\f";
  7006. case 13:
  7007. if (this.input.charCodeAt(this.state.pos) === 10) {
  7008. ++this.state.pos;
  7009. }
  7010. case 10:
  7011. this.state.lineStart = this.state.pos;
  7012. ++this.state.curLine;
  7013. case 8232:
  7014. case 8233:
  7015. return "";
  7016. case 56:
  7017. case 57:
  7018. if (inTemplate) {
  7019. return null;
  7020. }
  7021. default:
  7022. if (ch >= 48 && ch <= 55) {
  7023. const codePos = this.state.pos - 1;
  7024. let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
  7025. let octal = parseInt(octalStr, 8);
  7026. if (octal > 255) {
  7027. octalStr = octalStr.slice(0, -1);
  7028. octal = parseInt(octalStr, 8);
  7029. }
  7030. this.state.pos += octalStr.length - 1;
  7031. const next = this.input.charCodeAt(this.state.pos);
  7032. if (octalStr !== "0" || next === 56 || next === 57) {
  7033. if (inTemplate) {
  7034. return null;
  7035. } else if (this.state.strict) {
  7036. this.raise(codePos, Errors.StrictOctalLiteral);
  7037. } else {
  7038. this.state.octalPositions.push(codePos);
  7039. }
  7040. }
  7041. return String.fromCharCode(octal);
  7042. }
  7043. return String.fromCharCode(ch);
  7044. }
  7045. }
  7046. readHexChar(len, forceLen, throwOnInvalid) {
  7047. const codePos = this.state.pos;
  7048. const n = this.readInt(16, len, forceLen, false);
  7049. if (n === null) {
  7050. if (throwOnInvalid) {
  7051. this.raise(codePos, Errors.InvalidEscapeSequence);
  7052. } else {
  7053. this.state.pos = codePos - 1;
  7054. }
  7055. }
  7056. return n;
  7057. }
  7058. readWord1() {
  7059. let word = "";
  7060. this.state.containsEsc = false;
  7061. const start = this.state.pos;
  7062. let chunkStart = this.state.pos;
  7063. while (this.state.pos < this.length) {
  7064. const ch = this.input.codePointAt(this.state.pos);
  7065. if (isIdentifierChar(ch)) {
  7066. this.state.pos += ch <= 0xffff ? 1 : 2;
  7067. } else if (this.state.isIterator && ch === 64) {
  7068. ++this.state.pos;
  7069. } else if (ch === 92) {
  7070. this.state.containsEsc = true;
  7071. word += this.input.slice(chunkStart, this.state.pos);
  7072. const escStart = this.state.pos;
  7073. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  7074. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  7075. this.raise(this.state.pos, Errors.MissingUnicodeEscape);
  7076. continue;
  7077. }
  7078. ++this.state.pos;
  7079. const esc = this.readCodePoint(true);
  7080. if (esc !== null) {
  7081. if (!identifierCheck(esc)) {
  7082. this.raise(escStart, Errors.EscapedCharNotAnIdentifier);
  7083. }
  7084. word += String.fromCodePoint(esc);
  7085. }
  7086. chunkStart = this.state.pos;
  7087. } else {
  7088. break;
  7089. }
  7090. }
  7091. return word + this.input.slice(chunkStart, this.state.pos);
  7092. }
  7093. isIterator(word) {
  7094. return word === "@@iterator" || word === "@@asyncIterator";
  7095. }
  7096. readWord() {
  7097. const word = this.readWord1();
  7098. const type = keywords.get(word) || types.name;
  7099. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  7100. this.raise(this.state.pos, Errors.InvalidIdentifier, word);
  7101. }
  7102. this.finishToken(type, word);
  7103. }
  7104. checkKeywordEscapes() {
  7105. const kw = this.state.type.keyword;
  7106. if (kw && this.state.containsEsc) {
  7107. this.raise(this.state.start, Errors.InvalidEscapedReservedWord, kw);
  7108. }
  7109. }
  7110. braceIsBlock(prevType) {
  7111. const parent = this.curContext();
  7112. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  7113. return true;
  7114. }
  7115. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  7116. return !parent.isExpr;
  7117. }
  7118. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  7119. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7120. }
  7121. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  7122. return true;
  7123. }
  7124. if (prevType === types.braceL) {
  7125. return parent === types$1.braceStatement;
  7126. }
  7127. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  7128. return false;
  7129. }
  7130. if (prevType === types.relational) {
  7131. return true;
  7132. }
  7133. return !this.state.exprAllowed;
  7134. }
  7135. updateContext(prevType) {
  7136. const type = this.state.type;
  7137. let update;
  7138. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  7139. this.state.exprAllowed = false;
  7140. } else if (update = type.updateContext) {
  7141. update.call(this, prevType);
  7142. } else {
  7143. this.state.exprAllowed = type.beforeExpr;
  7144. }
  7145. }
  7146. }
  7147. class UtilParser extends Tokenizer {
  7148. addExtra(node, key, val) {
  7149. if (!node) return;
  7150. const extra = node.extra = node.extra || {};
  7151. extra[key] = val;
  7152. }
  7153. isRelational(op) {
  7154. return this.match(types.relational) && this.state.value === op;
  7155. }
  7156. isLookaheadRelational(op) {
  7157. const next = this.nextTokenStart();
  7158. if (this.input.charAt(next) === op) {
  7159. if (next + 1 === this.input.length) {
  7160. return true;
  7161. }
  7162. const afterNext = this.input.charCodeAt(next + 1);
  7163. return afterNext !== op.charCodeAt(0) && afterNext !== 61;
  7164. }
  7165. return false;
  7166. }
  7167. expectRelational(op) {
  7168. if (this.isRelational(op)) {
  7169. this.next();
  7170. } else {
  7171. this.unexpected(null, types.relational);
  7172. }
  7173. }
  7174. isContextual(name) {
  7175. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  7176. }
  7177. isUnparsedContextual(nameStart, name) {
  7178. const nameEnd = nameStart + name.length;
  7179. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  7180. }
  7181. isLookaheadContextual(name) {
  7182. const next = this.nextTokenStart();
  7183. return this.isUnparsedContextual(next, name);
  7184. }
  7185. eatContextual(name) {
  7186. return this.isContextual(name) && this.eat(types.name);
  7187. }
  7188. expectContextual(name, message) {
  7189. if (!this.eatContextual(name)) this.unexpected(null, message);
  7190. }
  7191. canInsertSemicolon() {
  7192. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  7193. }
  7194. hasPrecedingLineBreak() {
  7195. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7196. }
  7197. isLineTerminator() {
  7198. return this.eat(types.semi) || this.canInsertSemicolon();
  7199. }
  7200. semicolon() {
  7201. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  7202. }
  7203. expect(type, pos) {
  7204. this.eat(type) || this.unexpected(pos, type);
  7205. }
  7206. assertNoSpace(message = "Unexpected space.") {
  7207. if (this.state.start > this.state.lastTokEnd) {
  7208. this.raise(this.state.lastTokEnd, message);
  7209. }
  7210. }
  7211. unexpected(pos, messageOrType = "Unexpected token") {
  7212. if (typeof messageOrType !== "string") {
  7213. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  7214. }
  7215. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  7216. }
  7217. expectPlugin(name, pos) {
  7218. if (!this.hasPlugin(name)) {
  7219. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7220. missingPlugin: [name]
  7221. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  7222. }
  7223. return true;
  7224. }
  7225. expectOnePlugin(names, pos) {
  7226. if (!names.some(n => this.hasPlugin(n))) {
  7227. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7228. missingPlugin: names
  7229. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  7230. }
  7231. }
  7232. checkYieldAwaitInDefaultParams() {
  7233. if (this.state.yieldPos !== -1 && (this.state.awaitPos === -1 || this.state.yieldPos < this.state.awaitPos)) {
  7234. this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function");
  7235. }
  7236. if (this.state.awaitPos !== -1) {
  7237. this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function");
  7238. }
  7239. }
  7240. tryParse(fn, oldState = this.state.clone()) {
  7241. const abortSignal = {
  7242. node: null
  7243. };
  7244. try {
  7245. const node = fn((node = null) => {
  7246. abortSignal.node = node;
  7247. throw abortSignal;
  7248. });
  7249. if (this.state.errors.length > oldState.errors.length) {
  7250. const failState = this.state;
  7251. this.state = oldState;
  7252. return {
  7253. node,
  7254. error: failState.errors[oldState.errors.length],
  7255. thrown: false,
  7256. aborted: false,
  7257. failState
  7258. };
  7259. }
  7260. return {
  7261. node,
  7262. error: null,
  7263. thrown: false,
  7264. aborted: false,
  7265. failState: null
  7266. };
  7267. } catch (error) {
  7268. const failState = this.state;
  7269. this.state = oldState;
  7270. if (error instanceof SyntaxError) {
  7271. return {
  7272. node: null,
  7273. error,
  7274. thrown: true,
  7275. aborted: false,
  7276. failState
  7277. };
  7278. }
  7279. if (error === abortSignal) {
  7280. return {
  7281. node: abortSignal.node,
  7282. error: null,
  7283. thrown: false,
  7284. aborted: true,
  7285. failState
  7286. };
  7287. }
  7288. throw error;
  7289. }
  7290. }
  7291. checkExpressionErrors(refExpressionErrors, andThrow) {
  7292. if (!refExpressionErrors) return false;
  7293. const {
  7294. shorthandAssign,
  7295. doubleProto
  7296. } = refExpressionErrors;
  7297. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  7298. if (shorthandAssign >= 0) {
  7299. this.unexpected(shorthandAssign);
  7300. }
  7301. if (doubleProto >= 0) {
  7302. this.raise(doubleProto, Errors.DuplicateProto);
  7303. }
  7304. }
  7305. }
  7306. class ExpressionErrors {
  7307. constructor() {
  7308. this.shorthandAssign = -1;
  7309. this.doubleProto = -1;
  7310. }
  7311. }
  7312. class Node {
  7313. constructor(parser, pos, loc) {
  7314. this.type = "";
  7315. this.start = pos;
  7316. this.end = 0;
  7317. this.loc = new SourceLocation(loc);
  7318. if (parser && parser.options.ranges) this.range = [pos, 0];
  7319. if (parser && parser.filename) this.loc.filename = parser.filename;
  7320. }
  7321. __clone() {
  7322. const newNode = new Node();
  7323. const keys = Object.keys(this);
  7324. for (let i = 0, length = keys.length; i < length; i++) {
  7325. const key = keys[i];
  7326. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  7327. newNode[key] = this[key];
  7328. }
  7329. }
  7330. return newNode;
  7331. }
  7332. }
  7333. class NodeUtils extends UtilParser {
  7334. startNode() {
  7335. return new Node(this, this.state.start, this.state.startLoc);
  7336. }
  7337. startNodeAt(pos, loc) {
  7338. return new Node(this, pos, loc);
  7339. }
  7340. startNodeAtNode(type) {
  7341. return this.startNodeAt(type.start, type.loc.start);
  7342. }
  7343. finishNode(node, type) {
  7344. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  7345. }
  7346. finishNodeAt(node, type, pos, loc) {
  7347. node.type = type;
  7348. node.end = pos;
  7349. node.loc.end = loc;
  7350. if (this.options.ranges) node.range[1] = pos;
  7351. this.processComment(node);
  7352. return node;
  7353. }
  7354. resetStartLocation(node, start, startLoc) {
  7355. node.start = start;
  7356. node.loc.start = startLoc;
  7357. if (this.options.ranges) node.range[0] = start;
  7358. }
  7359. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  7360. node.end = end;
  7361. node.loc.end = endLoc;
  7362. if (this.options.ranges) node.range[1] = end;
  7363. }
  7364. resetStartLocationFromNode(node, locationNode) {
  7365. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  7366. }
  7367. }
  7368. const unwrapParenthesizedExpression = node => {
  7369. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7370. };
  7371. class LValParser extends NodeUtils {
  7372. toAssignable(node) {
  7373. var _node$extra, _node$extra3;
  7374. let parenthesized = undefined;
  7375. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  7376. parenthesized = unwrapParenthesizedExpression(node);
  7377. if (parenthesized.type !== "Identifier" && parenthesized.type !== "MemberExpression") {
  7378. this.raise(node.start, Errors.InvalidParenthesizedAssignment);
  7379. }
  7380. }
  7381. switch (node.type) {
  7382. case "Identifier":
  7383. case "ObjectPattern":
  7384. case "ArrayPattern":
  7385. case "AssignmentPattern":
  7386. break;
  7387. case "ObjectExpression":
  7388. node.type = "ObjectPattern";
  7389. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7390. var _node$extra2;
  7391. const prop = node.properties[i];
  7392. const isLast = i === last;
  7393. this.toAssignableObjectExpressionProp(prop, isLast);
  7394. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  7395. this.raiseRestNotLast(node.extra.trailingComma);
  7396. }
  7397. }
  7398. break;
  7399. case "ObjectProperty":
  7400. this.toAssignable(node.value);
  7401. break;
  7402. case "SpreadElement":
  7403. {
  7404. this.checkToRestConversion(node);
  7405. node.type = "RestElement";
  7406. const arg = node.argument;
  7407. this.toAssignable(arg);
  7408. break;
  7409. }
  7410. case "ArrayExpression":
  7411. node.type = "ArrayPattern";
  7412. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma);
  7413. break;
  7414. case "AssignmentExpression":
  7415. if (node.operator !== "=") {
  7416. this.raise(node.left.end, Errors.MissingEqInAssignment);
  7417. }
  7418. node.type = "AssignmentPattern";
  7419. delete node.operator;
  7420. this.toAssignable(node.left);
  7421. break;
  7422. case "ParenthesizedExpression":
  7423. this.toAssignable(parenthesized);
  7424. break;
  7425. }
  7426. return node;
  7427. }
  7428. toAssignableObjectExpressionProp(prop, isLast) {
  7429. if (prop.type === "ObjectMethod") {
  7430. const error = prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod;
  7431. this.raise(prop.key.start, error);
  7432. } else if (prop.type === "SpreadElement" && !isLast) {
  7433. this.raiseRestNotLast(prop.start);
  7434. } else {
  7435. this.toAssignable(prop);
  7436. }
  7437. }
  7438. toAssignableList(exprList, trailingCommaPos) {
  7439. let end = exprList.length;
  7440. if (end) {
  7441. const last = exprList[end - 1];
  7442. if (last && last.type === "RestElement") {
  7443. --end;
  7444. } else if (last && last.type === "SpreadElement") {
  7445. last.type = "RestElement";
  7446. const arg = last.argument;
  7447. this.toAssignable(arg);
  7448. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7449. this.unexpected(arg.start);
  7450. }
  7451. if (trailingCommaPos) {
  7452. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7453. }
  7454. --end;
  7455. }
  7456. }
  7457. for (let i = 0; i < end; i++) {
  7458. const elt = exprList[i];
  7459. if (elt) {
  7460. this.toAssignable(elt);
  7461. if (elt.type === "RestElement") {
  7462. this.raiseRestNotLast(elt.start);
  7463. }
  7464. }
  7465. }
  7466. return exprList;
  7467. }
  7468. toReferencedList(exprList, isParenthesizedExpr) {
  7469. return exprList;
  7470. }
  7471. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7472. this.toReferencedList(exprList, isParenthesizedExpr);
  7473. for (let _i = 0; _i < exprList.length; _i++) {
  7474. const expr = exprList[_i];
  7475. if (expr && expr.type === "ArrayExpression") {
  7476. this.toReferencedListDeep(expr.elements);
  7477. }
  7478. }
  7479. }
  7480. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  7481. const node = this.startNode();
  7482. this.next();
  7483. node.argument = this.parseMaybeAssign(false, refExpressionErrors, undefined, refNeedsArrowPos);
  7484. return this.finishNode(node, "SpreadElement");
  7485. }
  7486. parseRestBinding() {
  7487. const node = this.startNode();
  7488. this.next();
  7489. node.argument = this.parseBindingAtom();
  7490. return this.finishNode(node, "RestElement");
  7491. }
  7492. parseBindingAtom() {
  7493. switch (this.state.type) {
  7494. case types.bracketL:
  7495. {
  7496. const node = this.startNode();
  7497. this.next();
  7498. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7499. return this.finishNode(node, "ArrayPattern");
  7500. }
  7501. case types.braceL:
  7502. return this.parseObj(types.braceR, true);
  7503. }
  7504. return this.parseIdentifier();
  7505. }
  7506. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7507. const elts = [];
  7508. let first = true;
  7509. while (!this.eat(close)) {
  7510. if (first) {
  7511. first = false;
  7512. } else {
  7513. this.expect(types.comma);
  7514. }
  7515. if (allowEmpty && this.match(types.comma)) {
  7516. elts.push(null);
  7517. } else if (this.eat(close)) {
  7518. break;
  7519. } else if (this.match(types.ellipsis)) {
  7520. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7521. this.checkCommaAfterRest(closeCharCode);
  7522. this.expect(close);
  7523. break;
  7524. } else {
  7525. const decorators = [];
  7526. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7527. this.raise(this.state.start, Errors.UnsupportedParameterDecorator);
  7528. }
  7529. while (this.match(types.at)) {
  7530. decorators.push(this.parseDecorator());
  7531. }
  7532. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7533. }
  7534. }
  7535. return elts;
  7536. }
  7537. parseAssignableListItem(allowModifiers, decorators) {
  7538. const left = this.parseMaybeDefault();
  7539. this.parseAssignableListItemTypes(left);
  7540. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7541. if (decorators.length) {
  7542. left.decorators = decorators;
  7543. }
  7544. return elt;
  7545. }
  7546. parseAssignableListItemTypes(param) {
  7547. return param;
  7548. }
  7549. parseMaybeDefault(startPos, startLoc, left) {
  7550. startLoc = startLoc || this.state.startLoc;
  7551. startPos = startPos || this.state.start;
  7552. left = left || this.parseBindingAtom();
  7553. if (!this.eat(types.eq)) return left;
  7554. const node = this.startNodeAt(startPos, startLoc);
  7555. node.left = left;
  7556. node.right = this.parseMaybeAssign();
  7557. return this.finishNode(node, "AssignmentPattern");
  7558. }
  7559. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding, strictModeChanged = false) {
  7560. switch (expr.type) {
  7561. case "Identifier":
  7562. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) {
  7563. this.raise(expr.start, bindingType === BIND_NONE ? Errors.StrictEvalArguments : Errors.StrictEvalArgumentsBinding, expr.name);
  7564. }
  7565. if (checkClashes) {
  7566. const key = `_${expr.name}`;
  7567. if (checkClashes[key]) {
  7568. this.raise(expr.start, Errors.ParamDupe);
  7569. } else {
  7570. checkClashes[key] = true;
  7571. }
  7572. }
  7573. if (disallowLetBinding && expr.name === "let") {
  7574. this.raise(expr.start, Errors.LetInLexicalBinding);
  7575. }
  7576. if (!(bindingType & BIND_NONE)) {
  7577. this.scope.declareName(expr.name, bindingType, expr.start);
  7578. }
  7579. break;
  7580. case "MemberExpression":
  7581. if (bindingType !== BIND_NONE) {
  7582. this.raise(expr.start, Errors.InvalidPropertyBindingPattern);
  7583. }
  7584. break;
  7585. case "ObjectPattern":
  7586. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7587. let prop = _expr$properties[_i2];
  7588. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  7589. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  7590. }
  7591. break;
  7592. case "ArrayPattern":
  7593. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7594. const elem = _expr$elements[_i3];
  7595. if (elem) {
  7596. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding);
  7597. }
  7598. }
  7599. break;
  7600. case "AssignmentPattern":
  7601. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  7602. break;
  7603. case "RestElement":
  7604. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  7605. break;
  7606. case "ParenthesizedExpression":
  7607. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  7608. break;
  7609. default:
  7610. {
  7611. this.raise(expr.start, bindingType === BIND_NONE ? Errors.InvalidLhs : Errors.InvalidLhsBinding, contextDescription);
  7612. }
  7613. }
  7614. }
  7615. checkToRestConversion(node) {
  7616. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7617. this.raise(node.argument.start, Errors.InvalidRestAssignmentPattern);
  7618. }
  7619. }
  7620. checkCommaAfterRest(close) {
  7621. if (this.match(types.comma)) {
  7622. if (this.lookaheadCharCode() === close) {
  7623. this.raiseTrailingCommaAfterRest(this.state.start);
  7624. } else {
  7625. this.raiseRestNotLast(this.state.start);
  7626. }
  7627. }
  7628. }
  7629. raiseRestNotLast(pos) {
  7630. throw this.raise(pos, Errors.ElementAfterRest);
  7631. }
  7632. raiseTrailingCommaAfterRest(pos) {
  7633. this.raise(pos, Errors.RestTrailingComma);
  7634. }
  7635. }
  7636. class ExpressionParser extends LValParser {
  7637. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  7638. if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) {
  7639. return;
  7640. }
  7641. const key = prop.key;
  7642. const name = key.type === "Identifier" ? key.name : String(key.value);
  7643. if (name === "__proto__") {
  7644. if (protoRef.used) {
  7645. if (refExpressionErrors) {
  7646. if (refExpressionErrors.doubleProto === -1) {
  7647. refExpressionErrors.doubleProto = key.start;
  7648. }
  7649. } else {
  7650. this.raise(key.start, Errors.DuplicateProto);
  7651. }
  7652. }
  7653. protoRef.used = true;
  7654. }
  7655. }
  7656. getExpression() {
  7657. let paramFlags = PARAM;
  7658. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  7659. paramFlags |= PARAM_AWAIT;
  7660. }
  7661. this.scope.enter(SCOPE_PROGRAM);
  7662. this.prodParam.enter(paramFlags);
  7663. this.nextToken();
  7664. const expr = this.parseExpression();
  7665. if (!this.match(types.eof)) {
  7666. this.unexpected();
  7667. }
  7668. expr.comments = this.state.comments;
  7669. expr.errors = this.state.errors;
  7670. return expr;
  7671. }
  7672. parseExpression(noIn, refExpressionErrors) {
  7673. const startPos = this.state.start;
  7674. const startLoc = this.state.startLoc;
  7675. const expr = this.parseMaybeAssign(noIn, refExpressionErrors);
  7676. if (this.match(types.comma)) {
  7677. const node = this.startNodeAt(startPos, startLoc);
  7678. node.expressions = [expr];
  7679. while (this.eat(types.comma)) {
  7680. node.expressions.push(this.parseMaybeAssign(noIn, refExpressionErrors));
  7681. }
  7682. this.toReferencedList(node.expressions);
  7683. return this.finishNode(node, "SequenceExpression");
  7684. }
  7685. return expr;
  7686. }
  7687. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  7688. const startPos = this.state.start;
  7689. const startLoc = this.state.startLoc;
  7690. if (this.isContextual("yield")) {
  7691. if (this.prodParam.hasYield) {
  7692. let left = this.parseYield(noIn);
  7693. if (afterLeftParse) {
  7694. left = afterLeftParse.call(this, left, startPos, startLoc);
  7695. }
  7696. return left;
  7697. } else {
  7698. this.state.exprAllowed = false;
  7699. }
  7700. }
  7701. let ownExpressionErrors;
  7702. if (refExpressionErrors) {
  7703. ownExpressionErrors = false;
  7704. } else {
  7705. refExpressionErrors = new ExpressionErrors();
  7706. ownExpressionErrors = true;
  7707. }
  7708. if (this.match(types.parenL) || this.match(types.name)) {
  7709. this.state.potentialArrowAt = this.state.start;
  7710. }
  7711. let left = this.parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos);
  7712. if (afterLeftParse) {
  7713. left = afterLeftParse.call(this, left, startPos, startLoc);
  7714. }
  7715. if (this.state.type.isAssign) {
  7716. const node = this.startNodeAt(startPos, startLoc);
  7717. const operator = this.state.value;
  7718. node.operator = operator;
  7719. if (operator === "??=") {
  7720. this.expectPlugin("logicalAssignment");
  7721. }
  7722. if (operator === "||=" || operator === "&&=") {
  7723. this.expectPlugin("logicalAssignment");
  7724. }
  7725. if (this.match(types.eq)) {
  7726. node.left = this.toAssignable(left);
  7727. refExpressionErrors.doubleProto = -1;
  7728. } else {
  7729. node.left = left;
  7730. }
  7731. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  7732. refExpressionErrors.shorthandAssign = -1;
  7733. }
  7734. this.checkLVal(left, undefined, undefined, "assignment expression");
  7735. this.next();
  7736. node.right = this.parseMaybeAssign(noIn);
  7737. return this.finishNode(node, "AssignmentExpression");
  7738. } else if (ownExpressionErrors) {
  7739. this.checkExpressionErrors(refExpressionErrors, true);
  7740. }
  7741. return left;
  7742. }
  7743. parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos) {
  7744. const startPos = this.state.start;
  7745. const startLoc = this.state.startLoc;
  7746. const potentialArrowAt = this.state.potentialArrowAt;
  7747. const expr = this.parseExprOps(noIn, refExpressionErrors);
  7748. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7749. return expr;
  7750. }
  7751. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7752. return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  7753. }
  7754. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  7755. if (this.eat(types.question)) {
  7756. const node = this.startNodeAt(startPos, startLoc);
  7757. node.test = expr;
  7758. node.consequent = this.parseMaybeAssign();
  7759. this.expect(types.colon);
  7760. node.alternate = this.parseMaybeAssign(noIn);
  7761. return this.finishNode(node, "ConditionalExpression");
  7762. }
  7763. return expr;
  7764. }
  7765. parseExprOps(noIn, refExpressionErrors) {
  7766. const startPos = this.state.start;
  7767. const startLoc = this.state.startLoc;
  7768. const potentialArrowAt = this.state.potentialArrowAt;
  7769. const expr = this.parseMaybeUnary(refExpressionErrors);
  7770. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7771. return expr;
  7772. }
  7773. if (this.checkExpressionErrors(refExpressionErrors, false)) {
  7774. return expr;
  7775. }
  7776. return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  7777. }
  7778. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  7779. let prec = this.state.type.binop;
  7780. if (prec != null && (!noIn || !this.match(types._in))) {
  7781. if (prec > minPrec) {
  7782. const operator = this.state.value;
  7783. if (operator === "|>" && this.state.inFSharpPipelineDirectBody) {
  7784. return left;
  7785. }
  7786. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  7787. node.left = left;
  7788. node.operator = operator;
  7789. if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  7790. this.raise(left.argument.start, Errors.UnexpectedTokenUnaryExponentiation);
  7791. }
  7792. const op = this.state.type;
  7793. const logical = op === types.logicalOR || op === types.logicalAND;
  7794. const coalesce = op === types.nullishCoalescing;
  7795. if (op === types.pipeline) {
  7796. this.expectPlugin("pipelineOperator");
  7797. this.state.inPipeline = true;
  7798. this.checkPipelineAtInfixOperator(left, leftStartPos);
  7799. } else if (coalesce) {
  7800. prec = types.logicalAND.binop;
  7801. }
  7802. this.next();
  7803. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  7804. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  7805. throw this.raise(this.state.start, Errors.UnexpectedAwaitAfterPipelineBody);
  7806. }
  7807. }
  7808. node.right = this.parseExprOpRightExpr(op, prec, noIn);
  7809. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  7810. const nextOp = this.state.type;
  7811. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  7812. throw this.raise(this.state.start, Errors.MixingCoalesceWithLogical);
  7813. }
  7814. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  7815. }
  7816. }
  7817. return left;
  7818. }
  7819. parseExprOpRightExpr(op, prec, noIn) {
  7820. const startPos = this.state.start;
  7821. const startLoc = this.state.startLoc;
  7822. switch (op) {
  7823. case types.pipeline:
  7824. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  7825. case "smart":
  7826. return this.withTopicPermittingContext(() => {
  7827. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc);
  7828. });
  7829. case "fsharp":
  7830. return this.withSoloAwaitPermittingContext(() => {
  7831. return this.parseFSharpPipelineBody(prec, noIn);
  7832. });
  7833. }
  7834. default:
  7835. return this.parseExprOpBaseRightExpr(op, prec, noIn);
  7836. }
  7837. }
  7838. parseExprOpBaseRightExpr(op, prec, noIn) {
  7839. const startPos = this.state.start;
  7840. const startLoc = this.state.startLoc;
  7841. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
  7842. }
  7843. parseMaybeUnary(refExpressionErrors) {
  7844. if (this.isContextual("await") && this.isAwaitAllowed()) {
  7845. return this.parseAwait();
  7846. } else if (this.state.type.prefix) {
  7847. const node = this.startNode();
  7848. const update = this.match(types.incDec);
  7849. node.operator = this.state.value;
  7850. node.prefix = true;
  7851. if (node.operator === "throw") {
  7852. this.expectPlugin("throwExpressions");
  7853. }
  7854. this.next();
  7855. node.argument = this.parseMaybeUnary();
  7856. this.checkExpressionErrors(refExpressionErrors, true);
  7857. if (update) {
  7858. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  7859. } else if (this.state.strict && node.operator === "delete") {
  7860. const arg = node.argument;
  7861. if (arg.type === "Identifier") {
  7862. this.raise(node.start, Errors.StrictDelete);
  7863. } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") {
  7864. this.raise(node.start, Errors.DeletePrivateField);
  7865. }
  7866. }
  7867. return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  7868. }
  7869. const startPos = this.state.start;
  7870. const startLoc = this.state.startLoc;
  7871. let expr = this.parseExprSubscripts(refExpressionErrors);
  7872. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7873. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  7874. const node = this.startNodeAt(startPos, startLoc);
  7875. node.operator = this.state.value;
  7876. node.prefix = false;
  7877. node.argument = expr;
  7878. this.checkLVal(expr, undefined, undefined, "postfix operation");
  7879. this.next();
  7880. expr = this.finishNode(node, "UpdateExpression");
  7881. }
  7882. return expr;
  7883. }
  7884. parseExprSubscripts(refExpressionErrors) {
  7885. const startPos = this.state.start;
  7886. const startLoc = this.state.startLoc;
  7887. const potentialArrowAt = this.state.potentialArrowAt;
  7888. const expr = this.parseExprAtom(refExpressionErrors);
  7889. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7890. return expr;
  7891. }
  7892. return this.parseSubscripts(expr, startPos, startLoc);
  7893. }
  7894. parseSubscripts(base, startPos, startLoc, noCalls) {
  7895. const state = {
  7896. optionalChainMember: false,
  7897. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  7898. stop: false
  7899. };
  7900. do {
  7901. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  7902. if (state.maybeAsyncArrow) {
  7903. this.state.maybeInAsyncArrowHead = true;
  7904. }
  7905. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  7906. state.maybeAsyncArrow = false;
  7907. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  7908. } while (!state.stop);
  7909. return base;
  7910. }
  7911. parseSubscript(base, startPos, startLoc, noCalls, state) {
  7912. if (!noCalls && this.eat(types.doubleColon)) {
  7913. const node = this.startNodeAt(startPos, startLoc);
  7914. node.object = base;
  7915. node.callee = this.parseNoCallExpr();
  7916. state.stop = true;
  7917. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  7918. }
  7919. let optional = false;
  7920. if (this.match(types.questionDot)) {
  7921. state.optionalChainMember = optional = true;
  7922. if (noCalls && this.lookaheadCharCode() === 40) {
  7923. state.stop = true;
  7924. return base;
  7925. }
  7926. this.next();
  7927. }
  7928. const computed = this.eat(types.bracketL);
  7929. if (optional && !this.match(types.parenL) && !this.match(types.backQuote) || computed || this.eat(types.dot)) {
  7930. const node = this.startNodeAt(startPos, startLoc);
  7931. node.object = base;
  7932. node.property = computed ? this.parseExpression() : optional ? this.parseIdentifier(true) : this.parseMaybePrivateName(true);
  7933. node.computed = computed;
  7934. if (node.property.type === "PrivateName") {
  7935. if (node.object.type === "Super") {
  7936. this.raise(startPos, Errors.SuperPrivateField);
  7937. }
  7938. this.classScope.usePrivateName(node.property.id.name, node.property.start);
  7939. }
  7940. if (computed) {
  7941. this.expect(types.bracketR);
  7942. }
  7943. if (state.optionalChainMember) {
  7944. node.optional = optional;
  7945. return this.finishNode(node, "OptionalMemberExpression");
  7946. } else {
  7947. return this.finishNode(node, "MemberExpression");
  7948. }
  7949. } else if (!noCalls && this.match(types.parenL)) {
  7950. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7951. const oldYieldPos = this.state.yieldPos;
  7952. const oldAwaitPos = this.state.awaitPos;
  7953. this.state.maybeInArrowParameters = true;
  7954. this.state.yieldPos = -1;
  7955. this.state.awaitPos = -1;
  7956. this.next();
  7957. let node = this.startNodeAt(startPos, startLoc);
  7958. node.callee = base;
  7959. if (optional) {
  7960. node.optional = true;
  7961. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  7962. } else {
  7963. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  7964. }
  7965. this.finishCallExpression(node, state.optionalChainMember);
  7966. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  7967. state.stop = true;
  7968. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  7969. this.checkYieldAwaitInDefaultParams();
  7970. this.state.yieldPos = oldYieldPos;
  7971. this.state.awaitPos = oldAwaitPos;
  7972. } else {
  7973. this.toReferencedListDeep(node.arguments);
  7974. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  7975. if (!this.isAwaitAllowed() && !oldMaybeInArrowParameters || oldAwaitPos !== -1) {
  7976. this.state.awaitPos = oldAwaitPos;
  7977. }
  7978. }
  7979. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7980. return node;
  7981. } else if (this.match(types.backQuote)) {
  7982. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state);
  7983. } else {
  7984. state.stop = true;
  7985. return base;
  7986. }
  7987. }
  7988. parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) {
  7989. const node = this.startNodeAt(startPos, startLoc);
  7990. node.tag = base;
  7991. node.quasi = this.parseTemplate(true);
  7992. if (typeArguments) node.typeParameters = typeArguments;
  7993. if (state.optionalChainMember) {
  7994. this.raise(startPos, Errors.OptionalChainingNoTemplate);
  7995. }
  7996. return this.finishNode(node, "TaggedTemplateExpression");
  7997. }
  7998. atPossibleAsyncArrow(base) {
  7999. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  8000. }
  8001. finishCallExpression(node, optional) {
  8002. if (node.callee.type === "Import") {
  8003. if (node.arguments.length !== 1) {
  8004. this.raise(node.start, Errors.ImportCallArity);
  8005. } else {
  8006. const importArg = node.arguments[0];
  8007. if (importArg && importArg.type === "SpreadElement") {
  8008. this.raise(importArg.start, Errors.ImportCallSpreadArgument);
  8009. }
  8010. }
  8011. }
  8012. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  8013. }
  8014. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  8015. const elts = [];
  8016. let innerParenStart;
  8017. let first = true;
  8018. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8019. this.state.inFSharpPipelineDirectBody = false;
  8020. while (!this.eat(close)) {
  8021. if (first) {
  8022. first = false;
  8023. } else {
  8024. this.expect(types.comma);
  8025. if (this.match(close)) {
  8026. if (dynamicImport) {
  8027. this.raise(this.state.lastTokStart, Errors.ImportCallArgumentTrailingComma);
  8028. }
  8029. if (nodeForExtra) {
  8030. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8031. }
  8032. this.next();
  8033. break;
  8034. }
  8035. }
  8036. if (this.match(types.parenL) && !innerParenStart) {
  8037. innerParenStart = this.state.start;
  8038. }
  8039. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8040. start: 0
  8041. } : undefined, allowPlaceholder));
  8042. }
  8043. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  8044. this.unexpected();
  8045. }
  8046. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8047. return elts;
  8048. }
  8049. shouldParseAsyncArrow() {
  8050. return this.match(types.arrow) && !this.canInsertSemicolon();
  8051. }
  8052. parseAsyncArrowFromCallExpression(node, call) {
  8053. var _call$extra;
  8054. this.expect(types.arrow);
  8055. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8056. return node;
  8057. }
  8058. parseNoCallExpr() {
  8059. const startPos = this.state.start;
  8060. const startLoc = this.state.startLoc;
  8061. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8062. }
  8063. parseExprAtom(refExpressionErrors) {
  8064. if (this.state.type === types.slash) this.readRegexp();
  8065. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8066. let node;
  8067. switch (this.state.type) {
  8068. case types._super:
  8069. node = this.startNode();
  8070. this.next();
  8071. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  8072. this.raise(node.start, Errors.SuperNotAllowed);
  8073. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  8074. this.raise(node.start, Errors.UnexpectedSuper);
  8075. }
  8076. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  8077. this.raise(node.start, Errors.UnsupportedSuper);
  8078. }
  8079. return this.finishNode(node, "Super");
  8080. case types._import:
  8081. node = this.startNode();
  8082. this.next();
  8083. if (this.match(types.dot)) {
  8084. return this.parseImportMetaProperty(node);
  8085. }
  8086. if (!this.match(types.parenL)) {
  8087. this.raise(this.state.lastTokStart, Errors.UnsupportedImport);
  8088. }
  8089. return this.finishNode(node, "Import");
  8090. case types._this:
  8091. node = this.startNode();
  8092. this.next();
  8093. return this.finishNode(node, "ThisExpression");
  8094. case types.name:
  8095. {
  8096. node = this.startNode();
  8097. const containsEsc = this.state.containsEsc;
  8098. const id = this.parseIdentifier();
  8099. if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) {
  8100. const last = this.state.context.length - 1;
  8101. if (this.state.context[last] !== types$1.functionStatement) {
  8102. throw new Error("Internal error");
  8103. }
  8104. this.state.context[last] = types$1.functionExpression;
  8105. this.next();
  8106. return this.parseFunction(node, undefined, true);
  8107. } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) {
  8108. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8109. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  8110. const oldYieldPos = this.state.yieldPos;
  8111. const oldAwaitPos = this.state.awaitPos;
  8112. this.state.maybeInArrowParameters = true;
  8113. this.state.maybeInAsyncArrowHead = true;
  8114. this.state.yieldPos = -1;
  8115. this.state.awaitPos = -1;
  8116. const params = [this.parseIdentifier()];
  8117. this.expect(types.arrow);
  8118. this.checkYieldAwaitInDefaultParams();
  8119. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8120. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  8121. this.state.yieldPos = oldYieldPos;
  8122. this.state.awaitPos = oldAwaitPos;
  8123. this.parseArrowExpression(node, params, true);
  8124. return node;
  8125. }
  8126. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8127. this.next();
  8128. this.parseArrowExpression(node, [id], false);
  8129. return node;
  8130. }
  8131. return id;
  8132. }
  8133. case types._do:
  8134. {
  8135. this.expectPlugin("doExpressions");
  8136. const node = this.startNode();
  8137. this.next();
  8138. const oldLabels = this.state.labels;
  8139. this.state.labels = [];
  8140. node.body = this.parseBlock();
  8141. this.state.labels = oldLabels;
  8142. return this.finishNode(node, "DoExpression");
  8143. }
  8144. case types.regexp:
  8145. {
  8146. const value = this.state.value;
  8147. node = this.parseLiteral(value.value, "RegExpLiteral");
  8148. node.pattern = value.pattern;
  8149. node.flags = value.flags;
  8150. return node;
  8151. }
  8152. case types.num:
  8153. return this.parseLiteral(this.state.value, "NumericLiteral");
  8154. case types.bigint:
  8155. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8156. case types.string:
  8157. return this.parseLiteral(this.state.value, "StringLiteral");
  8158. case types._null:
  8159. node = this.startNode();
  8160. this.next();
  8161. return this.finishNode(node, "NullLiteral");
  8162. case types._true:
  8163. case types._false:
  8164. return this.parseBooleanLiteral();
  8165. case types.parenL:
  8166. return this.parseParenAndDistinguishExpression(canBeArrow);
  8167. case types.bracketBarL:
  8168. case types.bracketHashL:
  8169. {
  8170. this.expectPlugin("recordAndTuple");
  8171. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8172. const close = this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR;
  8173. this.state.inFSharpPipelineDirectBody = false;
  8174. node = this.startNode();
  8175. this.next();
  8176. node.elements = this.parseExprList(close, true, refExpressionErrors, node);
  8177. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8178. return this.finishNode(node, "TupleExpression");
  8179. }
  8180. case types.bracketL:
  8181. {
  8182. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8183. this.state.inFSharpPipelineDirectBody = false;
  8184. node = this.startNode();
  8185. this.next();
  8186. node.elements = this.parseExprList(types.bracketR, true, refExpressionErrors, node);
  8187. if (!this.state.maybeInArrowParameters) {
  8188. this.toReferencedList(node.elements);
  8189. }
  8190. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8191. return this.finishNode(node, "ArrayExpression");
  8192. }
  8193. case types.braceBarL:
  8194. case types.braceHashL:
  8195. {
  8196. this.expectPlugin("recordAndTuple");
  8197. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8198. const close = this.state.type === types.braceBarL ? types.braceBarR : types.braceR;
  8199. this.state.inFSharpPipelineDirectBody = false;
  8200. const ret = this.parseObj(close, false, true, refExpressionErrors);
  8201. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8202. return ret;
  8203. }
  8204. case types.braceL:
  8205. {
  8206. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8207. this.state.inFSharpPipelineDirectBody = false;
  8208. const ret = this.parseObj(types.braceR, false, false, refExpressionErrors);
  8209. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8210. return ret;
  8211. }
  8212. case types._function:
  8213. return this.parseFunctionExpression();
  8214. case types.at:
  8215. this.parseDecorators();
  8216. case types._class:
  8217. node = this.startNode();
  8218. this.takeDecorators(node);
  8219. return this.parseClass(node, false);
  8220. case types._new:
  8221. return this.parseNew();
  8222. case types.backQuote:
  8223. return this.parseTemplate(false);
  8224. case types.doubleColon:
  8225. {
  8226. node = this.startNode();
  8227. this.next();
  8228. node.object = null;
  8229. const callee = node.callee = this.parseNoCallExpr();
  8230. if (callee.type === "MemberExpression") {
  8231. return this.finishNode(node, "BindExpression");
  8232. } else {
  8233. throw this.raise(callee.start, Errors.UnsupportedBind);
  8234. }
  8235. }
  8236. case types.hash:
  8237. {
  8238. if (this.state.inPipeline) {
  8239. node = this.startNode();
  8240. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  8241. this.raise(node.start, Errors.PrimaryTopicRequiresSmartPipeline);
  8242. }
  8243. this.next();
  8244. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  8245. this.raise(node.start, Errors.PrimaryTopicNotAllowed);
  8246. }
  8247. this.registerTopicReference();
  8248. return this.finishNode(node, "PipelinePrimaryTopicReference");
  8249. }
  8250. }
  8251. default:
  8252. throw this.unexpected();
  8253. }
  8254. }
  8255. parseBooleanLiteral() {
  8256. const node = this.startNode();
  8257. node.value = this.match(types._true);
  8258. this.next();
  8259. return this.finishNode(node, "BooleanLiteral");
  8260. }
  8261. parseMaybePrivateName(isPrivateNameAllowed) {
  8262. const isPrivate = this.match(types.hash);
  8263. if (isPrivate) {
  8264. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  8265. if (!isPrivateNameAllowed) {
  8266. this.raise(this.state.pos, Errors.UnexpectedPrivateField);
  8267. }
  8268. const node = this.startNode();
  8269. this.next();
  8270. this.assertNoSpace("Unexpected space between # and identifier");
  8271. node.id = this.parseIdentifier(true);
  8272. return this.finishNode(node, "PrivateName");
  8273. } else {
  8274. return this.parseIdentifier(true);
  8275. }
  8276. }
  8277. parseFunctionExpression() {
  8278. const node = this.startNode();
  8279. let meta = this.startNode();
  8280. this.next();
  8281. meta = this.createIdentifier(meta, "function");
  8282. if (this.prodParam.hasYield && this.eat(types.dot)) {
  8283. return this.parseMetaProperty(node, meta, "sent");
  8284. }
  8285. return this.parseFunction(node);
  8286. }
  8287. parseMetaProperty(node, meta, propertyName) {
  8288. node.meta = meta;
  8289. if (meta.name === "function" && propertyName === "sent") {
  8290. if (this.isContextual(propertyName)) {
  8291. this.expectPlugin("functionSent");
  8292. } else if (!this.hasPlugin("functionSent")) {
  8293. this.unexpected();
  8294. }
  8295. }
  8296. const containsEsc = this.state.containsEsc;
  8297. node.property = this.parseIdentifier(true);
  8298. if (node.property.name !== propertyName || containsEsc) {
  8299. this.raise(node.property.start, Errors.UnsupportedMetaProperty, meta.name, propertyName);
  8300. }
  8301. return this.finishNode(node, "MetaProperty");
  8302. }
  8303. parseImportMetaProperty(node) {
  8304. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  8305. this.expect(types.dot);
  8306. if (this.isContextual("meta")) {
  8307. this.expectPlugin("importMeta");
  8308. if (!this.inModule) {
  8309. this.raiseWithData(id.start, {
  8310. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8311. }, Errors.ImportMetaOutsideModule);
  8312. }
  8313. this.sawUnambiguousESM = true;
  8314. } else if (!this.hasPlugin("importMeta")) {
  8315. this.raise(id.start, Errors.ImportCallArityLtOne);
  8316. }
  8317. return this.parseMetaProperty(node, id, "meta");
  8318. }
  8319. parseLiteral(value, type, startPos, startLoc) {
  8320. startPos = startPos || this.state.start;
  8321. startLoc = startLoc || this.state.startLoc;
  8322. const node = this.startNodeAt(startPos, startLoc);
  8323. this.addExtra(node, "rawValue", value);
  8324. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  8325. node.value = value;
  8326. this.next();
  8327. return this.finishNode(node, type);
  8328. }
  8329. parseParenAndDistinguishExpression(canBeArrow) {
  8330. const startPos = this.state.start;
  8331. const startLoc = this.state.startLoc;
  8332. let val;
  8333. this.expect(types.parenL);
  8334. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8335. const oldYieldPos = this.state.yieldPos;
  8336. const oldAwaitPos = this.state.awaitPos;
  8337. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8338. this.state.maybeInArrowParameters = true;
  8339. this.state.yieldPos = -1;
  8340. this.state.awaitPos = -1;
  8341. this.state.inFSharpPipelineDirectBody = false;
  8342. const innerStartPos = this.state.start;
  8343. const innerStartLoc = this.state.startLoc;
  8344. const exprList = [];
  8345. const refExpressionErrors = new ExpressionErrors();
  8346. const refNeedsArrowPos = {
  8347. start: 0
  8348. };
  8349. let first = true;
  8350. let spreadStart;
  8351. let optionalCommaStart;
  8352. while (!this.match(types.parenR)) {
  8353. if (first) {
  8354. first = false;
  8355. } else {
  8356. this.expect(types.comma, refNeedsArrowPos.start || null);
  8357. if (this.match(types.parenR)) {
  8358. optionalCommaStart = this.state.start;
  8359. break;
  8360. }
  8361. }
  8362. if (this.match(types.ellipsis)) {
  8363. const spreadNodeStartPos = this.state.start;
  8364. const spreadNodeStartLoc = this.state.startLoc;
  8365. spreadStart = this.state.start;
  8366. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  8367. this.checkCommaAfterRest(41);
  8368. break;
  8369. } else {
  8370. exprList.push(this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  8371. }
  8372. }
  8373. const innerEndPos = this.state.start;
  8374. const innerEndLoc = this.state.startLoc;
  8375. this.expect(types.parenR);
  8376. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8377. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8378. let arrowNode = this.startNodeAt(startPos, startLoc);
  8379. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  8380. if (!this.isAwaitAllowed() && !this.state.maybeInAsyncArrowHead) {
  8381. this.state.awaitPos = oldAwaitPos;
  8382. }
  8383. this.checkYieldAwaitInDefaultParams();
  8384. this.state.yieldPos = oldYieldPos;
  8385. this.state.awaitPos = oldAwaitPos;
  8386. for (let _i = 0; _i < exprList.length; _i++) {
  8387. const param = exprList[_i];
  8388. if (param.extra && param.extra.parenthesized) {
  8389. this.unexpected(param.extra.parenStart);
  8390. }
  8391. }
  8392. this.parseArrowExpression(arrowNode, exprList, false);
  8393. return arrowNode;
  8394. }
  8395. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  8396. if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
  8397. if (!exprList.length) {
  8398. this.unexpected(this.state.lastTokStart);
  8399. }
  8400. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8401. if (spreadStart) this.unexpected(spreadStart);
  8402. this.checkExpressionErrors(refExpressionErrors, true);
  8403. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8404. this.toReferencedListDeep(exprList, true);
  8405. if (exprList.length > 1) {
  8406. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8407. val.expressions = exprList;
  8408. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8409. } else {
  8410. val = exprList[0];
  8411. }
  8412. if (!this.options.createParenthesizedExpressions) {
  8413. this.addExtra(val, "parenthesized", true);
  8414. this.addExtra(val, "parenStart", startPos);
  8415. return val;
  8416. }
  8417. const parenExpression = this.startNodeAt(startPos, startLoc);
  8418. parenExpression.expression = val;
  8419. this.finishNode(parenExpression, "ParenthesizedExpression");
  8420. return parenExpression;
  8421. }
  8422. shouldParseArrow() {
  8423. return !this.canInsertSemicolon();
  8424. }
  8425. parseArrow(node) {
  8426. if (this.eat(types.arrow)) {
  8427. return node;
  8428. }
  8429. }
  8430. parseParenItem(node, startPos, startLoc) {
  8431. return node;
  8432. }
  8433. parseNew() {
  8434. const node = this.startNode();
  8435. let meta = this.startNode();
  8436. this.next();
  8437. meta = this.createIdentifier(meta, "new");
  8438. if (this.eat(types.dot)) {
  8439. const metaProp = this.parseMetaProperty(node, meta, "target");
  8440. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  8441. let error = Errors.UnexpectedNewTarget;
  8442. if (this.hasPlugin("classProperties")) {
  8443. error += " or class properties";
  8444. }
  8445. this.raise(metaProp.start, error);
  8446. }
  8447. return metaProp;
  8448. }
  8449. node.callee = this.parseNoCallExpr();
  8450. if (node.callee.type === "Import") {
  8451. this.raise(node.callee.start, Errors.ImportCallNotNewExpression);
  8452. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  8453. this.raise(this.state.lastTokEnd, Errors.OptionalChainingNoNew);
  8454. } else if (this.eat(types.questionDot)) {
  8455. this.raise(this.state.start, Errors.OptionalChainingNoNew);
  8456. }
  8457. this.parseNewArguments(node);
  8458. return this.finishNode(node, "NewExpression");
  8459. }
  8460. parseNewArguments(node) {
  8461. if (this.eat(types.parenL)) {
  8462. const args = this.parseExprList(types.parenR);
  8463. this.toReferencedList(args);
  8464. node.arguments = args;
  8465. } else {
  8466. node.arguments = [];
  8467. }
  8468. }
  8469. parseTemplateElement(isTagged) {
  8470. const elem = this.startNode();
  8471. if (this.state.value === null) {
  8472. if (!isTagged) {
  8473. this.raise(this.state.start + 1, Errors.InvalidEscapeSequenceTemplate);
  8474. }
  8475. }
  8476. elem.value = {
  8477. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8478. cooked: this.state.value
  8479. };
  8480. this.next();
  8481. elem.tail = this.match(types.backQuote);
  8482. return this.finishNode(elem, "TemplateElement");
  8483. }
  8484. parseTemplate(isTagged) {
  8485. const node = this.startNode();
  8486. this.next();
  8487. node.expressions = [];
  8488. let curElt = this.parseTemplateElement(isTagged);
  8489. node.quasis = [curElt];
  8490. while (!curElt.tail) {
  8491. this.expect(types.dollarBraceL);
  8492. node.expressions.push(this.parseExpression());
  8493. this.expect(types.braceR);
  8494. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8495. }
  8496. this.next();
  8497. return this.finishNode(node, "TemplateLiteral");
  8498. }
  8499. parseObj(close, isPattern, isRecord, refExpressionErrors) {
  8500. const propHash = Object.create(null);
  8501. let first = true;
  8502. const node = this.startNode();
  8503. node.properties = [];
  8504. this.next();
  8505. while (!this.eat(close)) {
  8506. if (first) {
  8507. first = false;
  8508. } else {
  8509. this.expect(types.comma);
  8510. if (this.match(close)) {
  8511. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8512. this.next();
  8513. break;
  8514. }
  8515. }
  8516. const prop = this.parseObjectMember(isPattern, refExpressionErrors);
  8517. if (!isPattern) {
  8518. this.checkDuplicatedProto(prop, propHash, refExpressionErrors);
  8519. }
  8520. if (prop.shorthand) {
  8521. this.addExtra(prop, "shorthand", true);
  8522. }
  8523. node.properties.push(prop);
  8524. }
  8525. let type = "ObjectExpression";
  8526. if (isPattern) {
  8527. type = "ObjectPattern";
  8528. } else if (isRecord) {
  8529. type = "RecordExpression";
  8530. }
  8531. return this.finishNode(node, type);
  8532. }
  8533. isAsyncProp(prop) {
  8534. 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();
  8535. }
  8536. parseObjectMember(isPattern, refExpressionErrors) {
  8537. let decorators = [];
  8538. if (this.match(types.at)) {
  8539. if (this.hasPlugin("decorators")) {
  8540. this.raise(this.state.start, Errors.UnsupportedPropertyDecorator);
  8541. }
  8542. while (this.match(types.at)) {
  8543. decorators.push(this.parseDecorator());
  8544. }
  8545. }
  8546. const prop = this.startNode();
  8547. let isGenerator = false;
  8548. let isAsync = false;
  8549. let startPos;
  8550. let startLoc;
  8551. if (this.match(types.ellipsis)) {
  8552. if (decorators.length) this.unexpected();
  8553. if (isPattern) {
  8554. this.next();
  8555. prop.argument = this.parseIdentifier();
  8556. this.checkCommaAfterRest(125);
  8557. return this.finishNode(prop, "RestElement");
  8558. }
  8559. return this.parseSpread();
  8560. }
  8561. if (decorators.length) {
  8562. prop.decorators = decorators;
  8563. decorators = [];
  8564. }
  8565. prop.method = false;
  8566. if (isPattern || refExpressionErrors) {
  8567. startPos = this.state.start;
  8568. startLoc = this.state.startLoc;
  8569. }
  8570. if (!isPattern) {
  8571. isGenerator = this.eat(types.star);
  8572. }
  8573. const containsEsc = this.state.containsEsc;
  8574. this.parsePropertyName(prop, false);
  8575. if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) {
  8576. isAsync = true;
  8577. isGenerator = this.eat(types.star);
  8578. this.parsePropertyName(prop, false);
  8579. } else {
  8580. isAsync = false;
  8581. }
  8582. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  8583. return prop;
  8584. }
  8585. isGetterOrSetterMethod(prop, isPattern) {
  8586. 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);
  8587. }
  8588. getGetterSetterExpectedParamCount(method) {
  8589. return method.kind === "get" ? 0 : 1;
  8590. }
  8591. checkGetterSetterParams(method) {
  8592. const paramCount = this.getGetterSetterExpectedParamCount(method);
  8593. const start = method.start;
  8594. if (method.params.length !== paramCount) {
  8595. if (method.kind === "get") {
  8596. this.raise(start, Errors.BadGetterArity);
  8597. } else {
  8598. this.raise(start, Errors.BadSetterArity);
  8599. }
  8600. }
  8601. if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") {
  8602. this.raise(start, Errors.BadSetterRestParameter);
  8603. }
  8604. }
  8605. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  8606. if (isAsync || isGenerator || this.match(types.parenL)) {
  8607. if (isPattern) this.unexpected();
  8608. prop.kind = "method";
  8609. prop.method = true;
  8610. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  8611. }
  8612. if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) {
  8613. if (isGenerator || isAsync) this.unexpected();
  8614. prop.kind = prop.key.name;
  8615. this.parsePropertyName(prop, false);
  8616. this.parseMethod(prop, false, false, false, false, "ObjectMethod");
  8617. this.checkGetterSetterParams(prop);
  8618. return prop;
  8619. }
  8620. }
  8621. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  8622. prop.shorthand = false;
  8623. if (this.eat(types.colon)) {
  8624. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refExpressionErrors);
  8625. return this.finishNode(prop, "ObjectProperty");
  8626. }
  8627. if (!prop.computed && prop.key.type === "Identifier") {
  8628. this.checkReservedWord(prop.key.name, prop.key.start, true, true);
  8629. if (isPattern) {
  8630. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8631. } else if (this.match(types.eq) && refExpressionErrors) {
  8632. if (refExpressionErrors.shorthandAssign === -1) {
  8633. refExpressionErrors.shorthandAssign = this.state.start;
  8634. }
  8635. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8636. } else {
  8637. prop.value = prop.key.__clone();
  8638. }
  8639. prop.shorthand = true;
  8640. return this.finishNode(prop, "ObjectProperty");
  8641. }
  8642. }
  8643. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  8644. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  8645. if (!node) this.unexpected();
  8646. return node;
  8647. }
  8648. parsePropertyName(prop, isPrivateNameAllowed) {
  8649. if (this.eat(types.bracketL)) {
  8650. prop.computed = true;
  8651. prop.key = this.parseMaybeAssign();
  8652. this.expect(types.bracketR);
  8653. } else {
  8654. const oldInPropertyName = this.state.inPropertyName;
  8655. this.state.inPropertyName = true;
  8656. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  8657. if (prop.key.type !== "PrivateName") {
  8658. prop.computed = false;
  8659. }
  8660. this.state.inPropertyName = oldInPropertyName;
  8661. }
  8662. return prop.key;
  8663. }
  8664. initFunction(node, isAsync) {
  8665. node.id = null;
  8666. node.generator = false;
  8667. node.async = !!isAsync;
  8668. }
  8669. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  8670. const oldYieldPos = this.state.yieldPos;
  8671. const oldAwaitPos = this.state.awaitPos;
  8672. this.state.yieldPos = -1;
  8673. this.state.awaitPos = -1;
  8674. this.initFunction(node, isAsync);
  8675. node.generator = !!isGenerator;
  8676. const allowModifiers = isConstructor;
  8677. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  8678. this.prodParam.enter(functionFlags(isAsync, node.generator));
  8679. this.parseFunctionParams(node, allowModifiers);
  8680. this.parseFunctionBodyAndFinish(node, type, true);
  8681. this.prodParam.exit();
  8682. this.scope.exit();
  8683. this.state.yieldPos = oldYieldPos;
  8684. this.state.awaitPos = oldAwaitPos;
  8685. return node;
  8686. }
  8687. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  8688. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  8689. this.prodParam.enter(functionFlags(isAsync, false));
  8690. this.initFunction(node, isAsync);
  8691. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8692. const oldYieldPos = this.state.yieldPos;
  8693. const oldAwaitPos = this.state.awaitPos;
  8694. if (params) {
  8695. this.state.maybeInArrowParameters = true;
  8696. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  8697. }
  8698. this.state.maybeInArrowParameters = false;
  8699. this.state.yieldPos = -1;
  8700. this.state.awaitPos = -1;
  8701. this.parseFunctionBody(node, true);
  8702. this.prodParam.exit();
  8703. this.scope.exit();
  8704. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8705. this.state.yieldPos = oldYieldPos;
  8706. this.state.awaitPos = oldAwaitPos;
  8707. return this.finishNode(node, "ArrowFunctionExpression");
  8708. }
  8709. setArrowFunctionParameters(node, params, trailingCommaPos) {
  8710. node.params = this.toAssignableList(params, trailingCommaPos);
  8711. }
  8712. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8713. this.parseFunctionBody(node, false, isMethod);
  8714. this.finishNode(node, type);
  8715. }
  8716. parseFunctionBody(node, allowExpression, isMethod = false) {
  8717. const isExpression = allowExpression && !this.match(types.braceL);
  8718. const oldInParameters = this.state.inParameters;
  8719. this.state.inParameters = false;
  8720. if (isExpression) {
  8721. node.body = this.parseMaybeAssign();
  8722. this.checkParams(node, false, allowExpression, false);
  8723. } else {
  8724. const oldStrict = this.state.strict;
  8725. const oldLabels = this.state.labels;
  8726. this.state.labels = [];
  8727. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  8728. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  8729. const nonSimple = !this.isSimpleParamList(node.params);
  8730. if (hasStrictModeDirective && nonSimple) {
  8731. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  8732. this.raise(errorPos, Errors.IllegalLanguageModeDirective);
  8733. }
  8734. const strictModeChanged = !oldStrict && this.state.strict;
  8735. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  8736. if (this.state.strict && node.id) {
  8737. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, strictModeChanged);
  8738. }
  8739. });
  8740. this.prodParam.exit();
  8741. this.state.labels = oldLabels;
  8742. }
  8743. this.state.inParameters = oldInParameters;
  8744. }
  8745. isSimpleParamList(params) {
  8746. for (let i = 0, len = params.length; i < len; i++) {
  8747. if (params[i].type !== "Identifier") return false;
  8748. }
  8749. return true;
  8750. }
  8751. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  8752. const nameHash = Object.create(null);
  8753. for (let i = 0; i < node.params.length; i++) {
  8754. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged);
  8755. }
  8756. }
  8757. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  8758. const elts = [];
  8759. let first = true;
  8760. while (!this.eat(close)) {
  8761. if (first) {
  8762. first = false;
  8763. } else {
  8764. this.expect(types.comma);
  8765. if (this.match(close)) {
  8766. if (nodeForExtra) {
  8767. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8768. }
  8769. this.next();
  8770. break;
  8771. }
  8772. }
  8773. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  8774. }
  8775. return elts;
  8776. }
  8777. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  8778. let elt;
  8779. if (allowEmpty && this.match(types.comma)) {
  8780. elt = null;
  8781. } else if (this.match(types.ellipsis)) {
  8782. const spreadNodeStartPos = this.state.start;
  8783. const spreadNodeStartLoc = this.state.startLoc;
  8784. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  8785. } else if (this.match(types.question)) {
  8786. this.expectPlugin("partialApplication");
  8787. if (!allowPlaceholder) {
  8788. this.raise(this.state.start, Errors.UnexpectedArgumentPlaceholder);
  8789. }
  8790. const node = this.startNode();
  8791. this.next();
  8792. elt = this.finishNode(node, "ArgumentPlaceholder");
  8793. } else {
  8794. elt = this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  8795. }
  8796. return elt;
  8797. }
  8798. parseIdentifier(liberal) {
  8799. const node = this.startNode();
  8800. const name = this.parseIdentifierName(node.start, liberal);
  8801. return this.createIdentifier(node, name);
  8802. }
  8803. createIdentifier(node, name) {
  8804. node.name = name;
  8805. node.loc.identifierName = name;
  8806. return this.finishNode(node, "Identifier");
  8807. }
  8808. parseIdentifierName(pos, liberal) {
  8809. let name;
  8810. if (this.match(types.name)) {
  8811. name = this.state.value;
  8812. } else if (this.state.type.keyword) {
  8813. name = this.state.type.keyword;
  8814. const context = this.state.context;
  8815. if ((name === "class" || name === "function") && context[context.length - 1].token === "function") {
  8816. context.pop();
  8817. }
  8818. } else {
  8819. throw this.unexpected();
  8820. }
  8821. if (liberal) {
  8822. this.state.type = types.name;
  8823. } else {
  8824. this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false);
  8825. }
  8826. this.next();
  8827. return name;
  8828. }
  8829. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  8830. if (this.prodParam.hasYield && word === "yield") {
  8831. this.raise(startLoc, Errors.YieldBindingIdentifier);
  8832. return;
  8833. }
  8834. if (word === "await") {
  8835. if (this.prodParam.hasAwait) {
  8836. this.raise(startLoc, Errors.AwaitBindingIdentifier);
  8837. return;
  8838. }
  8839. if (this.state.awaitPos === -1 && (this.state.maybeInAsyncArrowHead || this.isAwaitAllowed())) {
  8840. this.state.awaitPos = this.state.start;
  8841. }
  8842. }
  8843. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  8844. this.raise(startLoc, Errors.ArgumentsDisallowedInInitializer);
  8845. return;
  8846. }
  8847. if (checkKeywords && isKeyword(word)) {
  8848. this.raise(startLoc, Errors.UnexpectedKeyword, word);
  8849. return;
  8850. }
  8851. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  8852. if (reservedTest(word, this.inModule)) {
  8853. if (!this.prodParam.hasAwait && word === "await") {
  8854. this.raise(startLoc, Errors.AwaitNotInAsyncFunction);
  8855. } else {
  8856. this.raise(startLoc, Errors.UnexpectedReservedWord, word);
  8857. }
  8858. }
  8859. }
  8860. isAwaitAllowed() {
  8861. if (this.scope.inFunction) return this.prodParam.hasAwait;
  8862. if (this.options.allowAwaitOutsideFunction) return true;
  8863. if (this.hasPlugin("topLevelAwait")) {
  8864. return this.inModule && this.prodParam.hasAwait;
  8865. }
  8866. return false;
  8867. }
  8868. parseAwait() {
  8869. const node = this.startNode();
  8870. this.next();
  8871. if (this.state.inParameters) {
  8872. this.raise(node.start, Errors.AwaitExpressionFormalParameter);
  8873. } else if (this.state.awaitPos === -1) {
  8874. this.state.awaitPos = node.start;
  8875. }
  8876. if (this.eat(types.star)) {
  8877. this.raise(node.start, Errors.ObsoleteAwaitStar);
  8878. }
  8879. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  8880. 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)) {
  8881. this.ambiguousScriptDifferentAst = true;
  8882. } else {
  8883. this.sawUnambiguousESM = true;
  8884. }
  8885. }
  8886. if (!this.state.soloAwait) {
  8887. node.argument = this.parseMaybeUnary();
  8888. }
  8889. return this.finishNode(node, "AwaitExpression");
  8890. }
  8891. parseYield(noIn) {
  8892. const node = this.startNode();
  8893. if (this.state.inParameters) {
  8894. this.raise(node.start, Errors.YieldInParameter);
  8895. } else if (this.state.yieldPos === -1) {
  8896. this.state.yieldPos = node.start;
  8897. }
  8898. this.next();
  8899. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  8900. node.delegate = false;
  8901. node.argument = null;
  8902. } else {
  8903. node.delegate = this.eat(types.star);
  8904. node.argument = this.parseMaybeAssign(noIn);
  8905. }
  8906. return this.finishNode(node, "YieldExpression");
  8907. }
  8908. checkPipelineAtInfixOperator(left, leftStartPos) {
  8909. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  8910. if (left.type === "SequenceExpression") {
  8911. this.raise(leftStartPos, Errors.PipelineHeadSequenceExpression);
  8912. }
  8913. }
  8914. }
  8915. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  8916. const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
  8917. this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos);
  8918. return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc);
  8919. }
  8920. checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) {
  8921. if (this.match(types.arrow)) {
  8922. throw this.raise(this.state.start, Errors.PipelineBodyNoArrow);
  8923. } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") {
  8924. this.raise(startPos, Errors.PipelineBodySequenceExpression);
  8925. }
  8926. }
  8927. parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) {
  8928. const bodyNode = this.startNodeAt(startPos, startLoc);
  8929. switch (pipelineStyle) {
  8930. case "PipelineBareFunction":
  8931. bodyNode.callee = childExpression;
  8932. break;
  8933. case "PipelineBareConstructor":
  8934. bodyNode.callee = childExpression.callee;
  8935. break;
  8936. case "PipelineBareAwaitedFunction":
  8937. bodyNode.callee = childExpression.argument;
  8938. break;
  8939. case "PipelineTopicExpression":
  8940. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  8941. this.raise(startPos, Errors.PipelineTopicUnused);
  8942. }
  8943. bodyNode.expression = childExpression;
  8944. break;
  8945. default:
  8946. throw new Error(`Internal @babel/parser error: Unknown pipeline style (${pipelineStyle})`);
  8947. }
  8948. return this.finishNode(bodyNode, pipelineStyle);
  8949. }
  8950. checkSmartPipelineBodyStyle(expression) {
  8951. switch (expression.type) {
  8952. default:
  8953. return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression";
  8954. }
  8955. }
  8956. isSimpleReference(expression) {
  8957. switch (expression.type) {
  8958. case "MemberExpression":
  8959. return !expression.computed && this.isSimpleReference(expression.object);
  8960. case "Identifier":
  8961. return true;
  8962. default:
  8963. return false;
  8964. }
  8965. }
  8966. withTopicPermittingContext(callback) {
  8967. const outerContextTopicState = this.state.topicContext;
  8968. this.state.topicContext = {
  8969. maxNumOfResolvableTopics: 1,
  8970. maxTopicIndex: null
  8971. };
  8972. try {
  8973. return callback();
  8974. } finally {
  8975. this.state.topicContext = outerContextTopicState;
  8976. }
  8977. }
  8978. withTopicForbiddingContext(callback) {
  8979. const outerContextTopicState = this.state.topicContext;
  8980. this.state.topicContext = {
  8981. maxNumOfResolvableTopics: 0,
  8982. maxTopicIndex: null
  8983. };
  8984. try {
  8985. return callback();
  8986. } finally {
  8987. this.state.topicContext = outerContextTopicState;
  8988. }
  8989. }
  8990. withSoloAwaitPermittingContext(callback) {
  8991. const outerContextSoloAwaitState = this.state.soloAwait;
  8992. this.state.soloAwait = true;
  8993. try {
  8994. return callback();
  8995. } finally {
  8996. this.state.soloAwait = outerContextSoloAwaitState;
  8997. }
  8998. }
  8999. registerTopicReference() {
  9000. this.state.topicContext.maxTopicIndex = 0;
  9001. }
  9002. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  9003. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  9004. }
  9005. topicReferenceWasUsedInCurrentTopicContext() {
  9006. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  9007. }
  9008. parseFSharpPipelineBody(prec, noIn) {
  9009. const startPos = this.state.start;
  9010. const startLoc = this.state.startLoc;
  9011. this.state.potentialArrowAt = this.state.start;
  9012. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9013. this.state.inFSharpPipelineDirectBody = true;
  9014. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
  9015. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9016. return ret;
  9017. }
  9018. }
  9019. const loopLabel = {
  9020. kind: "loop"
  9021. },
  9022. switchLabel = {
  9023. kind: "switch"
  9024. };
  9025. const FUNC_NO_FLAGS = 0b000,
  9026. FUNC_STATEMENT = 0b001,
  9027. FUNC_HANGING_STATEMENT = 0b010,
  9028. FUNC_NULLABLE_ID = 0b100;
  9029. class StatementParser extends ExpressionParser {
  9030. parseTopLevel(file, program) {
  9031. program.sourceType = this.options.sourceType;
  9032. program.interpreter = this.parseInterpreterDirective();
  9033. this.parseBlockBody(program, true, true, types.eof);
  9034. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9035. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  9036. const [name] = _Array$from[_i];
  9037. const pos = this.scope.undefinedExports.get(name);
  9038. this.raise(pos, Errors.ModuleExportUndefined, name);
  9039. }
  9040. }
  9041. file.program = this.finishNode(program, "Program");
  9042. file.comments = this.state.comments;
  9043. if (this.options.tokens) file.tokens = this.tokens;
  9044. return this.finishNode(file, "File");
  9045. }
  9046. stmtToDirective(stmt) {
  9047. const expr = stmt.expression;
  9048. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9049. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9050. const raw = this.input.slice(expr.start, expr.end);
  9051. const val = directiveLiteral.value = raw.slice(1, -1);
  9052. this.addExtra(directiveLiteral, "raw", raw);
  9053. this.addExtra(directiveLiteral, "rawValue", val);
  9054. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9055. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9056. }
  9057. parseInterpreterDirective() {
  9058. if (!this.match(types.interpreterDirective)) {
  9059. return null;
  9060. }
  9061. const node = this.startNode();
  9062. node.value = this.state.value;
  9063. this.next();
  9064. return this.finishNode(node, "InterpreterDirective");
  9065. }
  9066. isLet(context) {
  9067. if (!this.isContextual("let")) {
  9068. return false;
  9069. }
  9070. const next = this.nextTokenStart();
  9071. const nextCh = this.input.charCodeAt(next);
  9072. if (nextCh === 91) return true;
  9073. if (context) return false;
  9074. if (nextCh === 123) return true;
  9075. if (isIdentifierStart(nextCh)) {
  9076. let pos = next + 1;
  9077. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9078. ++pos;
  9079. }
  9080. const ident = this.input.slice(next, pos);
  9081. if (!keywordRelationalOperator.test(ident)) return true;
  9082. }
  9083. return false;
  9084. }
  9085. parseStatement(context, topLevel) {
  9086. if (this.match(types.at)) {
  9087. this.parseDecorators(true);
  9088. }
  9089. return this.parseStatementContent(context, topLevel);
  9090. }
  9091. parseStatementContent(context, topLevel) {
  9092. let starttype = this.state.type;
  9093. const node = this.startNode();
  9094. let kind;
  9095. if (this.isLet(context)) {
  9096. starttype = types._var;
  9097. kind = "let";
  9098. }
  9099. switch (starttype) {
  9100. case types._break:
  9101. case types._continue:
  9102. return this.parseBreakContinueStatement(node, starttype.keyword);
  9103. case types._debugger:
  9104. return this.parseDebuggerStatement(node);
  9105. case types._do:
  9106. return this.parseDoStatement(node);
  9107. case types._for:
  9108. return this.parseForStatement(node);
  9109. case types._function:
  9110. if (this.lookaheadCharCode() === 46) break;
  9111. if (context) {
  9112. if (this.state.strict) {
  9113. this.raise(this.state.start, Errors.StrictFunction);
  9114. } else if (context !== "if" && context !== "label") {
  9115. this.raise(this.state.start, Errors.SloppyFunction);
  9116. }
  9117. }
  9118. return this.parseFunctionStatement(node, false, !context);
  9119. case types._class:
  9120. if (context) this.unexpected();
  9121. return this.parseClass(node, true);
  9122. case types._if:
  9123. return this.parseIfStatement(node);
  9124. case types._return:
  9125. return this.parseReturnStatement(node);
  9126. case types._switch:
  9127. return this.parseSwitchStatement(node);
  9128. case types._throw:
  9129. return this.parseThrowStatement(node);
  9130. case types._try:
  9131. return this.parseTryStatement(node);
  9132. case types._const:
  9133. case types._var:
  9134. kind = kind || this.state.value;
  9135. if (context && kind !== "var") {
  9136. this.raise(this.state.start, Errors.UnexpectedLexicalDeclaration);
  9137. }
  9138. return this.parseVarStatement(node, kind);
  9139. case types._while:
  9140. return this.parseWhileStatement(node);
  9141. case types._with:
  9142. return this.parseWithStatement(node);
  9143. case types.braceL:
  9144. return this.parseBlock();
  9145. case types.semi:
  9146. return this.parseEmptyStatement(node);
  9147. case types._export:
  9148. case types._import:
  9149. {
  9150. const nextTokenCharCode = this.lookaheadCharCode();
  9151. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  9152. break;
  9153. }
  9154. if (!this.options.allowImportExportEverywhere && !topLevel) {
  9155. this.raise(this.state.start, Errors.UnexpectedImportExport);
  9156. }
  9157. this.next();
  9158. let result;
  9159. if (starttype === types._import) {
  9160. result = this.parseImport(node);
  9161. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  9162. this.sawUnambiguousESM = true;
  9163. }
  9164. } else {
  9165. result = this.parseExport(node);
  9166. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  9167. this.sawUnambiguousESM = true;
  9168. }
  9169. }
  9170. this.assertModuleNodeAllowed(node);
  9171. return result;
  9172. }
  9173. default:
  9174. {
  9175. if (this.isAsyncFunction()) {
  9176. if (context) {
  9177. this.raise(this.state.start, Errors.AsyncFunctionInSingleStatementContext);
  9178. }
  9179. this.next();
  9180. return this.parseFunctionStatement(node, true, !context);
  9181. }
  9182. }
  9183. }
  9184. const maybeName = this.state.value;
  9185. const expr = this.parseExpression();
  9186. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  9187. return this.parseLabeledStatement(node, maybeName, expr, context);
  9188. } else {
  9189. return this.parseExpressionStatement(node, expr);
  9190. }
  9191. }
  9192. assertModuleNodeAllowed(node) {
  9193. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  9194. this.raiseWithData(node.start, {
  9195. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9196. }, Errors.ImportOutsideModule);
  9197. }
  9198. }
  9199. takeDecorators(node) {
  9200. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9201. if (decorators.length) {
  9202. node.decorators = decorators;
  9203. this.resetStartLocationFromNode(node, decorators[0]);
  9204. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  9205. }
  9206. }
  9207. canHaveLeadingDecorator() {
  9208. return this.match(types._class);
  9209. }
  9210. parseDecorators(allowExport) {
  9211. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9212. while (this.match(types.at)) {
  9213. const decorator = this.parseDecorator();
  9214. currentContextDecorators.push(decorator);
  9215. }
  9216. if (this.match(types._export)) {
  9217. if (!allowExport) {
  9218. this.unexpected();
  9219. }
  9220. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9221. this.raise(this.state.start, Errors.DecoratorExportClass);
  9222. }
  9223. } else if (!this.canHaveLeadingDecorator()) {
  9224. throw this.raise(this.state.start, Errors.UnexpectedLeadingDecorator);
  9225. }
  9226. }
  9227. parseDecorator() {
  9228. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  9229. const node = this.startNode();
  9230. this.next();
  9231. if (this.hasPlugin("decorators")) {
  9232. this.state.decoratorStack.push([]);
  9233. const startPos = this.state.start;
  9234. const startLoc = this.state.startLoc;
  9235. let expr;
  9236. if (this.eat(types.parenL)) {
  9237. expr = this.parseExpression();
  9238. this.expect(types.parenR);
  9239. } else {
  9240. expr = this.parseIdentifier(false);
  9241. while (this.eat(types.dot)) {
  9242. const node = this.startNodeAt(startPos, startLoc);
  9243. node.object = expr;
  9244. node.property = this.parseIdentifier(true);
  9245. node.computed = false;
  9246. expr = this.finishNode(node, "MemberExpression");
  9247. }
  9248. }
  9249. node.expression = this.parseMaybeDecoratorArguments(expr);
  9250. this.state.decoratorStack.pop();
  9251. } else {
  9252. node.expression = this.parseExprSubscripts();
  9253. }
  9254. return this.finishNode(node, "Decorator");
  9255. }
  9256. parseMaybeDecoratorArguments(expr) {
  9257. if (this.eat(types.parenL)) {
  9258. const node = this.startNodeAtNode(expr);
  9259. node.callee = expr;
  9260. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  9261. this.toReferencedList(node.arguments);
  9262. return this.finishNode(node, "CallExpression");
  9263. }
  9264. return expr;
  9265. }
  9266. parseBreakContinueStatement(node, keyword) {
  9267. const isBreak = keyword === "break";
  9268. this.next();
  9269. if (this.isLineTerminator()) {
  9270. node.label = null;
  9271. } else {
  9272. node.label = this.parseIdentifier();
  9273. this.semicolon();
  9274. }
  9275. this.verifyBreakContinue(node, keyword);
  9276. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  9277. }
  9278. verifyBreakContinue(node, keyword) {
  9279. const isBreak = keyword === "break";
  9280. let i;
  9281. for (i = 0; i < this.state.labels.length; ++i) {
  9282. const lab = this.state.labels[i];
  9283. if (node.label == null || lab.name === node.label.name) {
  9284. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  9285. if (node.label && isBreak) break;
  9286. }
  9287. }
  9288. if (i === this.state.labels.length) {
  9289. this.raise(node.start, Errors.IllegalBreakContinue, keyword);
  9290. }
  9291. }
  9292. parseDebuggerStatement(node) {
  9293. this.next();
  9294. this.semicolon();
  9295. return this.finishNode(node, "DebuggerStatement");
  9296. }
  9297. parseHeaderExpression() {
  9298. this.expect(types.parenL);
  9299. const val = this.parseExpression();
  9300. this.expect(types.parenR);
  9301. return val;
  9302. }
  9303. parseDoStatement(node) {
  9304. this.next();
  9305. this.state.labels.push(loopLabel);
  9306. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  9307. this.state.labels.pop();
  9308. this.expect(types._while);
  9309. node.test = this.parseHeaderExpression();
  9310. this.eat(types.semi);
  9311. return this.finishNode(node, "DoWhileStatement");
  9312. }
  9313. parseForStatement(node) {
  9314. this.next();
  9315. this.state.labels.push(loopLabel);
  9316. let awaitAt = -1;
  9317. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  9318. awaitAt = this.state.lastTokStart;
  9319. }
  9320. this.scope.enter(SCOPE_OTHER);
  9321. this.expect(types.parenL);
  9322. if (this.match(types.semi)) {
  9323. if (awaitAt > -1) {
  9324. this.unexpected(awaitAt);
  9325. }
  9326. return this.parseFor(node, null);
  9327. }
  9328. const isLet = this.isLet();
  9329. if (this.match(types._var) || this.match(types._const) || isLet) {
  9330. const init = this.startNode();
  9331. const kind = isLet ? "let" : this.state.value;
  9332. this.next();
  9333. this.parseVar(init, true, kind);
  9334. this.finishNode(init, "VariableDeclaration");
  9335. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  9336. return this.parseForIn(node, init, awaitAt);
  9337. }
  9338. if (awaitAt > -1) {
  9339. this.unexpected(awaitAt);
  9340. }
  9341. return this.parseFor(node, init);
  9342. }
  9343. const refExpressionErrors = new ExpressionErrors();
  9344. const init = this.parseExpression(true, refExpressionErrors);
  9345. if (this.match(types._in) || this.isContextual("of")) {
  9346. this.toAssignable(init);
  9347. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  9348. this.checkLVal(init, undefined, undefined, description);
  9349. return this.parseForIn(node, init, awaitAt);
  9350. } else {
  9351. this.checkExpressionErrors(refExpressionErrors, true);
  9352. }
  9353. if (awaitAt > -1) {
  9354. this.unexpected(awaitAt);
  9355. }
  9356. return this.parseFor(node, init);
  9357. }
  9358. parseFunctionStatement(node, isAsync, declarationPosition) {
  9359. this.next();
  9360. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  9361. }
  9362. parseIfStatement(node) {
  9363. this.next();
  9364. node.test = this.parseHeaderExpression();
  9365. node.consequent = this.parseStatement("if");
  9366. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  9367. return this.finishNode(node, "IfStatement");
  9368. }
  9369. parseReturnStatement(node) {
  9370. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  9371. this.raise(this.state.start, Errors.IllegalReturn);
  9372. }
  9373. this.next();
  9374. if (this.isLineTerminator()) {
  9375. node.argument = null;
  9376. } else {
  9377. node.argument = this.parseExpression();
  9378. this.semicolon();
  9379. }
  9380. return this.finishNode(node, "ReturnStatement");
  9381. }
  9382. parseSwitchStatement(node) {
  9383. this.next();
  9384. node.discriminant = this.parseHeaderExpression();
  9385. const cases = node.cases = [];
  9386. this.expect(types.braceL);
  9387. this.state.labels.push(switchLabel);
  9388. this.scope.enter(SCOPE_OTHER);
  9389. let cur;
  9390. for (let sawDefault; !this.match(types.braceR);) {
  9391. if (this.match(types._case) || this.match(types._default)) {
  9392. const isCase = this.match(types._case);
  9393. if (cur) this.finishNode(cur, "SwitchCase");
  9394. cases.push(cur = this.startNode());
  9395. cur.consequent = [];
  9396. this.next();
  9397. if (isCase) {
  9398. cur.test = this.parseExpression();
  9399. } else {
  9400. if (sawDefault) {
  9401. this.raise(this.state.lastTokStart, Errors.MultipleDefaultsInSwitch);
  9402. }
  9403. sawDefault = true;
  9404. cur.test = null;
  9405. }
  9406. this.expect(types.colon);
  9407. } else {
  9408. if (cur) {
  9409. cur.consequent.push(this.parseStatement(null));
  9410. } else {
  9411. this.unexpected();
  9412. }
  9413. }
  9414. }
  9415. this.scope.exit();
  9416. if (cur) this.finishNode(cur, "SwitchCase");
  9417. this.next();
  9418. this.state.labels.pop();
  9419. return this.finishNode(node, "SwitchStatement");
  9420. }
  9421. parseThrowStatement(node) {
  9422. this.next();
  9423. if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) {
  9424. this.raise(this.state.lastTokEnd, Errors.NewlineAfterThrow);
  9425. }
  9426. node.argument = this.parseExpression();
  9427. this.semicolon();
  9428. return this.finishNode(node, "ThrowStatement");
  9429. }
  9430. parseTryStatement(node) {
  9431. this.next();
  9432. node.block = this.parseBlock();
  9433. node.handler = null;
  9434. if (this.match(types._catch)) {
  9435. const clause = this.startNode();
  9436. this.next();
  9437. if (this.match(types.parenL)) {
  9438. this.expect(types.parenL);
  9439. clause.param = this.parseBindingAtom();
  9440. const simple = clause.param.type === "Identifier";
  9441. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9442. this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause");
  9443. this.expect(types.parenR);
  9444. } else {
  9445. clause.param = null;
  9446. this.scope.enter(SCOPE_OTHER);
  9447. }
  9448. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9449. this.scope.exit();
  9450. node.handler = this.finishNode(clause, "CatchClause");
  9451. }
  9452. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9453. if (!node.handler && !node.finalizer) {
  9454. this.raise(node.start, Errors.NoCatchOrFinally);
  9455. }
  9456. return this.finishNode(node, "TryStatement");
  9457. }
  9458. parseVarStatement(node, kind) {
  9459. this.next();
  9460. this.parseVar(node, false, kind);
  9461. this.semicolon();
  9462. return this.finishNode(node, "VariableDeclaration");
  9463. }
  9464. parseWhileStatement(node) {
  9465. this.next();
  9466. node.test = this.parseHeaderExpression();
  9467. this.state.labels.push(loopLabel);
  9468. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9469. this.state.labels.pop();
  9470. return this.finishNode(node, "WhileStatement");
  9471. }
  9472. parseWithStatement(node) {
  9473. if (this.state.strict) {
  9474. this.raise(this.state.start, Errors.StrictWith);
  9475. }
  9476. this.next();
  9477. node.object = this.parseHeaderExpression();
  9478. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9479. return this.finishNode(node, "WithStatement");
  9480. }
  9481. parseEmptyStatement(node) {
  9482. this.next();
  9483. return this.finishNode(node, "EmptyStatement");
  9484. }
  9485. parseLabeledStatement(node, maybeName, expr, context) {
  9486. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9487. const label = _this$state$labels[_i2];
  9488. if (label.name === maybeName) {
  9489. this.raise(expr.start, Errors.LabelRedeclaration, maybeName);
  9490. }
  9491. }
  9492. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9493. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9494. const label = this.state.labels[i];
  9495. if (label.statementStart === node.start) {
  9496. label.statementStart = this.state.start;
  9497. label.kind = kind;
  9498. } else {
  9499. break;
  9500. }
  9501. }
  9502. this.state.labels.push({
  9503. name: maybeName,
  9504. kind: kind,
  9505. statementStart: this.state.start
  9506. });
  9507. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9508. this.state.labels.pop();
  9509. node.label = expr;
  9510. return this.finishNode(node, "LabeledStatement");
  9511. }
  9512. parseExpressionStatement(node, expr) {
  9513. node.expression = expr;
  9514. this.semicolon();
  9515. return this.finishNode(node, "ExpressionStatement");
  9516. }
  9517. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  9518. const node = this.startNode();
  9519. this.expect(types.braceL);
  9520. if (createNewLexicalScope) {
  9521. this.scope.enter(SCOPE_OTHER);
  9522. }
  9523. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  9524. if (createNewLexicalScope) {
  9525. this.scope.exit();
  9526. }
  9527. return this.finishNode(node, "BlockStatement");
  9528. }
  9529. isValidDirective(stmt) {
  9530. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9531. }
  9532. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  9533. const body = node.body = [];
  9534. const directives = node.directives = [];
  9535. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  9536. }
  9537. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  9538. const octalPositions = [];
  9539. const oldStrict = this.state.strict;
  9540. let hasStrictModeDirective = false;
  9541. let parsedNonDirective = false;
  9542. while (!this.match(end)) {
  9543. if (!parsedNonDirective && this.state.octalPositions.length) {
  9544. octalPositions.push(...this.state.octalPositions);
  9545. }
  9546. const stmt = this.parseStatement(null, topLevel);
  9547. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  9548. const directive = this.stmtToDirective(stmt);
  9549. directives.push(directive);
  9550. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  9551. hasStrictModeDirective = true;
  9552. this.setStrict(true);
  9553. }
  9554. continue;
  9555. }
  9556. parsedNonDirective = true;
  9557. body.push(stmt);
  9558. }
  9559. if (this.state.strict && octalPositions.length) {
  9560. for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
  9561. const pos = octalPositions[_i3];
  9562. this.raise(pos, Errors.StrictOctalLiteral);
  9563. }
  9564. }
  9565. if (afterBlockParse) {
  9566. afterBlockParse.call(this, hasStrictModeDirective);
  9567. }
  9568. if (!oldStrict) {
  9569. this.setStrict(false);
  9570. }
  9571. this.next();
  9572. }
  9573. parseFor(node, init) {
  9574. node.init = init;
  9575. this.expect(types.semi);
  9576. node.test = this.match(types.semi) ? null : this.parseExpression();
  9577. this.expect(types.semi);
  9578. node.update = this.match(types.parenR) ? null : this.parseExpression();
  9579. this.expect(types.parenR);
  9580. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9581. this.scope.exit();
  9582. this.state.labels.pop();
  9583. return this.finishNode(node, "ForStatement");
  9584. }
  9585. parseForIn(node, init, awaitAt) {
  9586. const isForIn = this.match(types._in);
  9587. this.next();
  9588. if (isForIn) {
  9589. if (awaitAt > -1) this.unexpected(awaitAt);
  9590. } else {
  9591. node.await = awaitAt > -1;
  9592. }
  9593. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  9594. this.raise(init.start, Errors.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  9595. } else if (init.type === "AssignmentPattern") {
  9596. this.raise(init.start, Errors.InvalidLhs, "for-loop");
  9597. }
  9598. node.left = init;
  9599. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  9600. this.expect(types.parenR);
  9601. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9602. this.scope.exit();
  9603. this.state.labels.pop();
  9604. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  9605. }
  9606. parseVar(node, isFor, kind) {
  9607. const declarations = node.declarations = [];
  9608. const isTypescript = this.hasPlugin("typescript");
  9609. node.kind = kind;
  9610. for (;;) {
  9611. const decl = this.startNode();
  9612. this.parseVarId(decl, kind);
  9613. if (this.eat(types.eq)) {
  9614. decl.init = this.parseMaybeAssign(isFor);
  9615. } else {
  9616. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  9617. if (!isTypescript) {
  9618. this.unexpected();
  9619. }
  9620. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  9621. this.raise(this.state.lastTokEnd, Errors.DeclarationMissingInitializer, "Complex binding patterns");
  9622. }
  9623. decl.init = null;
  9624. }
  9625. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  9626. if (!this.eat(types.comma)) break;
  9627. }
  9628. return node;
  9629. }
  9630. parseVarId(decl, kind) {
  9631. decl.id = this.parseBindingAtom();
  9632. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var");
  9633. }
  9634. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  9635. const isStatement = statement & FUNC_STATEMENT;
  9636. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  9637. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  9638. this.initFunction(node, isAsync);
  9639. if (this.match(types.star) && isHangingStatement) {
  9640. this.raise(this.state.start, Errors.GeneratorInSingleStatementContext);
  9641. }
  9642. node.generator = this.eat(types.star);
  9643. if (isStatement) {
  9644. node.id = this.parseFunctionId(requireId);
  9645. }
  9646. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9647. const oldYieldPos = this.state.yieldPos;
  9648. const oldAwaitPos = this.state.awaitPos;
  9649. this.state.maybeInArrowParameters = false;
  9650. this.state.yieldPos = -1;
  9651. this.state.awaitPos = -1;
  9652. this.scope.enter(SCOPE_FUNCTION);
  9653. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9654. if (!isStatement) {
  9655. node.id = this.parseFunctionId();
  9656. }
  9657. this.parseFunctionParams(node);
  9658. this.withTopicForbiddingContext(() => {
  9659. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  9660. });
  9661. this.prodParam.exit();
  9662. this.scope.exit();
  9663. if (isStatement && !isHangingStatement) {
  9664. this.registerFunctionStatementId(node);
  9665. }
  9666. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9667. this.state.yieldPos = oldYieldPos;
  9668. this.state.awaitPos = oldAwaitPos;
  9669. return node;
  9670. }
  9671. parseFunctionId(requireId) {
  9672. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  9673. }
  9674. parseFunctionParams(node, allowModifiers) {
  9675. const oldInParameters = this.state.inParameters;
  9676. this.state.inParameters = true;
  9677. this.expect(types.parenL);
  9678. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  9679. this.state.inParameters = oldInParameters;
  9680. this.checkYieldAwaitInDefaultParams();
  9681. }
  9682. registerFunctionStatementId(node) {
  9683. if (!node.id) return;
  9684. 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);
  9685. }
  9686. parseClass(node, isStatement, optionalId) {
  9687. this.next();
  9688. this.takeDecorators(node);
  9689. const oldStrict = this.state.strict;
  9690. this.state.strict = true;
  9691. this.parseClassId(node, isStatement, optionalId);
  9692. this.parseClassSuper(node);
  9693. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  9694. this.state.strict = oldStrict;
  9695. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  9696. }
  9697. isClassProperty() {
  9698. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  9699. }
  9700. isClassMethod() {
  9701. return this.match(types.parenL);
  9702. }
  9703. isNonstaticConstructor(method) {
  9704. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  9705. }
  9706. parseClassBody(constructorAllowsSuper, oldStrict) {
  9707. this.classScope.enter();
  9708. const state = {
  9709. hadConstructor: false
  9710. };
  9711. let decorators = [];
  9712. const classBody = this.startNode();
  9713. classBody.body = [];
  9714. this.expect(types.braceL);
  9715. this.withTopicForbiddingContext(() => {
  9716. while (!this.match(types.braceR)) {
  9717. if (this.eat(types.semi)) {
  9718. if (decorators.length > 0) {
  9719. throw this.raise(this.state.lastTokEnd, Errors.DecoratorSemicolon);
  9720. }
  9721. continue;
  9722. }
  9723. if (this.match(types.at)) {
  9724. decorators.push(this.parseDecorator());
  9725. continue;
  9726. }
  9727. const member = this.startNode();
  9728. if (decorators.length) {
  9729. member.decorators = decorators;
  9730. this.resetStartLocationFromNode(member, decorators[0]);
  9731. decorators = [];
  9732. }
  9733. this.parseClassMember(classBody, member, state, constructorAllowsSuper);
  9734. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  9735. this.raise(member.start, Errors.DecoratorConstructor);
  9736. }
  9737. }
  9738. });
  9739. if (!oldStrict) {
  9740. this.state.strict = false;
  9741. }
  9742. this.next();
  9743. if (decorators.length) {
  9744. throw this.raise(this.state.start, Errors.TrailingDecorator);
  9745. }
  9746. this.classScope.exit();
  9747. return this.finishNode(classBody, "ClassBody");
  9748. }
  9749. parseClassMemberFromModifier(classBody, member) {
  9750. const containsEsc = this.state.containsEsc;
  9751. const key = this.parseIdentifier(true);
  9752. if (this.isClassMethod()) {
  9753. const method = member;
  9754. method.kind = "method";
  9755. method.computed = false;
  9756. method.key = key;
  9757. method.static = false;
  9758. this.pushClassMethod(classBody, method, false, false, false, false);
  9759. return true;
  9760. } else if (this.isClassProperty()) {
  9761. const prop = member;
  9762. prop.computed = false;
  9763. prop.key = key;
  9764. prop.static = false;
  9765. classBody.body.push(this.parseClassProperty(prop));
  9766. return true;
  9767. } else if (containsEsc) {
  9768. throw this.unexpected();
  9769. }
  9770. return false;
  9771. }
  9772. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  9773. const isStatic = this.isContextual("static");
  9774. if (isStatic && this.parseClassMemberFromModifier(classBody, member)) {
  9775. return;
  9776. }
  9777. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  9778. }
  9779. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  9780. const publicMethod = member;
  9781. const privateMethod = member;
  9782. const publicProp = member;
  9783. const privateProp = member;
  9784. const method = publicMethod;
  9785. const publicMember = publicMethod;
  9786. member.static = isStatic;
  9787. if (this.eat(types.star)) {
  9788. method.kind = "method";
  9789. this.parseClassPropertyName(method);
  9790. if (method.key.type === "PrivateName") {
  9791. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  9792. return;
  9793. }
  9794. if (this.isNonstaticConstructor(publicMethod)) {
  9795. this.raise(publicMethod.key.start, Errors.ConstructorIsGenerator);
  9796. }
  9797. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  9798. return;
  9799. }
  9800. const containsEsc = this.state.containsEsc;
  9801. const key = this.parseClassPropertyName(member);
  9802. const isPrivate = key.type === "PrivateName";
  9803. const isSimple = key.type === "Identifier";
  9804. const maybeQuestionTokenStart = this.state.start;
  9805. this.parsePostMemberNameModifiers(publicMember);
  9806. if (this.isClassMethod()) {
  9807. method.kind = "method";
  9808. if (isPrivate) {
  9809. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9810. return;
  9811. }
  9812. const isConstructor = this.isNonstaticConstructor(publicMethod);
  9813. let allowsDirectSuper = false;
  9814. if (isConstructor) {
  9815. publicMethod.kind = "constructor";
  9816. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  9817. this.raise(key.start, Errors.DuplicateConstructor);
  9818. }
  9819. state.hadConstructor = true;
  9820. allowsDirectSuper = constructorAllowsSuper;
  9821. }
  9822. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  9823. } else if (this.isClassProperty()) {
  9824. if (isPrivate) {
  9825. this.pushClassPrivateProperty(classBody, privateProp);
  9826. } else {
  9827. this.pushClassProperty(classBody, publicProp);
  9828. }
  9829. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  9830. const isGenerator = this.eat(types.star);
  9831. if (publicMember.optional) {
  9832. this.unexpected(maybeQuestionTokenStart);
  9833. }
  9834. method.kind = "method";
  9835. this.parseClassPropertyName(method);
  9836. this.parsePostMemberNameModifiers(publicMember);
  9837. if (method.key.type === "PrivateName") {
  9838. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  9839. } else {
  9840. if (this.isNonstaticConstructor(publicMethod)) {
  9841. this.raise(publicMethod.key.start, Errors.ConstructorIsAsync);
  9842. }
  9843. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  9844. }
  9845. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  9846. method.kind = key.name;
  9847. this.parseClassPropertyName(publicMethod);
  9848. if (method.key.type === "PrivateName") {
  9849. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9850. } else {
  9851. if (this.isNonstaticConstructor(publicMethod)) {
  9852. this.raise(publicMethod.key.start, Errors.ConstructorIsAccessor);
  9853. }
  9854. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  9855. }
  9856. this.checkGetterSetterParams(publicMethod);
  9857. } else if (this.isLineTerminator()) {
  9858. if (isPrivate) {
  9859. this.pushClassPrivateProperty(classBody, privateProp);
  9860. } else {
  9861. this.pushClassProperty(classBody, publicProp);
  9862. }
  9863. } else {
  9864. this.unexpected();
  9865. }
  9866. }
  9867. parseClassPropertyName(member) {
  9868. const key = this.parsePropertyName(member, true);
  9869. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  9870. this.raise(key.start, Errors.StaticPrototype);
  9871. }
  9872. if (key.type === "PrivateName" && key.id.name === "constructor") {
  9873. this.raise(key.start, Errors.ConstructorClassPrivateField);
  9874. }
  9875. return key;
  9876. }
  9877. pushClassProperty(classBody, prop) {
  9878. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  9879. this.raise(prop.key.start, Errors.ConstructorClassField);
  9880. }
  9881. classBody.body.push(this.parseClassProperty(prop));
  9882. }
  9883. pushClassPrivateProperty(classBody, prop) {
  9884. this.expectPlugin("classPrivateProperties", prop.key.start);
  9885. const node = this.parseClassPrivateProperty(prop);
  9886. classBody.body.push(node);
  9887. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  9888. }
  9889. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9890. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  9891. }
  9892. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9893. this.expectPlugin("classPrivateMethods", method.key.start);
  9894. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  9895. classBody.body.push(node);
  9896. 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;
  9897. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  9898. }
  9899. parsePostMemberNameModifiers(methodOrProp) {}
  9900. parseAccessModifier() {
  9901. return undefined;
  9902. }
  9903. parseClassPrivateProperty(node) {
  9904. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9905. this.prodParam.enter(PARAM);
  9906. node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null;
  9907. this.semicolon();
  9908. this.prodParam.exit();
  9909. this.scope.exit();
  9910. return this.finishNode(node, "ClassPrivateProperty");
  9911. }
  9912. parseClassProperty(node) {
  9913. if (!node.typeAnnotation) {
  9914. this.expectPlugin("classProperties");
  9915. }
  9916. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9917. this.prodParam.enter(PARAM);
  9918. if (this.match(types.eq)) {
  9919. this.expectPlugin("classProperties");
  9920. this.next();
  9921. node.value = this.parseMaybeAssign();
  9922. } else {
  9923. node.value = null;
  9924. }
  9925. this.semicolon();
  9926. this.prodParam.exit();
  9927. this.scope.exit();
  9928. return this.finishNode(node, "ClassProperty");
  9929. }
  9930. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  9931. if (this.match(types.name)) {
  9932. node.id = this.parseIdentifier();
  9933. if (isStatement) {
  9934. this.checkLVal(node.id, bindingType, undefined, "class name");
  9935. }
  9936. } else {
  9937. if (optionalId || !isStatement) {
  9938. node.id = null;
  9939. } else {
  9940. this.unexpected(null, Errors.MissingClassName);
  9941. }
  9942. }
  9943. }
  9944. parseClassSuper(node) {
  9945. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  9946. }
  9947. parseExport(node) {
  9948. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  9949. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  9950. const hasStar = parseAfterDefault && this.eatExportStar(node);
  9951. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  9952. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  9953. const isFromRequired = hasDefault || hasStar;
  9954. if (hasStar && !hasNamespace) {
  9955. if (hasDefault) this.unexpected();
  9956. this.parseExportFrom(node, true);
  9957. return this.finishNode(node, "ExportAllDeclaration");
  9958. }
  9959. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  9960. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  9961. throw this.unexpected(null, types.braceL);
  9962. }
  9963. let hasDeclaration;
  9964. if (isFromRequired || hasSpecifiers) {
  9965. hasDeclaration = false;
  9966. this.parseExportFrom(node, isFromRequired);
  9967. } else {
  9968. hasDeclaration = this.maybeParseExportDeclaration(node);
  9969. }
  9970. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  9971. this.checkExport(node, true, false, !!node.source);
  9972. return this.finishNode(node, "ExportNamedDeclaration");
  9973. }
  9974. if (this.eat(types._default)) {
  9975. node.declaration = this.parseExportDefaultExpression();
  9976. this.checkExport(node, true, true);
  9977. return this.finishNode(node, "ExportDefaultDeclaration");
  9978. }
  9979. throw this.unexpected(null, types.braceL);
  9980. }
  9981. eatExportStar(node) {
  9982. return this.eat(types.star);
  9983. }
  9984. maybeParseExportDefaultSpecifier(node) {
  9985. if (this.isExportDefaultSpecifier()) {
  9986. this.expectPlugin("exportDefaultFrom");
  9987. const specifier = this.startNode();
  9988. specifier.exported = this.parseIdentifier(true);
  9989. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9990. return true;
  9991. }
  9992. return false;
  9993. }
  9994. maybeParseExportNamespaceSpecifier(node) {
  9995. if (this.isContextual("as")) {
  9996. if (!node.specifiers) node.specifiers = [];
  9997. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  9998. this.next();
  9999. specifier.exported = this.parseIdentifier(true);
  10000. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  10001. return true;
  10002. }
  10003. return false;
  10004. }
  10005. maybeParseExportNamedSpecifiers(node) {
  10006. if (this.match(types.braceL)) {
  10007. if (!node.specifiers) node.specifiers = [];
  10008. node.specifiers.push(...this.parseExportSpecifiers());
  10009. node.source = null;
  10010. node.declaration = null;
  10011. return true;
  10012. }
  10013. return false;
  10014. }
  10015. maybeParseExportDeclaration(node) {
  10016. if (this.shouldParseExportDeclaration()) {
  10017. if (this.isContextual("async")) {
  10018. const next = this.nextTokenStart();
  10019. if (!this.isUnparsedContextual(next, "function")) {
  10020. this.unexpected(next, types._function);
  10021. }
  10022. }
  10023. node.specifiers = [];
  10024. node.source = null;
  10025. node.declaration = this.parseExportDeclaration(node);
  10026. return true;
  10027. }
  10028. return false;
  10029. }
  10030. isAsyncFunction() {
  10031. if (!this.isContextual("async")) return false;
  10032. const next = this.nextTokenStart();
  10033. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10034. }
  10035. parseExportDefaultExpression() {
  10036. const expr = this.startNode();
  10037. const isAsync = this.isAsyncFunction();
  10038. if (this.match(types._function) || isAsync) {
  10039. this.next();
  10040. if (isAsync) {
  10041. this.next();
  10042. }
  10043. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10044. } else if (this.match(types._class)) {
  10045. return this.parseClass(expr, true, true);
  10046. } else if (this.match(types.at)) {
  10047. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10048. this.raise(this.state.start, Errors.DecoratorBeforeExport);
  10049. }
  10050. this.parseDecorators(false);
  10051. return this.parseClass(expr, true, true);
  10052. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10053. throw this.raise(this.state.start, Errors.UnsupportedDefaultExport);
  10054. } else {
  10055. const res = this.parseMaybeAssign();
  10056. this.semicolon();
  10057. return res;
  10058. }
  10059. }
  10060. parseExportDeclaration(node) {
  10061. return this.parseStatement(null);
  10062. }
  10063. isExportDefaultSpecifier() {
  10064. if (this.match(types.name)) {
  10065. const value = this.state.value;
  10066. if (value === "async" || value === "let") {
  10067. return false;
  10068. }
  10069. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  10070. const l = this.lookahead();
  10071. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  10072. this.expectOnePlugin(["flow", "typescript"]);
  10073. return false;
  10074. }
  10075. }
  10076. } else if (!this.match(types._default)) {
  10077. return false;
  10078. }
  10079. const next = this.nextTokenStart();
  10080. return this.input.charCodeAt(next) === 44 || this.isUnparsedContextual(next, "from");
  10081. }
  10082. parseExportFrom(node, expect) {
  10083. if (this.eatContextual("from")) {
  10084. node.source = this.parseImportSource();
  10085. this.checkExport(node);
  10086. } else {
  10087. if (expect) {
  10088. this.unexpected();
  10089. } else {
  10090. node.source = null;
  10091. }
  10092. }
  10093. this.semicolon();
  10094. }
  10095. shouldParseExportDeclaration() {
  10096. if (this.match(types.at)) {
  10097. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  10098. if (this.hasPlugin("decorators")) {
  10099. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10100. this.unexpected(this.state.start, Errors.DecoratorBeforeExport);
  10101. } else {
  10102. return true;
  10103. }
  10104. }
  10105. }
  10106. 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();
  10107. }
  10108. checkExport(node, checkNames, isDefault, isFrom) {
  10109. if (checkNames) {
  10110. if (isDefault) {
  10111. this.checkDuplicateExports(node, "default");
  10112. } else if (node.specifiers && node.specifiers.length) {
  10113. for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
  10114. const specifier = _node$specifiers[_i4];
  10115. this.checkDuplicateExports(specifier, specifier.exported.name);
  10116. if (!isFrom && specifier.local) {
  10117. this.checkReservedWord(specifier.local.name, specifier.local.start, true, false);
  10118. this.scope.checkLocalExport(specifier.local);
  10119. }
  10120. }
  10121. } else if (node.declaration) {
  10122. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  10123. const id = node.declaration.id;
  10124. if (!id) throw new Error("Assertion failure");
  10125. this.checkDuplicateExports(node, id.name);
  10126. } else if (node.declaration.type === "VariableDeclaration") {
  10127. for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
  10128. const declaration = _node$declaration$dec[_i5];
  10129. this.checkDeclaration(declaration.id);
  10130. }
  10131. }
  10132. }
  10133. }
  10134. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10135. if (currentContextDecorators.length) {
  10136. const isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
  10137. if (!node.declaration || !isClass) {
  10138. throw this.raise(node.start, Errors.UnsupportedDecoratorExport);
  10139. }
  10140. this.takeDecorators(node.declaration);
  10141. }
  10142. }
  10143. checkDeclaration(node) {
  10144. if (node.type === "Identifier") {
  10145. this.checkDuplicateExports(node, node.name);
  10146. } else if (node.type === "ObjectPattern") {
  10147. for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
  10148. const prop = _node$properties[_i6];
  10149. this.checkDeclaration(prop);
  10150. }
  10151. } else if (node.type === "ArrayPattern") {
  10152. for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
  10153. const elem = _node$elements[_i7];
  10154. if (elem) {
  10155. this.checkDeclaration(elem);
  10156. }
  10157. }
  10158. } else if (node.type === "ObjectProperty") {
  10159. this.checkDeclaration(node.value);
  10160. } else if (node.type === "RestElement") {
  10161. this.checkDeclaration(node.argument);
  10162. } else if (node.type === "AssignmentPattern") {
  10163. this.checkDeclaration(node.left);
  10164. }
  10165. }
  10166. checkDuplicateExports(node, name) {
  10167. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  10168. this.raise(node.start, name === "default" ? Errors.DuplicateDefaultExport : Errors.DuplicateExport, name);
  10169. }
  10170. this.state.exportedIdentifiers.push(name);
  10171. }
  10172. parseExportSpecifiers() {
  10173. const nodes = [];
  10174. let first = true;
  10175. this.expect(types.braceL);
  10176. while (!this.eat(types.braceR)) {
  10177. if (first) {
  10178. first = false;
  10179. } else {
  10180. this.expect(types.comma);
  10181. if (this.eat(types.braceR)) break;
  10182. }
  10183. const node = this.startNode();
  10184. node.local = this.parseIdentifier(true);
  10185. node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
  10186. nodes.push(this.finishNode(node, "ExportSpecifier"));
  10187. }
  10188. return nodes;
  10189. }
  10190. parseImport(node) {
  10191. node.specifiers = [];
  10192. if (!this.match(types.string)) {
  10193. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  10194. const parseNext = !hasDefault || this.eat(types.comma);
  10195. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  10196. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  10197. this.expectContextual("from");
  10198. }
  10199. node.source = this.parseImportSource();
  10200. this.semicolon();
  10201. return this.finishNode(node, "ImportDeclaration");
  10202. }
  10203. parseImportSource() {
  10204. if (!this.match(types.string)) this.unexpected();
  10205. return this.parseExprAtom();
  10206. }
  10207. shouldParseDefaultImport(node) {
  10208. return this.match(types.name);
  10209. }
  10210. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  10211. specifier.local = this.parseIdentifier();
  10212. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  10213. node.specifiers.push(this.finishNode(specifier, type));
  10214. }
  10215. maybeParseDefaultImportSpecifier(node) {
  10216. if (this.shouldParseDefaultImport(node)) {
  10217. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  10218. return true;
  10219. }
  10220. return false;
  10221. }
  10222. maybeParseStarImportSpecifier(node) {
  10223. if (this.match(types.star)) {
  10224. const specifier = this.startNode();
  10225. this.next();
  10226. this.expectContextual("as");
  10227. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  10228. return true;
  10229. }
  10230. return false;
  10231. }
  10232. parseNamedImportSpecifiers(node) {
  10233. let first = true;
  10234. this.expect(types.braceL);
  10235. while (!this.eat(types.braceR)) {
  10236. if (first) {
  10237. first = false;
  10238. } else {
  10239. if (this.eat(types.colon)) {
  10240. throw this.raise(this.state.start, Errors.DestructureNamedImport);
  10241. }
  10242. this.expect(types.comma);
  10243. if (this.eat(types.braceR)) break;
  10244. }
  10245. this.parseImportSpecifier(node);
  10246. }
  10247. }
  10248. parseImportSpecifier(node) {
  10249. const specifier = this.startNode();
  10250. specifier.imported = this.parseIdentifier(true);
  10251. if (this.eatContextual("as")) {
  10252. specifier.local = this.parseIdentifier();
  10253. } else {
  10254. this.checkReservedWord(specifier.imported.name, specifier.start, true, true);
  10255. specifier.local = specifier.imported.__clone();
  10256. }
  10257. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  10258. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  10259. }
  10260. }
  10261. class ClassScope {
  10262. constructor() {
  10263. this.privateNames = new Set();
  10264. this.loneAccessors = new Map();
  10265. this.undefinedPrivateNames = new Map();
  10266. }
  10267. }
  10268. class ClassScopeHandler {
  10269. constructor(raise) {
  10270. this.stack = [];
  10271. this.undefinedPrivateNames = new Map();
  10272. this.raise = raise;
  10273. }
  10274. current() {
  10275. return this.stack[this.stack.length - 1];
  10276. }
  10277. enter() {
  10278. this.stack.push(new ClassScope());
  10279. }
  10280. exit() {
  10281. const oldClassScope = this.stack.pop();
  10282. const current = this.current();
  10283. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  10284. const [name, pos] = _Array$from[_i];
  10285. if (current) {
  10286. if (!current.undefinedPrivateNames.has(name)) {
  10287. current.undefinedPrivateNames.set(name, pos);
  10288. }
  10289. } else {
  10290. this.raise(pos, Errors.InvalidPrivateFieldResolution, name);
  10291. }
  10292. }
  10293. }
  10294. declarePrivateName(name, elementType, pos) {
  10295. const classScope = this.current();
  10296. let redefined = classScope.privateNames.has(name);
  10297. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  10298. const accessor = redefined && classScope.loneAccessors.get(name);
  10299. if (accessor) {
  10300. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  10301. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  10302. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  10303. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  10304. redefined = oldKind === newKind || oldStatic !== newStatic;
  10305. if (!redefined) classScope.loneAccessors.delete(name);
  10306. } else if (!redefined) {
  10307. classScope.loneAccessors.set(name, elementType);
  10308. }
  10309. }
  10310. if (redefined) {
  10311. this.raise(pos, Errors.PrivateNameRedeclaration, name);
  10312. }
  10313. classScope.privateNames.add(name);
  10314. classScope.undefinedPrivateNames.delete(name);
  10315. }
  10316. usePrivateName(name, pos) {
  10317. let classScope;
  10318. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  10319. classScope = _this$stack[_i2];
  10320. if (classScope.privateNames.has(name)) return;
  10321. }
  10322. if (classScope) {
  10323. classScope.undefinedPrivateNames.set(name, pos);
  10324. } else {
  10325. this.raise(pos, Errors.InvalidPrivateFieldResolution, name);
  10326. }
  10327. }
  10328. }
  10329. class Parser extends StatementParser {
  10330. constructor(options, input) {
  10331. options = getOptions(options);
  10332. super(options, input);
  10333. const ScopeHandler = this.getScopeHandler();
  10334. this.options = options;
  10335. this.inModule = this.options.sourceType === "module";
  10336. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  10337. this.prodParam = new ProductionParameterHandler();
  10338. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  10339. this.plugins = pluginsMap(this.options.plugins);
  10340. this.filename = options.sourceFilename;
  10341. }
  10342. getScopeHandler() {
  10343. return ScopeHandler;
  10344. }
  10345. parse() {
  10346. let paramFlags = PARAM;
  10347. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  10348. paramFlags |= PARAM_AWAIT;
  10349. }
  10350. this.scope.enter(SCOPE_PROGRAM);
  10351. this.prodParam.enter(paramFlags);
  10352. const file = this.startNode();
  10353. const program = this.startNode();
  10354. this.nextToken();
  10355. file.errors = null;
  10356. this.parseTopLevel(file, program);
  10357. file.errors = this.state.errors;
  10358. return file;
  10359. }
  10360. }
  10361. function pluginsMap(plugins) {
  10362. const pluginMap = new Map();
  10363. for (let _i = 0; _i < plugins.length; _i++) {
  10364. const plugin = plugins[_i];
  10365. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  10366. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  10367. }
  10368. return pluginMap;
  10369. }
  10370. function parse(input, options) {
  10371. if (options && options.sourceType === "unambiguous") {
  10372. options = Object.assign({}, options);
  10373. try {
  10374. options.sourceType = "module";
  10375. const parser = getParser(options, input);
  10376. const ast = parser.parse();
  10377. if (parser.sawUnambiguousESM) {
  10378. return ast;
  10379. }
  10380. if (parser.ambiguousScriptDifferentAst) {
  10381. try {
  10382. options.sourceType = "script";
  10383. return getParser(options, input).parse();
  10384. } catch (_unused) {}
  10385. } else {
  10386. ast.program.sourceType = "script";
  10387. }
  10388. return ast;
  10389. } catch (moduleError) {
  10390. try {
  10391. options.sourceType = "script";
  10392. return getParser(options, input).parse();
  10393. } catch (_unused2) {}
  10394. throw moduleError;
  10395. }
  10396. } else {
  10397. return getParser(options, input).parse();
  10398. }
  10399. }
  10400. function parseExpression(input, options) {
  10401. const parser = getParser(options, input);
  10402. if (parser.options.strictMode) {
  10403. parser.state.strict = true;
  10404. }
  10405. return parser.getExpression();
  10406. }
  10407. function getParser(options, input) {
  10408. let cls = Parser;
  10409. if (options && options.plugins) {
  10410. validatePlugins(options.plugins);
  10411. cls = getParserClass(options.plugins);
  10412. }
  10413. return new cls(options, input);
  10414. }
  10415. const parserClassCache = {};
  10416. function getParserClass(pluginsFromOptions) {
  10417. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  10418. const key = pluginList.join("/");
  10419. let cls = parserClassCache[key];
  10420. if (!cls) {
  10421. cls = Parser;
  10422. for (let _i = 0; _i < pluginList.length; _i++) {
  10423. const plugin = pluginList[_i];
  10424. cls = mixinPlugins[plugin](cls);
  10425. }
  10426. parserClassCache[key] = cls;
  10427. }
  10428. return cls;
  10429. }
  10430. exports.parse = parse;
  10431. exports.parseExpression = parseExpression;
  10432. exports.tokTypes = types;
  10433. //# sourceMappingURL=index.js.map