index.js 474 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function _objectWithoutPropertiesLoose(source, excluded) {
  4. if (source == null) return {};
  5. var target = {};
  6. var sourceKeys = Object.keys(source);
  7. var key, i;
  8. for (i = 0; i < sourceKeys.length; i++) {
  9. key = sourceKeys[i];
  10. if (excluded.indexOf(key) >= 0) continue;
  11. target[key] = source[key];
  12. }
  13. return target;
  14. }
  15. class Position {
  16. constructor(line, col, index) {
  17. this.line = void 0;
  18. this.column = void 0;
  19. this.index = void 0;
  20. this.line = line;
  21. this.column = col;
  22. this.index = index;
  23. }
  24. }
  25. class SourceLocation {
  26. constructor(start, end) {
  27. this.start = void 0;
  28. this.end = void 0;
  29. this.filename = void 0;
  30. this.identifierName = void 0;
  31. this.start = start;
  32. this.end = end;
  33. }
  34. }
  35. function createPositionWithColumnOffset(position, columnOffset) {
  36. const {
  37. line,
  38. column,
  39. index
  40. } = position;
  41. return new Position(line, column + columnOffset, index + columnOffset);
  42. }
  43. var ParseErrorCode = {
  44. SyntaxError: "BABEL_PARSER_SYNTAX_ERROR",
  45. SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  46. };
  47. const reflect = (keys, last = keys.length - 1) => ({
  48. get() {
  49. return keys.reduce((object, key) =>
  50. object[key], this);
  51. },
  52. set(value) {
  53. keys.reduce(
  54. (item, key, i) => i === last ? item[key] = value : item[key], this);
  55. }
  56. });
  57. const instantiate = (constructor, properties, descriptors) => Object.keys(descriptors).map(key => [key, descriptors[key]]).filter(([, descriptor]) => !!descriptor).map(([key, descriptor]) => [key, typeof descriptor === "function" ? {
  58. value: descriptor,
  59. enumerable: false
  60. } : typeof descriptor.reflect === "string" ? Object.assign({}, descriptor, reflect(descriptor.reflect.split("."))) : descriptor]).reduce((instance, [key, descriptor]) => Object.defineProperty(instance, key, Object.assign({
  61. configurable: true
  62. }, descriptor)), Object.assign(new constructor(), properties));
  63. var ModuleErrors = {
  64. ImportMetaOutsideModule: {
  65. message: `import.meta may appear only with 'sourceType: "module"'`,
  66. code: ParseErrorCode.SourceTypeModuleError
  67. },
  68. ImportOutsideModule: {
  69. message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  70. code: ParseErrorCode.SourceTypeModuleError
  71. }
  72. };
  73. const NodeDescriptions = {
  74. ArrayPattern: "array destructuring pattern",
  75. AssignmentExpression: "assignment expression",
  76. AssignmentPattern: "assignment expression",
  77. ArrowFunctionExpression: "arrow function expression",
  78. ConditionalExpression: "conditional expression",
  79. CatchClause: "catch clause",
  80. ForOfStatement: "for-of statement",
  81. ForInStatement: "for-in statement",
  82. ForStatement: "for-loop",
  83. FormalParameters: "function parameter list",
  84. Identifier: "identifier",
  85. ImportSpecifier: "import specifier",
  86. ImportDefaultSpecifier: "import default specifier",
  87. ImportNamespaceSpecifier: "import namespace specifier",
  88. ObjectPattern: "object destructuring pattern",
  89. ParenthesizedExpression: "parenthesized expression",
  90. RestElement: "rest element",
  91. UpdateExpression: {
  92. true: "prefix operation",
  93. false: "postfix operation"
  94. },
  95. VariableDeclarator: "variable declaration",
  96. YieldExpression: "yield expression"
  97. };
  98. const toNodeDescription = ({
  99. type,
  100. prefix
  101. }) => type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[String(prefix)] : NodeDescriptions[type];
  102. var StandardErrors = {
  103. AccessorIsGenerator: ({
  104. kind
  105. }) => `A ${kind}ter cannot be a generator.`,
  106. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  107. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  108. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  109. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  110. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  111. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  112. AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  113. BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  114. BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  115. BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  116. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  117. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  118. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  119. ConstructorIsAsync: "Constructor can't be an async function.",
  120. ConstructorIsGenerator: "Constructor can't be a generator.",
  121. DeclarationMissingInitializer: ({
  122. kind
  123. }) => `Missing initializer in ${kind} declaration.`,
  124. DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  125. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.",
  126. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  127. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  128. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  129. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  130. DeletePrivateField: "Deleting a private field is not allowed.",
  131. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  132. DuplicateConstructor: "Duplicate constructor in the same class.",
  133. DuplicateDefaultExport: "Only one default export allowed per module.",
  134. DuplicateExport: ({
  135. exportName
  136. }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  137. DuplicateProto: "Redefinition of __proto__ property.",
  138. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  139. ElementAfterRest: "Rest element must be last element.",
  140. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  141. ExportBindingIsString: ({
  142. localName,
  143. exportName
  144. }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  145. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  146. ForInOfLoopInitializer: ({
  147. type
  148. }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  149. ForInUsing: "For-in loop may not start with 'using' declaration.",
  150. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  151. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  152. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  153. IllegalBreakContinue: ({
  154. type
  155. }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  156. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  157. IllegalReturn: "'return' outside of function.",
  158. ImportBindingIsString: ({
  159. importName
  160. }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
  161. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.",
  162. ImportCallArity: ({
  163. maxArgumentCount
  164. }) => `\`import()\` requires exactly ${maxArgumentCount === 1 ? "one argument" : "one or two arguments"}.`,
  165. ImportCallNotNewExpression: "Cannot use new with import(...).",
  166. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  167. ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  168. ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  169. ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  170. IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  171. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  172. InvalidCodePoint: "Code point out of bounds.",
  173. InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  174. InvalidDecimal: "Invalid decimal.",
  175. InvalidDigit: ({
  176. radix
  177. }) => `Expected number in radix ${radix}.`,
  178. InvalidEscapeSequence: "Bad character escape sequence.",
  179. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  180. InvalidEscapedReservedWord: ({
  181. reservedWord
  182. }) => `Escape sequence in keyword ${reservedWord}.`,
  183. InvalidIdentifier: ({
  184. identifierName
  185. }) => `Invalid identifier ${identifierName}.`,
  186. InvalidLhs: ({
  187. ancestor
  188. }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  189. InvalidLhsBinding: ({
  190. ancestor
  191. }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  192. InvalidNumber: "Invalid number.",
  193. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  194. InvalidOrUnexpectedToken: ({
  195. unexpected
  196. }) => `Unexpected character '${unexpected}'.`,
  197. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  198. InvalidPrivateFieldResolution: ({
  199. identifierName
  200. }) => `Private name #${identifierName} is not defined.`,
  201. InvalidPropertyBindingPattern: "Binding member expression.",
  202. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  203. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  204. LabelRedeclaration: ({
  205. labelName
  206. }) => `Label '${labelName}' is already declared.`,
  207. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  208. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  209. MalformedRegExpFlags: "Invalid regular expression flag.",
  210. MissingClassName: "A class name is required.",
  211. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  212. MissingSemicolon: "Missing semicolon.",
  213. MissingPlugin: ({
  214. missingPlugin
  215. }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  216. MissingOneOfPlugins: ({
  217. missingPlugin
  218. }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  219. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  220. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  221. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  222. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  223. ModuleAttributesWithDuplicateKeys: ({
  224. key
  225. }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  226. ModuleExportNameHasLoneSurrogate: ({
  227. surrogateCharCode
  228. }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  229. ModuleExportUndefined: ({
  230. localName
  231. }) => `Export '${localName}' is not defined.`,
  232. MultipleDefaultsInSwitch: "Multiple default clauses.",
  233. NewlineAfterThrow: "Illegal newline after throw.",
  234. NoCatchOrFinally: "Missing catch or finally clause.",
  235. NumberIdentifier: "Identifier directly after number.",
  236. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  237. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  238. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  239. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  240. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  241. ParamDupe: "Argument name clash.",
  242. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  243. PatternHasMethod: "Object pattern can't contain methods.",
  244. PrivateInExpectedIn: ({
  245. identifierName
  246. }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  247. PrivateNameRedeclaration: ({
  248. identifierName
  249. }) => `Duplicate private name #${identifierName}.`,
  250. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  251. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  252. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  253. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  254. RestTrailingComma: "Unexpected trailing comma after rest element.",
  255. 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.",
  256. StaticPrototype: "Classes may not have static property named prototype.",
  257. 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?",
  258. SuperPrivateField: "Private fields can't be accessed on super.",
  259. TrailingDecorator: "Decorators must be attached to a class element.",
  260. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  261. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  262. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  263. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  264. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  265. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  266. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  267. UnexpectedKeyword: ({
  268. keyword
  269. }) => `Unexpected keyword '${keyword}'.`,
  270. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  271. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  272. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  273. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  274. UnexpectedPrivateField: "Unexpected private name.",
  275. UnexpectedReservedWord: ({
  276. reservedWord
  277. }) => `Unexpected reserved word '${reservedWord}'.`,
  278. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  279. UnexpectedToken: ({
  280. expected,
  281. unexpected
  282. }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  283. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  284. UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.",
  285. UnsupportedBind: "Binding should be performed on object property.",
  286. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  287. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  288. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  289. UnsupportedMetaProperty: ({
  290. target,
  291. onlyValidPropertyName
  292. }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  293. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  294. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  295. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  296. UnterminatedComment: "Unterminated comment.",
  297. UnterminatedRegExp: "Unterminated regular expression.",
  298. UnterminatedString: "Unterminated string constant.",
  299. UnterminatedTemplate: "Unterminated template.",
  300. UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  301. VarRedeclaration: ({
  302. identifierName
  303. }) => `Identifier '${identifierName}' has already been declared.`,
  304. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  305. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  306. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  307. };
  308. var StrictModeErrors = {
  309. StrictDelete: "Deleting local variable in strict mode.",
  310. StrictEvalArguments: ({
  311. referenceName
  312. }) => `Assigning to '${referenceName}' in strict mode.`,
  313. StrictEvalArgumentsBinding: ({
  314. bindingName
  315. }) => `Binding '${bindingName}' in strict mode.`,
  316. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  317. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  318. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  319. StrictWith: "'with' in strict mode."
  320. };
  321. const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]);
  322. var PipelineOperatorErrors = {
  323. PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  324. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  325. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  326. PipeTopicUnconfiguredToken: ({
  327. token
  328. }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`,
  329. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  330. PipeUnparenthesizedBody: ({
  331. type
  332. }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({
  333. type
  334. })}; please wrap it in parentheses.`,
  335. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  336. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  337. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  338. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  339. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  340. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'
  341. };
  342. const _excluded$1 = ["toMessage"],
  343. _excluded2$1 = ["message"];
  344. function toParseErrorConstructor(_ref) {
  345. let {
  346. toMessage
  347. } = _ref,
  348. properties = _objectWithoutPropertiesLoose(_ref, _excluded$1);
  349. return function constructor({
  350. loc,
  351. details
  352. }) {
  353. return instantiate(SyntaxError, Object.assign({}, properties, {
  354. loc
  355. }), {
  356. clone(overrides = {}) {
  357. const loc = overrides.loc || {};
  358. return constructor({
  359. loc: new Position("line" in loc ? loc.line : this.loc.line, "column" in loc ? loc.column : this.loc.column, "index" in loc ? loc.index : this.loc.index),
  360. details: Object.assign({}, this.details, overrides.details)
  361. });
  362. },
  363. details: {
  364. value: details,
  365. enumerable: false
  366. },
  367. message: {
  368. get() {
  369. return `${toMessage(this.details)} (${this.loc.line}:${this.loc.column})`;
  370. },
  371. set(value) {
  372. Object.defineProperty(this, "message", {
  373. value
  374. });
  375. }
  376. },
  377. pos: {
  378. reflect: "loc.index",
  379. enumerable: true
  380. },
  381. missingPlugin: "missingPlugin" in details && {
  382. reflect: "details.missingPlugin",
  383. enumerable: true
  384. }
  385. });
  386. };
  387. }
  388. function ParseErrorEnum(argument, syntaxPlugin) {
  389. if (Array.isArray(argument)) {
  390. return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]);
  391. }
  392. const ParseErrorConstructors = {};
  393. for (const reasonCode of Object.keys(argument)) {
  394. const template = argument[reasonCode];
  395. const _ref2 = typeof template === "string" ? {
  396. message: () => template
  397. } : typeof template === "function" ? {
  398. message: template
  399. } : template,
  400. {
  401. message
  402. } = _ref2,
  403. rest = _objectWithoutPropertiesLoose(_ref2, _excluded2$1);
  404. const toMessage = typeof message === "string" ? () => message : message;
  405. ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({
  406. code: ParseErrorCode.SyntaxError,
  407. reasonCode,
  408. toMessage
  409. }, syntaxPlugin ? {
  410. syntaxPlugin
  411. } : {}, rest));
  412. }
  413. return ParseErrorConstructors;
  414. }
  415. const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors));
  416. const {
  417. defineProperty
  418. } = Object;
  419. const toUnenumerable = (object, key) => defineProperty(object, key, {
  420. enumerable: false,
  421. value: object[key]
  422. });
  423. function toESTreeLocation(node) {
  424. node.loc.start && toUnenumerable(node.loc.start, "index");
  425. node.loc.end && toUnenumerable(node.loc.end, "index");
  426. return node;
  427. }
  428. var estree = (superClass => class ESTreeParserMixin extends superClass {
  429. parse() {
  430. const file = toESTreeLocation(super.parse());
  431. if (this.options.tokens) {
  432. file.tokens = file.tokens.map(toESTreeLocation);
  433. }
  434. return file;
  435. }
  436. parseRegExpLiteral({
  437. pattern,
  438. flags
  439. }) {
  440. let regex = null;
  441. try {
  442. regex = new RegExp(pattern, flags);
  443. } catch (e) {
  444. }
  445. const node = this.estreeParseLiteral(regex);
  446. node.regex = {
  447. pattern,
  448. flags
  449. };
  450. return node;
  451. }
  452. parseBigIntLiteral(value) {
  453. let bigInt;
  454. try {
  455. bigInt = BigInt(value);
  456. } catch (_unused) {
  457. bigInt = null;
  458. }
  459. const node = this.estreeParseLiteral(bigInt);
  460. node.bigint = String(node.value || value);
  461. return node;
  462. }
  463. parseDecimalLiteral(value) {
  464. const decimal = null;
  465. const node = this.estreeParseLiteral(decimal);
  466. node.decimal = String(node.value || value);
  467. return node;
  468. }
  469. estreeParseLiteral(value) {
  470. return this.parseLiteral(value, "Literal");
  471. }
  472. parseStringLiteral(value) {
  473. return this.estreeParseLiteral(value);
  474. }
  475. parseNumericLiteral(value) {
  476. return this.estreeParseLiteral(value);
  477. }
  478. parseNullLiteral() {
  479. return this.estreeParseLiteral(null);
  480. }
  481. parseBooleanLiteral(value) {
  482. return this.estreeParseLiteral(value);
  483. }
  484. directiveToStmt(directive) {
  485. const expression = directive.value;
  486. delete directive.value;
  487. expression.type = "Literal";
  488. expression.raw = expression.extra.raw;
  489. expression.value = expression.extra.expressionValue;
  490. const stmt = directive;
  491. stmt.type = "ExpressionStatement";
  492. stmt.expression = expression;
  493. stmt.directive = expression.extra.rawValue;
  494. delete expression.extra;
  495. return stmt;
  496. }
  497. initFunction(node, isAsync) {
  498. super.initFunction(node, isAsync);
  499. node.expression = false;
  500. }
  501. checkDeclaration(node) {
  502. if (node != null && this.isObjectProperty(node)) {
  503. this.checkDeclaration(node.value);
  504. } else {
  505. super.checkDeclaration(node);
  506. }
  507. }
  508. getObjectOrClassMethodParams(method) {
  509. return method.value.params;
  510. }
  511. isValidDirective(stmt) {
  512. var _stmt$expression$extr;
  513. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  514. }
  515. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  516. super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse);
  517. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  518. node.body = directiveStatements.concat(node.body);
  519. delete node.directives;
  520. }
  521. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  522. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  523. if (method.typeParameters) {
  524. method.value.typeParameters = method.typeParameters;
  525. delete method.typeParameters;
  526. }
  527. classBody.body.push(method);
  528. }
  529. parsePrivateName() {
  530. const node = super.parsePrivateName();
  531. {
  532. if (!this.getPluginOption("estree", "classFeatures")) {
  533. return node;
  534. }
  535. }
  536. return this.convertPrivateNameToPrivateIdentifier(node);
  537. }
  538. convertPrivateNameToPrivateIdentifier(node) {
  539. const name = super.getPrivateNameSV(node);
  540. node = node;
  541. delete node.id;
  542. node.name = name;
  543. node.type = "PrivateIdentifier";
  544. return node;
  545. }
  546. isPrivateName(node) {
  547. {
  548. if (!this.getPluginOption("estree", "classFeatures")) {
  549. return super.isPrivateName(node);
  550. }
  551. }
  552. return node.type === "PrivateIdentifier";
  553. }
  554. getPrivateNameSV(node) {
  555. {
  556. if (!this.getPluginOption("estree", "classFeatures")) {
  557. return super.getPrivateNameSV(node);
  558. }
  559. }
  560. return node.name;
  561. }
  562. parseLiteral(value, type) {
  563. const node = super.parseLiteral(value, type);
  564. node.raw = node.extra.raw;
  565. delete node.extra;
  566. return node;
  567. }
  568. parseFunctionBody(node, allowExpression, isMethod = false) {
  569. super.parseFunctionBody(node, allowExpression, isMethod);
  570. node.expression = node.body.type !== "BlockStatement";
  571. }
  572. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  573. let funcNode = this.startNode();
  574. funcNode.kind = node.kind;
  575. funcNode = super.parseMethod(
  576. funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  577. funcNode.type = "FunctionExpression";
  578. delete funcNode.kind;
  579. node.value = funcNode;
  580. if (type === "ClassPrivateMethod") {
  581. node.computed = false;
  582. }
  583. return this.finishNode(
  584. node, "MethodDefinition");
  585. }
  586. parseClassProperty(...args) {
  587. const propertyNode = super.parseClassProperty(...args);
  588. {
  589. if (!this.getPluginOption("estree", "classFeatures")) {
  590. return propertyNode;
  591. }
  592. }
  593. propertyNode.type = "PropertyDefinition";
  594. return propertyNode;
  595. }
  596. parseClassPrivateProperty(...args) {
  597. const propertyNode = super.parseClassPrivateProperty(...args);
  598. {
  599. if (!this.getPluginOption("estree", "classFeatures")) {
  600. return propertyNode;
  601. }
  602. }
  603. propertyNode.type = "PropertyDefinition";
  604. propertyNode.computed = false;
  605. return propertyNode;
  606. }
  607. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  608. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  609. if (node) {
  610. node.type = "Property";
  611. if (node.kind === "method") {
  612. node.kind = "init";
  613. }
  614. node.shorthand = false;
  615. }
  616. return node;
  617. }
  618. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  619. const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  620. if (node) {
  621. node.kind = "init";
  622. node.type = "Property";
  623. }
  624. return node;
  625. }
  626. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  627. return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  628. }
  629. isAssignable(node, isBinding) {
  630. if (node != null && this.isObjectProperty(node)) {
  631. return this.isAssignable(node.value, isBinding);
  632. }
  633. return super.isAssignable(node, isBinding);
  634. }
  635. toAssignable(node, isLHS = false) {
  636. if (node != null && this.isObjectProperty(node)) {
  637. const {
  638. key,
  639. value
  640. } = node;
  641. if (this.isPrivateName(key)) {
  642. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  643. }
  644. this.toAssignable(value, isLHS);
  645. } else {
  646. super.toAssignable(node, isLHS);
  647. }
  648. }
  649. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  650. if (prop.kind === "get" || prop.kind === "set") {
  651. this.raise(Errors.PatternHasAccessor, {
  652. at: prop.key
  653. });
  654. } else if (prop.method) {
  655. this.raise(Errors.PatternHasMethod, {
  656. at: prop.key
  657. });
  658. } else {
  659. super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  660. }
  661. }
  662. finishCallExpression(unfinished, optional) {
  663. const node = super.finishCallExpression(unfinished, optional);
  664. if (node.callee.type === "Import") {
  665. node.type = "ImportExpression";
  666. node.source = node.arguments[0];
  667. if (this.hasPlugin("importAssertions")) {
  668. var _node$arguments$;
  669. node.attributes = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null;
  670. }
  671. delete node.arguments;
  672. delete node.callee;
  673. }
  674. return node;
  675. }
  676. toReferencedArguments(node
  677. ) {
  678. if (node.type === "ImportExpression") {
  679. return;
  680. }
  681. super.toReferencedArguments(node);
  682. }
  683. parseExport(unfinished, decorators) {
  684. const exportStartLoc = this.state.lastTokStartLoc;
  685. const node = super.parseExport(unfinished, decorators);
  686. switch (node.type) {
  687. case "ExportAllDeclaration":
  688. node.exported = null;
  689. break;
  690. case "ExportNamedDeclaration":
  691. if (node.specifiers.length === 1 &&
  692. node.specifiers[0].type === "ExportNamespaceSpecifier") {
  693. node.type = "ExportAllDeclaration";
  694. node.exported = node.specifiers[0].exported;
  695. delete node.specifiers;
  696. }
  697. case "ExportDefaultDeclaration":
  698. {
  699. var _declaration$decorato;
  700. const {
  701. declaration
  702. } = node;
  703. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 &&
  704. declaration.start === node.start) {
  705. this.resetStartLocation(node,
  706. exportStartLoc);
  707. }
  708. }
  709. break;
  710. }
  711. return node;
  712. }
  713. parseSubscript(base, startLoc, noCalls, state) {
  714. const node = super.parseSubscript(base, startLoc, noCalls, state);
  715. if (state.optionalChainMember) {
  716. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  717. node.type = node.type.substring(8);
  718. }
  719. if (state.stop) {
  720. const chain = this.startNodeAtNode(node);
  721. chain.expression = node;
  722. return this.finishNode(chain, "ChainExpression");
  723. }
  724. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  725. node.optional = false;
  726. }
  727. return node;
  728. }
  729. hasPropertyAsPrivateName(node) {
  730. if (node.type === "ChainExpression") {
  731. node = node.expression;
  732. }
  733. return super.hasPropertyAsPrivateName(node);
  734. }
  735. isOptionalChain(node) {
  736. return node.type === "ChainExpression";
  737. }
  738. isObjectProperty(node) {
  739. return node.type === "Property" && node.kind === "init" && !node.method;
  740. }
  741. isObjectMethod(node) {
  742. return node.method || node.kind === "get" || node.kind === "set";
  743. }
  744. finishNodeAt(node, type, endLoc) {
  745. return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
  746. }
  747. resetStartLocation(node, startLoc) {
  748. super.resetStartLocation(node, startLoc);
  749. toESTreeLocation(node);
  750. }
  751. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  752. super.resetEndLocation(node, endLoc);
  753. toESTreeLocation(node);
  754. }
  755. });
  756. class TokContext {
  757. constructor(token, preserveSpace) {
  758. this.token = void 0;
  759. this.preserveSpace = void 0;
  760. this.token = token;
  761. this.preserveSpace = !!preserveSpace;
  762. }
  763. }
  764. const types = {
  765. brace: new TokContext("{"),
  766. j_oTag: new TokContext("<tag"),
  767. j_cTag: new TokContext("</tag"),
  768. j_expr: new TokContext("<tag>...</tag>", true)
  769. };
  770. {
  771. types.template = new TokContext("`", true);
  772. }
  773. const beforeExpr = true;
  774. const startsExpr = true;
  775. const isLoop = true;
  776. const isAssign = true;
  777. const prefix = true;
  778. const postfix = true;
  779. class ExportedTokenType {
  780. constructor(label, conf = {}) {
  781. this.label = void 0;
  782. this.keyword = void 0;
  783. this.beforeExpr = void 0;
  784. this.startsExpr = void 0;
  785. this.rightAssociative = void 0;
  786. this.isLoop = void 0;
  787. this.isAssign = void 0;
  788. this.prefix = void 0;
  789. this.postfix = void 0;
  790. this.binop = void 0;
  791. this.label = label;
  792. this.keyword = conf.keyword;
  793. this.beforeExpr = !!conf.beforeExpr;
  794. this.startsExpr = !!conf.startsExpr;
  795. this.rightAssociative = !!conf.rightAssociative;
  796. this.isLoop = !!conf.isLoop;
  797. this.isAssign = !!conf.isAssign;
  798. this.prefix = !!conf.prefix;
  799. this.postfix = !!conf.postfix;
  800. this.binop = conf.binop != null ? conf.binop : null;
  801. {
  802. this.updateContext = null;
  803. }
  804. }
  805. }
  806. const keywords$1 = new Map();
  807. function createKeyword(name, options = {}) {
  808. options.keyword = name;
  809. const token = createToken(name, options);
  810. keywords$1.set(name, token);
  811. return token;
  812. }
  813. function createBinop(name, binop) {
  814. return createToken(name, {
  815. beforeExpr,
  816. binop
  817. });
  818. }
  819. let tokenTypeCounter = -1;
  820. const tokenTypes = [];
  821. const tokenLabels = [];
  822. const tokenBinops = [];
  823. const tokenBeforeExprs = [];
  824. const tokenStartsExprs = [];
  825. const tokenPrefixes = [];
  826. function createToken(name, options = {}) {
  827. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  828. ++tokenTypeCounter;
  829. tokenLabels.push(name);
  830. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  831. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  832. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  833. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  834. tokenTypes.push(new ExportedTokenType(name, options));
  835. return tokenTypeCounter;
  836. }
  837. function createKeywordLike(name, options = {}) {
  838. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  839. ++tokenTypeCounter;
  840. keywords$1.set(name, tokenTypeCounter);
  841. tokenLabels.push(name);
  842. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  843. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  844. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  845. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  846. tokenTypes.push(new ExportedTokenType("name", options));
  847. return tokenTypeCounter;
  848. }
  849. const tt = {
  850. bracketL: createToken("[", {
  851. beforeExpr,
  852. startsExpr
  853. }),
  854. bracketHashL: createToken("#[", {
  855. beforeExpr,
  856. startsExpr
  857. }),
  858. bracketBarL: createToken("[|", {
  859. beforeExpr,
  860. startsExpr
  861. }),
  862. bracketR: createToken("]"),
  863. bracketBarR: createToken("|]"),
  864. braceL: createToken("{", {
  865. beforeExpr,
  866. startsExpr
  867. }),
  868. braceBarL: createToken("{|", {
  869. beforeExpr,
  870. startsExpr
  871. }),
  872. braceHashL: createToken("#{", {
  873. beforeExpr,
  874. startsExpr
  875. }),
  876. braceR: createToken("}"),
  877. braceBarR: createToken("|}"),
  878. parenL: createToken("(", {
  879. beforeExpr,
  880. startsExpr
  881. }),
  882. parenR: createToken(")"),
  883. comma: createToken(",", {
  884. beforeExpr
  885. }),
  886. semi: createToken(";", {
  887. beforeExpr
  888. }),
  889. colon: createToken(":", {
  890. beforeExpr
  891. }),
  892. doubleColon: createToken("::", {
  893. beforeExpr
  894. }),
  895. dot: createToken("."),
  896. question: createToken("?", {
  897. beforeExpr
  898. }),
  899. questionDot: createToken("?."),
  900. arrow: createToken("=>", {
  901. beforeExpr
  902. }),
  903. template: createToken("template"),
  904. ellipsis: createToken("...", {
  905. beforeExpr
  906. }),
  907. backQuote: createToken("`", {
  908. startsExpr
  909. }),
  910. dollarBraceL: createToken("${", {
  911. beforeExpr,
  912. startsExpr
  913. }),
  914. templateTail: createToken("...`", {
  915. startsExpr
  916. }),
  917. templateNonTail: createToken("...${", {
  918. beforeExpr,
  919. startsExpr
  920. }),
  921. at: createToken("@"),
  922. hash: createToken("#", {
  923. startsExpr
  924. }),
  925. interpreterDirective: createToken("#!..."),
  926. eq: createToken("=", {
  927. beforeExpr,
  928. isAssign
  929. }),
  930. assign: createToken("_=", {
  931. beforeExpr,
  932. isAssign
  933. }),
  934. slashAssign: createToken("_=", {
  935. beforeExpr,
  936. isAssign
  937. }),
  938. xorAssign: createToken("_=", {
  939. beforeExpr,
  940. isAssign
  941. }),
  942. moduloAssign: createToken("_=", {
  943. beforeExpr,
  944. isAssign
  945. }),
  946. incDec: createToken("++/--", {
  947. prefix,
  948. postfix,
  949. startsExpr
  950. }),
  951. bang: createToken("!", {
  952. beforeExpr,
  953. prefix,
  954. startsExpr
  955. }),
  956. tilde: createToken("~", {
  957. beforeExpr,
  958. prefix,
  959. startsExpr
  960. }),
  961. doubleCaret: createToken("^^", {
  962. startsExpr
  963. }),
  964. doubleAt: createToken("@@", {
  965. startsExpr
  966. }),
  967. pipeline: createBinop("|>", 0),
  968. nullishCoalescing: createBinop("??", 1),
  969. logicalOR: createBinop("||", 1),
  970. logicalAND: createBinop("&&", 2),
  971. bitwiseOR: createBinop("|", 3),
  972. bitwiseXOR: createBinop("^", 4),
  973. bitwiseAND: createBinop("&", 5),
  974. equality: createBinop("==/!=/===/!==", 6),
  975. lt: createBinop("</>/<=/>=", 7),
  976. gt: createBinop("</>/<=/>=", 7),
  977. relational: createBinop("</>/<=/>=", 7),
  978. bitShift: createBinop("<</>>/>>>", 8),
  979. bitShiftL: createBinop("<</>>/>>>", 8),
  980. bitShiftR: createBinop("<</>>/>>>", 8),
  981. plusMin: createToken("+/-", {
  982. beforeExpr,
  983. binop: 9,
  984. prefix,
  985. startsExpr
  986. }),
  987. modulo: createToken("%", {
  988. binop: 10,
  989. startsExpr
  990. }),
  991. star: createToken("*", {
  992. binop: 10
  993. }),
  994. slash: createBinop("/", 10),
  995. exponent: createToken("**", {
  996. beforeExpr,
  997. binop: 11,
  998. rightAssociative: true
  999. }),
  1000. _in: createKeyword("in", {
  1001. beforeExpr,
  1002. binop: 7
  1003. }),
  1004. _instanceof: createKeyword("instanceof", {
  1005. beforeExpr,
  1006. binop: 7
  1007. }),
  1008. _break: createKeyword("break"),
  1009. _case: createKeyword("case", {
  1010. beforeExpr
  1011. }),
  1012. _catch: createKeyword("catch"),
  1013. _continue: createKeyword("continue"),
  1014. _debugger: createKeyword("debugger"),
  1015. _default: createKeyword("default", {
  1016. beforeExpr
  1017. }),
  1018. _else: createKeyword("else", {
  1019. beforeExpr
  1020. }),
  1021. _finally: createKeyword("finally"),
  1022. _function: createKeyword("function", {
  1023. startsExpr
  1024. }),
  1025. _if: createKeyword("if"),
  1026. _return: createKeyword("return", {
  1027. beforeExpr
  1028. }),
  1029. _switch: createKeyword("switch"),
  1030. _throw: createKeyword("throw", {
  1031. beforeExpr,
  1032. prefix,
  1033. startsExpr
  1034. }),
  1035. _try: createKeyword("try"),
  1036. _var: createKeyword("var"),
  1037. _const: createKeyword("const"),
  1038. _with: createKeyword("with"),
  1039. _new: createKeyword("new", {
  1040. beforeExpr,
  1041. startsExpr
  1042. }),
  1043. _this: createKeyword("this", {
  1044. startsExpr
  1045. }),
  1046. _super: createKeyword("super", {
  1047. startsExpr
  1048. }),
  1049. _class: createKeyword("class", {
  1050. startsExpr
  1051. }),
  1052. _extends: createKeyword("extends", {
  1053. beforeExpr
  1054. }),
  1055. _export: createKeyword("export"),
  1056. _import: createKeyword("import", {
  1057. startsExpr
  1058. }),
  1059. _null: createKeyword("null", {
  1060. startsExpr
  1061. }),
  1062. _true: createKeyword("true", {
  1063. startsExpr
  1064. }),
  1065. _false: createKeyword("false", {
  1066. startsExpr
  1067. }),
  1068. _typeof: createKeyword("typeof", {
  1069. beforeExpr,
  1070. prefix,
  1071. startsExpr
  1072. }),
  1073. _void: createKeyword("void", {
  1074. beforeExpr,
  1075. prefix,
  1076. startsExpr
  1077. }),
  1078. _delete: createKeyword("delete", {
  1079. beforeExpr,
  1080. prefix,
  1081. startsExpr
  1082. }),
  1083. _do: createKeyword("do", {
  1084. isLoop,
  1085. beforeExpr
  1086. }),
  1087. _for: createKeyword("for", {
  1088. isLoop
  1089. }),
  1090. _while: createKeyword("while", {
  1091. isLoop
  1092. }),
  1093. _as: createKeywordLike("as", {
  1094. startsExpr
  1095. }),
  1096. _assert: createKeywordLike("assert", {
  1097. startsExpr
  1098. }),
  1099. _async: createKeywordLike("async", {
  1100. startsExpr
  1101. }),
  1102. _await: createKeywordLike("await", {
  1103. startsExpr
  1104. }),
  1105. _from: createKeywordLike("from", {
  1106. startsExpr
  1107. }),
  1108. _get: createKeywordLike("get", {
  1109. startsExpr
  1110. }),
  1111. _let: createKeywordLike("let", {
  1112. startsExpr
  1113. }),
  1114. _meta: createKeywordLike("meta", {
  1115. startsExpr
  1116. }),
  1117. _of: createKeywordLike("of", {
  1118. startsExpr
  1119. }),
  1120. _sent: createKeywordLike("sent", {
  1121. startsExpr
  1122. }),
  1123. _set: createKeywordLike("set", {
  1124. startsExpr
  1125. }),
  1126. _static: createKeywordLike("static", {
  1127. startsExpr
  1128. }),
  1129. _using: createKeywordLike("using", {
  1130. startsExpr
  1131. }),
  1132. _yield: createKeywordLike("yield", {
  1133. startsExpr
  1134. }),
  1135. _asserts: createKeywordLike("asserts", {
  1136. startsExpr
  1137. }),
  1138. _checks: createKeywordLike("checks", {
  1139. startsExpr
  1140. }),
  1141. _exports: createKeywordLike("exports", {
  1142. startsExpr
  1143. }),
  1144. _global: createKeywordLike("global", {
  1145. startsExpr
  1146. }),
  1147. _implements: createKeywordLike("implements", {
  1148. startsExpr
  1149. }),
  1150. _intrinsic: createKeywordLike("intrinsic", {
  1151. startsExpr
  1152. }),
  1153. _infer: createKeywordLike("infer", {
  1154. startsExpr
  1155. }),
  1156. _is: createKeywordLike("is", {
  1157. startsExpr
  1158. }),
  1159. _mixins: createKeywordLike("mixins", {
  1160. startsExpr
  1161. }),
  1162. _proto: createKeywordLike("proto", {
  1163. startsExpr
  1164. }),
  1165. _require: createKeywordLike("require", {
  1166. startsExpr
  1167. }),
  1168. _satisfies: createKeywordLike("satisfies", {
  1169. startsExpr
  1170. }),
  1171. _keyof: createKeywordLike("keyof", {
  1172. startsExpr
  1173. }),
  1174. _readonly: createKeywordLike("readonly", {
  1175. startsExpr
  1176. }),
  1177. _unique: createKeywordLike("unique", {
  1178. startsExpr
  1179. }),
  1180. _abstract: createKeywordLike("abstract", {
  1181. startsExpr
  1182. }),
  1183. _declare: createKeywordLike("declare", {
  1184. startsExpr
  1185. }),
  1186. _enum: createKeywordLike("enum", {
  1187. startsExpr
  1188. }),
  1189. _module: createKeywordLike("module", {
  1190. startsExpr
  1191. }),
  1192. _namespace: createKeywordLike("namespace", {
  1193. startsExpr
  1194. }),
  1195. _interface: createKeywordLike("interface", {
  1196. startsExpr
  1197. }),
  1198. _type: createKeywordLike("type", {
  1199. startsExpr
  1200. }),
  1201. _opaque: createKeywordLike("opaque", {
  1202. startsExpr
  1203. }),
  1204. name: createToken("name", {
  1205. startsExpr
  1206. }),
  1207. string: createToken("string", {
  1208. startsExpr
  1209. }),
  1210. num: createToken("num", {
  1211. startsExpr
  1212. }),
  1213. bigint: createToken("bigint", {
  1214. startsExpr
  1215. }),
  1216. decimal: createToken("decimal", {
  1217. startsExpr
  1218. }),
  1219. regexp: createToken("regexp", {
  1220. startsExpr
  1221. }),
  1222. privateName: createToken("#name", {
  1223. startsExpr
  1224. }),
  1225. eof: createToken("eof"),
  1226. jsxName: createToken("jsxName"),
  1227. jsxText: createToken("jsxText", {
  1228. beforeExpr: true
  1229. }),
  1230. jsxTagStart: createToken("jsxTagStart", {
  1231. startsExpr: true
  1232. }),
  1233. jsxTagEnd: createToken("jsxTagEnd"),
  1234. placeholder: createToken("%%", {
  1235. startsExpr: true
  1236. })
  1237. };
  1238. function tokenIsIdentifier(token) {
  1239. return token >= 93 && token <= 130;
  1240. }
  1241. function tokenKeywordOrIdentifierIsKeyword(token) {
  1242. return token <= 92;
  1243. }
  1244. function tokenIsKeywordOrIdentifier(token) {
  1245. return token >= 58 && token <= 130;
  1246. }
  1247. function tokenIsLiteralPropertyName(token) {
  1248. return token >= 58 && token <= 134;
  1249. }
  1250. function tokenComesBeforeExpression(token) {
  1251. return tokenBeforeExprs[token];
  1252. }
  1253. function tokenCanStartExpression(token) {
  1254. return tokenStartsExprs[token];
  1255. }
  1256. function tokenIsAssignment(token) {
  1257. return token >= 29 && token <= 33;
  1258. }
  1259. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  1260. return token >= 127 && token <= 129;
  1261. }
  1262. function tokenIsLoop(token) {
  1263. return token >= 90 && token <= 92;
  1264. }
  1265. function tokenIsKeyword(token) {
  1266. return token >= 58 && token <= 92;
  1267. }
  1268. function tokenIsOperator(token) {
  1269. return token >= 39 && token <= 59;
  1270. }
  1271. function tokenIsPostfix(token) {
  1272. return token === 34;
  1273. }
  1274. function tokenIsPrefix(token) {
  1275. return tokenPrefixes[token];
  1276. }
  1277. function tokenIsTSTypeOperator(token) {
  1278. return token >= 119 && token <= 121;
  1279. }
  1280. function tokenIsTSDeclarationStart(token) {
  1281. return token >= 122 && token <= 128;
  1282. }
  1283. function tokenLabelName(token) {
  1284. return tokenLabels[token];
  1285. }
  1286. function tokenOperatorPrecedence(token) {
  1287. return tokenBinops[token];
  1288. }
  1289. function tokenIsRightAssociative(token) {
  1290. return token === 57;
  1291. }
  1292. function tokenIsTemplate(token) {
  1293. return token >= 24 && token <= 25;
  1294. }
  1295. function getExportedToken(token) {
  1296. return tokenTypes[token];
  1297. }
  1298. {
  1299. tokenTypes[8].updateContext = context => {
  1300. context.pop();
  1301. };
  1302. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  1303. context.push(types.brace);
  1304. };
  1305. tokenTypes[22].updateContext = context => {
  1306. if (context[context.length - 1] === types.template) {
  1307. context.pop();
  1308. } else {
  1309. context.push(types.template);
  1310. }
  1311. };
  1312. tokenTypes[140].updateContext = context => {
  1313. context.push(types.j_expr, types.j_oTag);
  1314. };
  1315. }
  1316. 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\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\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-\u1711\u171f-\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-\u1b4c\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-\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-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\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";
  1317. 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\u0898-\u089f\u08ca-\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\u0c3c\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\u0cf3\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-\u0ece\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\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-\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";
  1318. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1319. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1320. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1321. 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, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 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, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 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, 20, 1, 64, 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, 38, 6, 186, 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, 19, 72, 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, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 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, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 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, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 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, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
  1322. 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, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 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, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  1323. function isInAstralSet(code, set) {
  1324. let pos = 0x10000;
  1325. for (let i = 0, length = set.length; i < length; i += 2) {
  1326. pos += set[i];
  1327. if (pos > code) return false;
  1328. pos += set[i + 1];
  1329. if (pos >= code) return true;
  1330. }
  1331. return false;
  1332. }
  1333. function isIdentifierStart(code) {
  1334. if (code < 65) return code === 36;
  1335. if (code <= 90) return true;
  1336. if (code < 97) return code === 95;
  1337. if (code <= 122) return true;
  1338. if (code <= 0xffff) {
  1339. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1340. }
  1341. return isInAstralSet(code, astralIdentifierStartCodes);
  1342. }
  1343. function isIdentifierChar(code) {
  1344. if (code < 48) return code === 36;
  1345. if (code < 58) return true;
  1346. if (code < 65) return false;
  1347. if (code <= 90) return true;
  1348. if (code < 97) return code === 95;
  1349. if (code <= 122) return true;
  1350. if (code <= 0xffff) {
  1351. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1352. }
  1353. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1354. }
  1355. const reservedWords = {
  1356. 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"],
  1357. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1358. strictBind: ["eval", "arguments"]
  1359. };
  1360. const keywords = new Set(reservedWords.keyword);
  1361. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1362. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1363. function isReservedWord(word, inModule) {
  1364. return inModule && word === "await" || word === "enum";
  1365. }
  1366. function isStrictReservedWord(word, inModule) {
  1367. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1368. }
  1369. function isStrictBindOnlyReservedWord(word) {
  1370. return reservedWordsStrictBindSet.has(word);
  1371. }
  1372. function isStrictBindReservedWord(word, inModule) {
  1373. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1374. }
  1375. function isKeyword(word) {
  1376. return keywords.has(word);
  1377. }
  1378. function isIteratorStart(current, next, next2) {
  1379. return current === 64 && next === 64 && isIdentifierStart(next2);
  1380. }
  1381. const reservedWordLikeSet = new Set(["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",
  1382. "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield",
  1383. "eval", "arguments",
  1384. "enum", "await"]);
  1385. function canBeReservedWord(word) {
  1386. return reservedWordLikeSet.has(word);
  1387. }
  1388. const SCOPE_OTHER = 0b000000000,
  1389. SCOPE_PROGRAM = 0b000000001,
  1390. SCOPE_FUNCTION = 0b000000010,
  1391. SCOPE_ARROW = 0b000000100,
  1392. SCOPE_SIMPLE_CATCH = 0b000001000,
  1393. SCOPE_SUPER = 0b000010000,
  1394. SCOPE_DIRECT_SUPER = 0b000100000,
  1395. SCOPE_CLASS = 0b001000000,
  1396. SCOPE_STATIC_BLOCK = 0b010000000,
  1397. SCOPE_TS_MODULE = 0b100000000,
  1398. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_STATIC_BLOCK | SCOPE_TS_MODULE;
  1399. const BIND_KIND_VALUE = 0b000000000001,
  1400. BIND_KIND_TYPE = 0b000000000010,
  1401. BIND_SCOPE_VAR = 0b000000000100,
  1402. BIND_SCOPE_LEXICAL = 0b000000001000,
  1403. BIND_SCOPE_FUNCTION = 0b000000010000,
  1404. BIND_FLAGS_NONE = 0b0000001000000,
  1405. BIND_FLAGS_CLASS = 0b0000010000000,
  1406. BIND_FLAGS_TS_ENUM = 0b0000100000000,
  1407. BIND_FLAGS_TS_CONST_ENUM = 0b0001000000000,
  1408. BIND_FLAGS_TS_EXPORT_ONLY = 0b0010000000000,
  1409. BIND_FLAGS_FLOW_DECLARE_FN = 0b0100000000000,
  1410. BIND_FLAGS_TS_IMPORT = 0b1000000000000;
  1411. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  1412. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  1413. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  1414. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  1415. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  1416. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  1417. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  1418. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  1419. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  1420. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  1421. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  1422. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  1423. BIND_TS_TYPE_IMPORT = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_TS_IMPORT,
  1424. BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
  1425. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  1426. CLASS_ELEMENT_KIND_GETTER = 0b010,
  1427. CLASS_ELEMENT_KIND_SETTER = 0b001,
  1428. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  1429. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  1430. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  1431. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  1432. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  1433. CLASS_ELEMENT_OTHER = 0;
  1434. class Scope {
  1435. constructor(flags) {
  1436. this.var = new Set();
  1437. this.lexical = new Set();
  1438. this.functions = new Set();
  1439. this.flags = flags;
  1440. }
  1441. }
  1442. class ScopeHandler {
  1443. constructor(parser, inModule) {
  1444. this.parser = void 0;
  1445. this.scopeStack = [];
  1446. this.inModule = void 0;
  1447. this.undefinedExports = new Map();
  1448. this.parser = parser;
  1449. this.inModule = inModule;
  1450. }
  1451. get inTopLevel() {
  1452. return (this.currentScope().flags & SCOPE_PROGRAM) > 0;
  1453. }
  1454. get inFunction() {
  1455. return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
  1456. }
  1457. get allowSuper() {
  1458. return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
  1459. }
  1460. get allowDirectSuper() {
  1461. return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
  1462. }
  1463. get inClass() {
  1464. return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
  1465. }
  1466. get inClassAndNotInNonArrowFunction() {
  1467. const flags = this.currentThisScopeFlags();
  1468. return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
  1469. }
  1470. get inStaticBlock() {
  1471. for (let i = this.scopeStack.length - 1;; i--) {
  1472. const {
  1473. flags
  1474. } = this.scopeStack[i];
  1475. if (flags & SCOPE_STATIC_BLOCK) {
  1476. return true;
  1477. }
  1478. if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
  1479. return false;
  1480. }
  1481. }
  1482. }
  1483. get inNonArrowFunction() {
  1484. return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
  1485. }
  1486. get treatFunctionsAsVar() {
  1487. return this.treatFunctionsAsVarInScope(this.currentScope());
  1488. }
  1489. createScope(flags) {
  1490. return new Scope(flags);
  1491. }
  1492. enter(flags) {
  1493. this.scopeStack.push(this.createScope(flags));
  1494. }
  1495. exit() {
  1496. const scope = this.scopeStack.pop();
  1497. return scope.flags;
  1498. }
  1499. treatFunctionsAsVarInScope(scope) {
  1500. return !!(scope.flags & (SCOPE_FUNCTION | SCOPE_STATIC_BLOCK) || !this.parser.inModule && scope.flags & SCOPE_PROGRAM);
  1501. }
  1502. declareName(name, bindingType, loc) {
  1503. let scope = this.currentScope();
  1504. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  1505. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1506. if (bindingType & BIND_SCOPE_FUNCTION) {
  1507. scope.functions.add(name);
  1508. } else {
  1509. scope.lexical.add(name);
  1510. }
  1511. if (bindingType & BIND_SCOPE_LEXICAL) {
  1512. this.maybeExportDefined(scope, name);
  1513. }
  1514. } else if (bindingType & BIND_SCOPE_VAR) {
  1515. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  1516. scope = this.scopeStack[i];
  1517. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1518. scope.var.add(name);
  1519. this.maybeExportDefined(scope, name);
  1520. if (scope.flags & SCOPE_VAR) break;
  1521. }
  1522. }
  1523. if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
  1524. this.undefinedExports.delete(name);
  1525. }
  1526. }
  1527. maybeExportDefined(scope, name) {
  1528. if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
  1529. this.undefinedExports.delete(name);
  1530. }
  1531. }
  1532. checkRedeclarationInScope(scope, name, bindingType, loc) {
  1533. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  1534. this.parser.raise(Errors.VarRedeclaration, {
  1535. at: loc,
  1536. identifierName: name
  1537. });
  1538. }
  1539. }
  1540. isRedeclaredInScope(scope, name, bindingType) {
  1541. if (!(bindingType & BIND_KIND_VALUE)) return false;
  1542. if (bindingType & BIND_SCOPE_LEXICAL) {
  1543. return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
  1544. }
  1545. if (bindingType & BIND_SCOPE_FUNCTION) {
  1546. return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
  1547. }
  1548. return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
  1549. }
  1550. checkLocalExport(id) {
  1551. const {
  1552. name
  1553. } = id;
  1554. const topLevelScope = this.scopeStack[0];
  1555. if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) &&
  1556. !topLevelScope.functions.has(name)) {
  1557. this.undefinedExports.set(name, id.loc.start);
  1558. }
  1559. }
  1560. currentScope() {
  1561. return this.scopeStack[this.scopeStack.length - 1];
  1562. }
  1563. currentVarScopeFlags() {
  1564. for (let i = this.scopeStack.length - 1;; i--) {
  1565. const {
  1566. flags
  1567. } = this.scopeStack[i];
  1568. if (flags & SCOPE_VAR) {
  1569. return flags;
  1570. }
  1571. }
  1572. }
  1573. currentThisScopeFlags() {
  1574. for (let i = this.scopeStack.length - 1;; i--) {
  1575. const {
  1576. flags
  1577. } = this.scopeStack[i];
  1578. if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
  1579. return flags;
  1580. }
  1581. }
  1582. }
  1583. }
  1584. class FlowScope extends Scope {
  1585. constructor(...args) {
  1586. super(...args);
  1587. this.declareFunctions = new Set();
  1588. }
  1589. }
  1590. class FlowScopeHandler extends ScopeHandler {
  1591. createScope(flags) {
  1592. return new FlowScope(flags);
  1593. }
  1594. declareName(name, bindingType, loc) {
  1595. const scope = this.currentScope();
  1596. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  1597. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1598. this.maybeExportDefined(scope, name);
  1599. scope.declareFunctions.add(name);
  1600. return;
  1601. }
  1602. super.declareName(name, bindingType, loc);
  1603. }
  1604. isRedeclaredInScope(scope, name, bindingType) {
  1605. if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
  1606. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  1607. return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
  1608. }
  1609. return false;
  1610. }
  1611. checkLocalExport(id) {
  1612. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  1613. super.checkLocalExport(id);
  1614. }
  1615. }
  1616. }
  1617. class BaseParser {
  1618. constructor() {
  1619. this.sawUnambiguousESM = false;
  1620. this.ambiguousScriptDifferentAst = false;
  1621. }
  1622. hasPlugin(pluginConfig) {
  1623. if (typeof pluginConfig === "string") {
  1624. return this.plugins.has(pluginConfig);
  1625. } else {
  1626. const [pluginName, pluginOptions] = pluginConfig;
  1627. if (!this.hasPlugin(pluginName)) {
  1628. return false;
  1629. }
  1630. const actualOptions = this.plugins.get(pluginName);
  1631. for (const key of Object.keys(pluginOptions)) {
  1632. if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
  1633. return false;
  1634. }
  1635. }
  1636. return true;
  1637. }
  1638. }
  1639. getPluginOption(plugin, name) {
  1640. var _this$plugins$get;
  1641. return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name];
  1642. }
  1643. }
  1644. function setTrailingComments(node, comments) {
  1645. if (node.trailingComments === undefined) {
  1646. node.trailingComments = comments;
  1647. } else {
  1648. node.trailingComments.unshift(...comments);
  1649. }
  1650. }
  1651. function setLeadingComments(node, comments) {
  1652. if (node.leadingComments === undefined) {
  1653. node.leadingComments = comments;
  1654. } else {
  1655. node.leadingComments.unshift(...comments);
  1656. }
  1657. }
  1658. function setInnerComments(node, comments) {
  1659. if (node.innerComments === undefined) {
  1660. node.innerComments = comments;
  1661. } else {
  1662. node.innerComments.unshift(...comments);
  1663. }
  1664. }
  1665. function adjustInnerComments(node, elements, commentWS) {
  1666. let lastElement = null;
  1667. let i = elements.length;
  1668. while (lastElement === null && i > 0) {
  1669. lastElement = elements[--i];
  1670. }
  1671. if (lastElement === null || lastElement.start > commentWS.start) {
  1672. setInnerComments(node, commentWS.comments);
  1673. } else {
  1674. setTrailingComments(lastElement, commentWS.comments);
  1675. }
  1676. }
  1677. class CommentsParser extends BaseParser {
  1678. addComment(comment) {
  1679. if (this.filename) comment.loc.filename = this.filename;
  1680. this.state.comments.push(comment);
  1681. }
  1682. processComment(node) {
  1683. const {
  1684. commentStack
  1685. } = this.state;
  1686. const commentStackLength = commentStack.length;
  1687. if (commentStackLength === 0) return;
  1688. let i = commentStackLength - 1;
  1689. const lastCommentWS = commentStack[i];
  1690. if (lastCommentWS.start === node.end) {
  1691. lastCommentWS.leadingNode = node;
  1692. i--;
  1693. }
  1694. const {
  1695. start: nodeStart
  1696. } = node;
  1697. for (; i >= 0; i--) {
  1698. const commentWS = commentStack[i];
  1699. const commentEnd = commentWS.end;
  1700. if (commentEnd > nodeStart) {
  1701. commentWS.containingNode = node;
  1702. this.finalizeComment(commentWS);
  1703. commentStack.splice(i, 1);
  1704. } else {
  1705. if (commentEnd === nodeStart) {
  1706. commentWS.trailingNode = node;
  1707. }
  1708. break;
  1709. }
  1710. }
  1711. }
  1712. finalizeComment(commentWS) {
  1713. const {
  1714. comments
  1715. } = commentWS;
  1716. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  1717. if (commentWS.leadingNode !== null) {
  1718. setTrailingComments(commentWS.leadingNode, comments);
  1719. }
  1720. if (commentWS.trailingNode !== null) {
  1721. setLeadingComments(commentWS.trailingNode, comments);
  1722. }
  1723. } else {
  1724. const {
  1725. containingNode: node,
  1726. start: commentStart
  1727. } = commentWS;
  1728. if (this.input.charCodeAt(commentStart - 1) === 44) {
  1729. switch (node.type) {
  1730. case "ObjectExpression":
  1731. case "ObjectPattern":
  1732. case "RecordExpression":
  1733. adjustInnerComments(node, node.properties, commentWS);
  1734. break;
  1735. case "CallExpression":
  1736. case "OptionalCallExpression":
  1737. adjustInnerComments(node, node.arguments, commentWS);
  1738. break;
  1739. case "FunctionDeclaration":
  1740. case "FunctionExpression":
  1741. case "ArrowFunctionExpression":
  1742. case "ObjectMethod":
  1743. case "ClassMethod":
  1744. case "ClassPrivateMethod":
  1745. adjustInnerComments(node, node.params, commentWS);
  1746. break;
  1747. case "ArrayExpression":
  1748. case "ArrayPattern":
  1749. case "TupleExpression":
  1750. adjustInnerComments(node, node.elements, commentWS);
  1751. break;
  1752. case "ExportNamedDeclaration":
  1753. case "ImportDeclaration":
  1754. adjustInnerComments(node, node.specifiers, commentWS);
  1755. break;
  1756. default:
  1757. {
  1758. setInnerComments(node, comments);
  1759. }
  1760. }
  1761. } else {
  1762. setInnerComments(node, comments);
  1763. }
  1764. }
  1765. }
  1766. finalizeRemainingComments() {
  1767. const {
  1768. commentStack
  1769. } = this.state;
  1770. for (let i = commentStack.length - 1; i >= 0; i--) {
  1771. this.finalizeComment(commentStack[i]);
  1772. }
  1773. this.state.commentStack = [];
  1774. }
  1775. resetPreviousNodeTrailingComments(node) {
  1776. const {
  1777. commentStack
  1778. } = this.state;
  1779. const {
  1780. length
  1781. } = commentStack;
  1782. if (length === 0) return;
  1783. const commentWS = commentStack[length - 1];
  1784. if (commentWS.leadingNode === node) {
  1785. commentWS.leadingNode = null;
  1786. }
  1787. }
  1788. takeSurroundingComments(node, start, end) {
  1789. const {
  1790. commentStack
  1791. } = this.state;
  1792. const commentStackLength = commentStack.length;
  1793. if (commentStackLength === 0) return;
  1794. let i = commentStackLength - 1;
  1795. for (; i >= 0; i--) {
  1796. const commentWS = commentStack[i];
  1797. const commentEnd = commentWS.end;
  1798. const commentStart = commentWS.start;
  1799. if (commentStart === end) {
  1800. commentWS.leadingNode = node;
  1801. } else if (commentEnd === start) {
  1802. commentWS.trailingNode = node;
  1803. } else if (commentEnd < start) {
  1804. break;
  1805. }
  1806. }
  1807. }
  1808. }
  1809. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  1810. const lineBreakG = new RegExp(lineBreak.source, "g");
  1811. function isNewLine(code) {
  1812. switch (code) {
  1813. case 10:
  1814. case 13:
  1815. case 8232:
  1816. case 8233:
  1817. return true;
  1818. default:
  1819. return false;
  1820. }
  1821. }
  1822. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  1823. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y;
  1824. const skipWhiteSpaceToLineBreak = new RegExp(
  1825. "(?=(" +
  1826. skipWhiteSpaceInLine.source + "))\\1" +
  1827. /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y");
  1828. function isWhitespace(code) {
  1829. switch (code) {
  1830. case 0x0009:
  1831. case 0x000b:
  1832. case 0x000c:
  1833. case 32:
  1834. case 160:
  1835. case 5760:
  1836. case 0x2000:
  1837. case 0x2001:
  1838. case 0x2002:
  1839. case 0x2003:
  1840. case 0x2004:
  1841. case 0x2005:
  1842. case 0x2006:
  1843. case 0x2007:
  1844. case 0x2008:
  1845. case 0x2009:
  1846. case 0x200a:
  1847. case 0x202f:
  1848. case 0x205f:
  1849. case 0x3000:
  1850. case 0xfeff:
  1851. return true;
  1852. default:
  1853. return false;
  1854. }
  1855. }
  1856. class State {
  1857. constructor() {
  1858. this.strict = void 0;
  1859. this.curLine = void 0;
  1860. this.lineStart = void 0;
  1861. this.startLoc = void 0;
  1862. this.endLoc = void 0;
  1863. this.errors = [];
  1864. this.potentialArrowAt = -1;
  1865. this.noArrowAt = [];
  1866. this.noArrowParamsConversionAt = [];
  1867. this.maybeInArrowParameters = false;
  1868. this.inType = false;
  1869. this.noAnonFunctionType = false;
  1870. this.hasFlowComment = false;
  1871. this.isAmbientContext = false;
  1872. this.inAbstractClass = false;
  1873. this.inDisallowConditionalTypesContext = false;
  1874. this.topicContext = {
  1875. maxNumOfResolvableTopics: 0,
  1876. maxTopicIndex: null
  1877. };
  1878. this.soloAwait = false;
  1879. this.inFSharpPipelineDirectBody = false;
  1880. this.labels = [];
  1881. this.comments = [];
  1882. this.commentStack = [];
  1883. this.pos = 0;
  1884. this.type = 137;
  1885. this.value = null;
  1886. this.start = 0;
  1887. this.end = 0;
  1888. this.lastTokEndLoc = null;
  1889. this.lastTokStartLoc = null;
  1890. this.lastTokStart = 0;
  1891. this.context = [types.brace];
  1892. this.canStartJSXElement = true;
  1893. this.containsEsc = false;
  1894. this.firstInvalidTemplateEscapePos = null;
  1895. this.strictErrors = new Map();
  1896. this.tokensLength = 0;
  1897. }
  1898. init({
  1899. strictMode,
  1900. sourceType,
  1901. startLine,
  1902. startColumn
  1903. }) {
  1904. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  1905. this.curLine = startLine;
  1906. this.lineStart = -startColumn;
  1907. this.startLoc = this.endLoc = new Position(startLine, startColumn, 0);
  1908. }
  1909. curPosition() {
  1910. return new Position(this.curLine, this.pos - this.lineStart, this.pos);
  1911. }
  1912. clone(skipArrays) {
  1913. const state = new State();
  1914. const keys = Object.keys(this);
  1915. for (let i = 0, length = keys.length; i < length; i++) {
  1916. const key = keys[i];
  1917. let val = this[key];
  1918. if (!skipArrays && Array.isArray(val)) {
  1919. val = val.slice();
  1920. }
  1921. state[key] = val;
  1922. }
  1923. return state;
  1924. }
  1925. }
  1926. var _isDigit = function isDigit(code) {
  1927. return code >= 48 && code <= 57;
  1928. };
  1929. const forbiddenNumericSeparatorSiblings = {
  1930. decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  1931. hex: new Set([46, 88, 95, 120])
  1932. };
  1933. const isAllowedNumericSeparatorSibling = {
  1934. bin: ch => ch === 48 || ch === 49,
  1935. oct: ch => ch >= 48 && ch <= 55,
  1936. dec: ch => ch >= 48 && ch <= 57,
  1937. hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
  1938. };
  1939. function readStringContents(type, input, pos, lineStart, curLine, errors) {
  1940. const initialPos = pos;
  1941. const initialLineStart = lineStart;
  1942. const initialCurLine = curLine;
  1943. let out = "";
  1944. let firstInvalidLoc = null;
  1945. let chunkStart = pos;
  1946. const {
  1947. length
  1948. } = input;
  1949. for (;;) {
  1950. if (pos >= length) {
  1951. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  1952. out += input.slice(chunkStart, pos);
  1953. break;
  1954. }
  1955. const ch = input.charCodeAt(pos);
  1956. if (isStringEnd(type, ch, input, pos)) {
  1957. out += input.slice(chunkStart, pos);
  1958. break;
  1959. }
  1960. if (ch === 92) {
  1961. out += input.slice(chunkStart, pos);
  1962. const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors);
  1963. if (res.ch === null && !firstInvalidLoc) {
  1964. firstInvalidLoc = {
  1965. pos,
  1966. lineStart,
  1967. curLine
  1968. };
  1969. } else {
  1970. out += res.ch;
  1971. }
  1972. ({
  1973. pos,
  1974. lineStart,
  1975. curLine
  1976. } = res);
  1977. chunkStart = pos;
  1978. } else if (ch === 8232 || ch === 8233) {
  1979. ++pos;
  1980. ++curLine;
  1981. lineStart = pos;
  1982. } else if (ch === 10 || ch === 13) {
  1983. if (type === "template") {
  1984. out += input.slice(chunkStart, pos) + "\n";
  1985. ++pos;
  1986. if (ch === 13 && input.charCodeAt(pos) === 10) {
  1987. ++pos;
  1988. }
  1989. ++curLine;
  1990. chunkStart = lineStart = pos;
  1991. } else {
  1992. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  1993. }
  1994. } else {
  1995. ++pos;
  1996. }
  1997. }
  1998. return {
  1999. pos,
  2000. str: out,
  2001. firstInvalidLoc,
  2002. lineStart,
  2003. curLine,
  2004. containsInvalid: !!firstInvalidLoc
  2005. };
  2006. }
  2007. function isStringEnd(type, ch, input, pos) {
  2008. if (type === "template") {
  2009. return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123;
  2010. }
  2011. return ch === (type === "double" ? 34 : 39);
  2012. }
  2013. function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
  2014. const throwOnInvalid = !inTemplate;
  2015. pos++;
  2016. const res = ch => ({
  2017. pos,
  2018. ch,
  2019. lineStart,
  2020. curLine
  2021. });
  2022. const ch = input.charCodeAt(pos++);
  2023. switch (ch) {
  2024. case 110:
  2025. return res("\n");
  2026. case 114:
  2027. return res("\r");
  2028. case 120:
  2029. {
  2030. let code;
  2031. ({
  2032. code,
  2033. pos
  2034. } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors));
  2035. return res(code === null ? null : String.fromCharCode(code));
  2036. }
  2037. case 117:
  2038. {
  2039. let code;
  2040. ({
  2041. code,
  2042. pos
  2043. } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors));
  2044. return res(code === null ? null : String.fromCodePoint(code));
  2045. }
  2046. case 116:
  2047. return res("\t");
  2048. case 98:
  2049. return res("\b");
  2050. case 118:
  2051. return res("\u000b");
  2052. case 102:
  2053. return res("\f");
  2054. case 13:
  2055. if (input.charCodeAt(pos) === 10) {
  2056. ++pos;
  2057. }
  2058. case 10:
  2059. lineStart = pos;
  2060. ++curLine;
  2061. case 8232:
  2062. case 8233:
  2063. return res("");
  2064. case 56:
  2065. case 57:
  2066. if (inTemplate) {
  2067. return res(null);
  2068. } else {
  2069. errors.strictNumericEscape(pos - 1, lineStart, curLine);
  2070. }
  2071. default:
  2072. if (ch >= 48 && ch <= 55) {
  2073. const startPos = pos - 1;
  2074. const match = input.slice(startPos, pos + 2).match(/^[0-7]+/);
  2075. let octalStr = match[0];
  2076. let octal = parseInt(octalStr, 8);
  2077. if (octal > 255) {
  2078. octalStr = octalStr.slice(0, -1);
  2079. octal = parseInt(octalStr, 8);
  2080. }
  2081. pos += octalStr.length - 1;
  2082. const next = input.charCodeAt(pos);
  2083. if (octalStr !== "0" || next === 56 || next === 57) {
  2084. if (inTemplate) {
  2085. return res(null);
  2086. } else {
  2087. errors.strictNumericEscape(startPos, lineStart, curLine);
  2088. }
  2089. }
  2090. return res(String.fromCharCode(octal));
  2091. }
  2092. return res(String.fromCharCode(ch));
  2093. }
  2094. }
  2095. function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) {
  2096. const initialPos = pos;
  2097. let n;
  2098. ({
  2099. n,
  2100. pos
  2101. } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid));
  2102. if (n === null) {
  2103. if (throwOnInvalid) {
  2104. errors.invalidEscapeSequence(initialPos, lineStart, curLine);
  2105. } else {
  2106. pos = initialPos - 1;
  2107. }
  2108. }
  2109. return {
  2110. code: n,
  2111. pos
  2112. };
  2113. }
  2114. function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) {
  2115. const start = pos;
  2116. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  2117. const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  2118. let invalid = false;
  2119. let total = 0;
  2120. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  2121. const code = input.charCodeAt(pos);
  2122. let val;
  2123. if (code === 95 && allowNumSeparator !== "bail") {
  2124. const prev = input.charCodeAt(pos - 1);
  2125. const next = input.charCodeAt(pos + 1);
  2126. if (!allowNumSeparator) {
  2127. if (bailOnError) return {
  2128. n: null,
  2129. pos
  2130. };
  2131. errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
  2132. } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
  2133. if (bailOnError) return {
  2134. n: null,
  2135. pos
  2136. };
  2137. errors.unexpectedNumericSeparator(pos, lineStart, curLine);
  2138. }
  2139. ++pos;
  2140. continue;
  2141. }
  2142. if (code >= 97) {
  2143. val = code - 97 + 10;
  2144. } else if (code >= 65) {
  2145. val = code - 65 + 10;
  2146. } else if (_isDigit(code)) {
  2147. val = code - 48;
  2148. } else {
  2149. val = Infinity;
  2150. }
  2151. if (val >= radix) {
  2152. if (val <= 9 && bailOnError) {
  2153. return {
  2154. n: null,
  2155. pos
  2156. };
  2157. } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
  2158. val = 0;
  2159. } else if (forceLen) {
  2160. val = 0;
  2161. invalid = true;
  2162. } else {
  2163. break;
  2164. }
  2165. }
  2166. ++pos;
  2167. total = total * radix + val;
  2168. }
  2169. if (pos === start || len != null && pos - start !== len || invalid) {
  2170. return {
  2171. n: null,
  2172. pos
  2173. };
  2174. }
  2175. return {
  2176. n: total,
  2177. pos
  2178. };
  2179. }
  2180. function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) {
  2181. const ch = input.charCodeAt(pos);
  2182. let code;
  2183. if (ch === 123) {
  2184. ++pos;
  2185. ({
  2186. code,
  2187. pos
  2188. } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors));
  2189. ++pos;
  2190. if (code !== null && code > 0x10ffff) {
  2191. if (throwOnInvalid) {
  2192. errors.invalidCodePoint(pos, lineStart, curLine);
  2193. } else {
  2194. return {
  2195. code: null,
  2196. pos
  2197. };
  2198. }
  2199. }
  2200. } else {
  2201. ({
  2202. code,
  2203. pos
  2204. } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors));
  2205. }
  2206. return {
  2207. code,
  2208. pos
  2209. };
  2210. }
  2211. const _excluded = ["at"],
  2212. _excluded2 = ["at"];
  2213. function buildPosition(pos, lineStart, curLine) {
  2214. return new Position(curLine, pos - lineStart, pos);
  2215. }
  2216. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]);
  2217. class Token {
  2218. constructor(state) {
  2219. this.type = state.type;
  2220. this.value = state.value;
  2221. this.start = state.start;
  2222. this.end = state.end;
  2223. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2224. }
  2225. }
  2226. class Tokenizer extends CommentsParser {
  2227. constructor(options, input) {
  2228. super();
  2229. this.isLookahead = void 0;
  2230. this.tokens = [];
  2231. this.errorHandlers_readInt = {
  2232. invalidDigit: (pos, lineStart, curLine, radix) => {
  2233. if (!this.options.errorRecovery) return false;
  2234. this.raise(Errors.InvalidDigit, {
  2235. at: buildPosition(pos, lineStart, curLine),
  2236. radix
  2237. });
  2238. return true;
  2239. },
  2240. numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
  2241. unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
  2242. };
  2243. this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
  2244. invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
  2245. invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
  2246. });
  2247. this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
  2248. strictNumericEscape: (pos, lineStart, curLine) => {
  2249. this.recordStrictModeErrors(Errors.StrictNumericEscape, {
  2250. at: buildPosition(pos, lineStart, curLine)
  2251. });
  2252. },
  2253. unterminated: (pos, lineStart, curLine) => {
  2254. throw this.raise(Errors.UnterminatedString, {
  2255. at: buildPosition(pos - 1, lineStart, curLine)
  2256. });
  2257. }
  2258. });
  2259. this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
  2260. strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
  2261. unterminated: (pos, lineStart, curLine) => {
  2262. throw this.raise(Errors.UnterminatedTemplate, {
  2263. at: buildPosition(pos, lineStart, curLine)
  2264. });
  2265. }
  2266. });
  2267. this.state = new State();
  2268. this.state.init(options);
  2269. this.input = input;
  2270. this.length = input.length;
  2271. this.isLookahead = false;
  2272. }
  2273. pushToken(token) {
  2274. this.tokens.length = this.state.tokensLength;
  2275. this.tokens.push(token);
  2276. ++this.state.tokensLength;
  2277. }
  2278. next() {
  2279. this.checkKeywordEscapes();
  2280. if (this.options.tokens) {
  2281. this.pushToken(new Token(this.state));
  2282. }
  2283. this.state.lastTokStart = this.state.start;
  2284. this.state.lastTokEndLoc = this.state.endLoc;
  2285. this.state.lastTokStartLoc = this.state.startLoc;
  2286. this.nextToken();
  2287. }
  2288. eat(type) {
  2289. if (this.match(type)) {
  2290. this.next();
  2291. return true;
  2292. } else {
  2293. return false;
  2294. }
  2295. }
  2296. match(type) {
  2297. return this.state.type === type;
  2298. }
  2299. createLookaheadState(state) {
  2300. return {
  2301. pos: state.pos,
  2302. value: null,
  2303. type: state.type,
  2304. start: state.start,
  2305. end: state.end,
  2306. context: [this.curContext()],
  2307. inType: state.inType,
  2308. startLoc: state.startLoc,
  2309. lastTokEndLoc: state.lastTokEndLoc,
  2310. curLine: state.curLine,
  2311. lineStart: state.lineStart,
  2312. curPosition: state.curPosition
  2313. };
  2314. }
  2315. lookahead() {
  2316. const old = this.state;
  2317. this.state = this.createLookaheadState(old);
  2318. this.isLookahead = true;
  2319. this.nextToken();
  2320. this.isLookahead = false;
  2321. const curr = this.state;
  2322. this.state = old;
  2323. return curr;
  2324. }
  2325. nextTokenStart() {
  2326. return this.nextTokenStartSince(this.state.pos);
  2327. }
  2328. nextTokenStartSince(pos) {
  2329. skipWhiteSpace.lastIndex = pos;
  2330. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2331. }
  2332. lookaheadCharCode() {
  2333. return this.input.charCodeAt(this.nextTokenStart());
  2334. }
  2335. codePointAtPos(pos) {
  2336. let cp = this.input.charCodeAt(pos);
  2337. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2338. const trail = this.input.charCodeAt(pos);
  2339. if ((trail & 0xfc00) === 0xdc00) {
  2340. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2341. }
  2342. }
  2343. return cp;
  2344. }
  2345. setStrict(strict) {
  2346. this.state.strict = strict;
  2347. if (strict) {
  2348. this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, {
  2349. at
  2350. }));
  2351. this.state.strictErrors.clear();
  2352. }
  2353. }
  2354. curContext() {
  2355. return this.state.context[this.state.context.length - 1];
  2356. }
  2357. nextToken() {
  2358. this.skipSpace();
  2359. this.state.start = this.state.pos;
  2360. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2361. if (this.state.pos >= this.length) {
  2362. this.finishToken(137);
  2363. return;
  2364. }
  2365. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2366. }
  2367. skipBlockComment(commentEnd) {
  2368. let startLoc;
  2369. if (!this.isLookahead) startLoc = this.state.curPosition();
  2370. const start = this.state.pos;
  2371. const end = this.input.indexOf(commentEnd, start + 2);
  2372. if (end === -1) {
  2373. throw this.raise(Errors.UnterminatedComment, {
  2374. at: this.state.curPosition()
  2375. });
  2376. }
  2377. this.state.pos = end + commentEnd.length;
  2378. lineBreakG.lastIndex = start + 2;
  2379. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2380. ++this.state.curLine;
  2381. this.state.lineStart = lineBreakG.lastIndex;
  2382. }
  2383. if (this.isLookahead) return;
  2384. const comment = {
  2385. type: "CommentBlock",
  2386. value: this.input.slice(start + 2, end),
  2387. start,
  2388. end: end + commentEnd.length,
  2389. loc: new SourceLocation(startLoc, this.state.curPosition())
  2390. };
  2391. if (this.options.tokens) this.pushToken(comment);
  2392. return comment;
  2393. }
  2394. skipLineComment(startSkip) {
  2395. const start = this.state.pos;
  2396. let startLoc;
  2397. if (!this.isLookahead) startLoc = this.state.curPosition();
  2398. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2399. if (this.state.pos < this.length) {
  2400. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2401. ch = this.input.charCodeAt(this.state.pos);
  2402. }
  2403. }
  2404. if (this.isLookahead) return;
  2405. const end = this.state.pos;
  2406. const value = this.input.slice(start + startSkip, end);
  2407. const comment = {
  2408. type: "CommentLine",
  2409. value,
  2410. start,
  2411. end,
  2412. loc: new SourceLocation(startLoc, this.state.curPosition())
  2413. };
  2414. if (this.options.tokens) this.pushToken(comment);
  2415. return comment;
  2416. }
  2417. skipSpace() {
  2418. const spaceStart = this.state.pos;
  2419. const comments = [];
  2420. loop: while (this.state.pos < this.length) {
  2421. const ch = this.input.charCodeAt(this.state.pos);
  2422. switch (ch) {
  2423. case 32:
  2424. case 160:
  2425. case 9:
  2426. ++this.state.pos;
  2427. break;
  2428. case 13:
  2429. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2430. ++this.state.pos;
  2431. }
  2432. case 10:
  2433. case 8232:
  2434. case 8233:
  2435. ++this.state.pos;
  2436. ++this.state.curLine;
  2437. this.state.lineStart = this.state.pos;
  2438. break;
  2439. case 47:
  2440. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2441. case 42:
  2442. {
  2443. const comment = this.skipBlockComment("*/");
  2444. if (comment !== undefined) {
  2445. this.addComment(comment);
  2446. if (this.options.attachComment) comments.push(comment);
  2447. }
  2448. break;
  2449. }
  2450. case 47:
  2451. {
  2452. const comment = this.skipLineComment(2);
  2453. if (comment !== undefined) {
  2454. this.addComment(comment);
  2455. if (this.options.attachComment) comments.push(comment);
  2456. }
  2457. break;
  2458. }
  2459. default:
  2460. break loop;
  2461. }
  2462. break;
  2463. default:
  2464. if (isWhitespace(ch)) {
  2465. ++this.state.pos;
  2466. } else if (ch === 45 && !this.inModule) {
  2467. const pos = this.state.pos;
  2468. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2469. const comment = this.skipLineComment(3);
  2470. if (comment !== undefined) {
  2471. this.addComment(comment);
  2472. if (this.options.attachComment) comments.push(comment);
  2473. }
  2474. } else {
  2475. break loop;
  2476. }
  2477. } else if (ch === 60 && !this.inModule) {
  2478. const pos = this.state.pos;
  2479. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2480. const comment = this.skipLineComment(4);
  2481. if (comment !== undefined) {
  2482. this.addComment(comment);
  2483. if (this.options.attachComment) comments.push(comment);
  2484. }
  2485. } else {
  2486. break loop;
  2487. }
  2488. } else {
  2489. break loop;
  2490. }
  2491. }
  2492. }
  2493. if (comments.length > 0) {
  2494. const end = this.state.pos;
  2495. const commentWhitespace = {
  2496. start: spaceStart,
  2497. end,
  2498. comments,
  2499. leadingNode: null,
  2500. trailingNode: null,
  2501. containingNode: null
  2502. };
  2503. this.state.commentStack.push(commentWhitespace);
  2504. }
  2505. }
  2506. finishToken(type, val) {
  2507. this.state.end = this.state.pos;
  2508. this.state.endLoc = this.state.curPosition();
  2509. const prevType = this.state.type;
  2510. this.state.type = type;
  2511. this.state.value = val;
  2512. if (!this.isLookahead) {
  2513. this.updateContext(prevType);
  2514. }
  2515. }
  2516. replaceToken(type) {
  2517. this.state.type = type;
  2518. this.updateContext();
  2519. }
  2520. readToken_numberSign() {
  2521. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2522. return;
  2523. }
  2524. const nextPos = this.state.pos + 1;
  2525. const next = this.codePointAtPos(nextPos);
  2526. if (next >= 48 && next <= 57) {
  2527. throw this.raise(Errors.UnexpectedDigitAfterHash, {
  2528. at: this.state.curPosition()
  2529. });
  2530. }
  2531. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2532. this.expectPlugin("recordAndTuple");
  2533. if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
  2534. throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, {
  2535. at: this.state.curPosition()
  2536. });
  2537. }
  2538. this.state.pos += 2;
  2539. if (next === 123) {
  2540. this.finishToken(7);
  2541. } else {
  2542. this.finishToken(1);
  2543. }
  2544. } else if (isIdentifierStart(next)) {
  2545. ++this.state.pos;
  2546. this.finishToken(136, this.readWord1(next));
  2547. } else if (next === 92) {
  2548. ++this.state.pos;
  2549. this.finishToken(136, this.readWord1());
  2550. } else {
  2551. this.finishOp(27, 1);
  2552. }
  2553. }
  2554. readToken_dot() {
  2555. const next = this.input.charCodeAt(this.state.pos + 1);
  2556. if (next >= 48 && next <= 57) {
  2557. this.readNumber(true);
  2558. return;
  2559. }
  2560. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2561. this.state.pos += 3;
  2562. this.finishToken(21);
  2563. } else {
  2564. ++this.state.pos;
  2565. this.finishToken(16);
  2566. }
  2567. }
  2568. readToken_slash() {
  2569. const next = this.input.charCodeAt(this.state.pos + 1);
  2570. if (next === 61) {
  2571. this.finishOp(31, 2);
  2572. } else {
  2573. this.finishOp(56, 1);
  2574. }
  2575. }
  2576. readToken_interpreter() {
  2577. if (this.state.pos !== 0 || this.length < 2) return false;
  2578. let ch = this.input.charCodeAt(this.state.pos + 1);
  2579. if (ch !== 33) return false;
  2580. const start = this.state.pos;
  2581. this.state.pos += 1;
  2582. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2583. ch = this.input.charCodeAt(this.state.pos);
  2584. }
  2585. const value = this.input.slice(start + 2, this.state.pos);
  2586. this.finishToken(28, value);
  2587. return true;
  2588. }
  2589. readToken_mult_modulo(code) {
  2590. let type = code === 42 ? 55 : 54;
  2591. let width = 1;
  2592. let next = this.input.charCodeAt(this.state.pos + 1);
  2593. if (code === 42 && next === 42) {
  2594. width++;
  2595. next = this.input.charCodeAt(this.state.pos + 2);
  2596. type = 57;
  2597. }
  2598. if (next === 61 && !this.state.inType) {
  2599. width++;
  2600. type = code === 37 ? 33 : 30;
  2601. }
  2602. this.finishOp(type, width);
  2603. }
  2604. readToken_pipe_amp(code) {
  2605. const next = this.input.charCodeAt(this.state.pos + 1);
  2606. if (next === code) {
  2607. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2608. this.finishOp(30, 3);
  2609. } else {
  2610. this.finishOp(code === 124 ? 41 : 42, 2);
  2611. }
  2612. return;
  2613. }
  2614. if (code === 124) {
  2615. if (next === 62) {
  2616. this.finishOp(39, 2);
  2617. return;
  2618. }
  2619. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2620. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2621. throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, {
  2622. at: this.state.curPosition()
  2623. });
  2624. }
  2625. this.state.pos += 2;
  2626. this.finishToken(9);
  2627. return;
  2628. }
  2629. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2630. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2631. throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, {
  2632. at: this.state.curPosition()
  2633. });
  2634. }
  2635. this.state.pos += 2;
  2636. this.finishToken(4);
  2637. return;
  2638. }
  2639. }
  2640. if (next === 61) {
  2641. this.finishOp(30, 2);
  2642. return;
  2643. }
  2644. this.finishOp(code === 124 ? 43 : 45, 1);
  2645. }
  2646. readToken_caret() {
  2647. const next = this.input.charCodeAt(this.state.pos + 1);
  2648. if (next === 61 && !this.state.inType) {
  2649. this.finishOp(32, 2);
  2650. }
  2651. else if (next === 94 &&
  2652. this.hasPlugin(["pipelineOperator", {
  2653. proposal: "hack",
  2654. topicToken: "^^"
  2655. }])) {
  2656. this.finishOp(37, 2);
  2657. const lookaheadCh = this.input.codePointAt(this.state.pos);
  2658. if (lookaheadCh === 94) {
  2659. throw this.unexpected();
  2660. }
  2661. }
  2662. else {
  2663. this.finishOp(44, 1);
  2664. }
  2665. }
  2666. readToken_atSign() {
  2667. const next = this.input.charCodeAt(this.state.pos + 1);
  2668. if (next === 64 && this.hasPlugin(["pipelineOperator", {
  2669. proposal: "hack",
  2670. topicToken: "@@"
  2671. }])) {
  2672. this.finishOp(38, 2);
  2673. }
  2674. else {
  2675. this.finishOp(26, 1);
  2676. }
  2677. }
  2678. readToken_plus_min(code) {
  2679. const next = this.input.charCodeAt(this.state.pos + 1);
  2680. if (next === code) {
  2681. this.finishOp(34, 2);
  2682. return;
  2683. }
  2684. if (next === 61) {
  2685. this.finishOp(30, 2);
  2686. } else {
  2687. this.finishOp(53, 1);
  2688. }
  2689. }
  2690. readToken_lt() {
  2691. const {
  2692. pos
  2693. } = this.state;
  2694. const next = this.input.charCodeAt(pos + 1);
  2695. if (next === 60) {
  2696. if (this.input.charCodeAt(pos + 2) === 61) {
  2697. this.finishOp(30, 3);
  2698. return;
  2699. }
  2700. this.finishOp(51, 2);
  2701. return;
  2702. }
  2703. if (next === 61) {
  2704. this.finishOp(49, 2);
  2705. return;
  2706. }
  2707. this.finishOp(47, 1);
  2708. }
  2709. readToken_gt() {
  2710. const {
  2711. pos
  2712. } = this.state;
  2713. const next = this.input.charCodeAt(pos + 1);
  2714. if (next === 62) {
  2715. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2716. if (this.input.charCodeAt(pos + size) === 61) {
  2717. this.finishOp(30, size + 1);
  2718. return;
  2719. }
  2720. this.finishOp(52, size);
  2721. return;
  2722. }
  2723. if (next === 61) {
  2724. this.finishOp(49, 2);
  2725. return;
  2726. }
  2727. this.finishOp(48, 1);
  2728. }
  2729. readToken_eq_excl(code) {
  2730. const next = this.input.charCodeAt(this.state.pos + 1);
  2731. if (next === 61) {
  2732. this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2733. return;
  2734. }
  2735. if (code === 61 && next === 62) {
  2736. this.state.pos += 2;
  2737. this.finishToken(19);
  2738. return;
  2739. }
  2740. this.finishOp(code === 61 ? 29 : 35, 1);
  2741. }
  2742. readToken_question() {
  2743. const next = this.input.charCodeAt(this.state.pos + 1);
  2744. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2745. if (next === 63) {
  2746. if (next2 === 61) {
  2747. this.finishOp(30, 3);
  2748. } else {
  2749. this.finishOp(40, 2);
  2750. }
  2751. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2752. this.state.pos += 2;
  2753. this.finishToken(18);
  2754. } else {
  2755. ++this.state.pos;
  2756. this.finishToken(17);
  2757. }
  2758. }
  2759. getTokenFromCode(code) {
  2760. switch (code) {
  2761. case 46:
  2762. this.readToken_dot();
  2763. return;
  2764. case 40:
  2765. ++this.state.pos;
  2766. this.finishToken(10);
  2767. return;
  2768. case 41:
  2769. ++this.state.pos;
  2770. this.finishToken(11);
  2771. return;
  2772. case 59:
  2773. ++this.state.pos;
  2774. this.finishToken(13);
  2775. return;
  2776. case 44:
  2777. ++this.state.pos;
  2778. this.finishToken(12);
  2779. return;
  2780. case 91:
  2781. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2782. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2783. throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, {
  2784. at: this.state.curPosition()
  2785. });
  2786. }
  2787. this.state.pos += 2;
  2788. this.finishToken(2);
  2789. } else {
  2790. ++this.state.pos;
  2791. this.finishToken(0);
  2792. }
  2793. return;
  2794. case 93:
  2795. ++this.state.pos;
  2796. this.finishToken(3);
  2797. return;
  2798. case 123:
  2799. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2800. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2801. throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, {
  2802. at: this.state.curPosition()
  2803. });
  2804. }
  2805. this.state.pos += 2;
  2806. this.finishToken(6);
  2807. } else {
  2808. ++this.state.pos;
  2809. this.finishToken(5);
  2810. }
  2811. return;
  2812. case 125:
  2813. ++this.state.pos;
  2814. this.finishToken(8);
  2815. return;
  2816. case 58:
  2817. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  2818. this.finishOp(15, 2);
  2819. } else {
  2820. ++this.state.pos;
  2821. this.finishToken(14);
  2822. }
  2823. return;
  2824. case 63:
  2825. this.readToken_question();
  2826. return;
  2827. case 96:
  2828. this.readTemplateToken();
  2829. return;
  2830. case 48:
  2831. {
  2832. const next = this.input.charCodeAt(this.state.pos + 1);
  2833. if (next === 120 || next === 88) {
  2834. this.readRadixNumber(16);
  2835. return;
  2836. }
  2837. if (next === 111 || next === 79) {
  2838. this.readRadixNumber(8);
  2839. return;
  2840. }
  2841. if (next === 98 || next === 66) {
  2842. this.readRadixNumber(2);
  2843. return;
  2844. }
  2845. }
  2846. case 49:
  2847. case 50:
  2848. case 51:
  2849. case 52:
  2850. case 53:
  2851. case 54:
  2852. case 55:
  2853. case 56:
  2854. case 57:
  2855. this.readNumber(false);
  2856. return;
  2857. case 34:
  2858. case 39:
  2859. this.readString(code);
  2860. return;
  2861. case 47:
  2862. this.readToken_slash();
  2863. return;
  2864. case 37:
  2865. case 42:
  2866. this.readToken_mult_modulo(code);
  2867. return;
  2868. case 124:
  2869. case 38:
  2870. this.readToken_pipe_amp(code);
  2871. return;
  2872. case 94:
  2873. this.readToken_caret();
  2874. return;
  2875. case 43:
  2876. case 45:
  2877. this.readToken_plus_min(code);
  2878. return;
  2879. case 60:
  2880. this.readToken_lt();
  2881. return;
  2882. case 62:
  2883. this.readToken_gt();
  2884. return;
  2885. case 61:
  2886. case 33:
  2887. this.readToken_eq_excl(code);
  2888. return;
  2889. case 126:
  2890. this.finishOp(36, 1);
  2891. return;
  2892. case 64:
  2893. this.readToken_atSign();
  2894. return;
  2895. case 35:
  2896. this.readToken_numberSign();
  2897. return;
  2898. case 92:
  2899. this.readWord();
  2900. return;
  2901. default:
  2902. if (isIdentifierStart(code)) {
  2903. this.readWord(code);
  2904. return;
  2905. }
  2906. }
  2907. throw this.raise(Errors.InvalidOrUnexpectedToken, {
  2908. at: this.state.curPosition(),
  2909. unexpected: String.fromCodePoint(code)
  2910. });
  2911. }
  2912. finishOp(type, size) {
  2913. const str = this.input.slice(this.state.pos, this.state.pos + size);
  2914. this.state.pos += size;
  2915. this.finishToken(type, str);
  2916. }
  2917. readRegexp() {
  2918. const startLoc = this.state.startLoc;
  2919. const start = this.state.start + 1;
  2920. let escaped, inClass;
  2921. let {
  2922. pos
  2923. } = this.state;
  2924. for (;; ++pos) {
  2925. if (pos >= this.length) {
  2926. throw this.raise(Errors.UnterminatedRegExp, {
  2927. at: createPositionWithColumnOffset(startLoc, 1)
  2928. });
  2929. }
  2930. const ch = this.input.charCodeAt(pos);
  2931. if (isNewLine(ch)) {
  2932. throw this.raise(Errors.UnterminatedRegExp, {
  2933. at: createPositionWithColumnOffset(startLoc, 1)
  2934. });
  2935. }
  2936. if (escaped) {
  2937. escaped = false;
  2938. } else {
  2939. if (ch === 91) {
  2940. inClass = true;
  2941. } else if (ch === 93 && inClass) {
  2942. inClass = false;
  2943. } else if (ch === 47 && !inClass) {
  2944. break;
  2945. }
  2946. escaped = ch === 92;
  2947. }
  2948. }
  2949. const content = this.input.slice(start, pos);
  2950. ++pos;
  2951. let mods = "";
  2952. const nextPos = () =>
  2953. createPositionWithColumnOffset(startLoc, pos + 2 - start);
  2954. while (pos < this.length) {
  2955. const cp = this.codePointAtPos(pos);
  2956. const char = String.fromCharCode(cp);
  2957. if (VALID_REGEX_FLAGS.has(cp)) {
  2958. if (cp === 118) {
  2959. this.expectPlugin("regexpUnicodeSets", nextPos());
  2960. if (mods.includes("u")) {
  2961. this.raise(Errors.IncompatibleRegExpUVFlags, {
  2962. at: nextPos()
  2963. });
  2964. }
  2965. } else if (cp === 117) {
  2966. if (mods.includes("v")) {
  2967. this.raise(Errors.IncompatibleRegExpUVFlags, {
  2968. at: nextPos()
  2969. });
  2970. }
  2971. }
  2972. if (mods.includes(char)) {
  2973. this.raise(Errors.DuplicateRegExpFlags, {
  2974. at: nextPos()
  2975. });
  2976. }
  2977. } else if (isIdentifierChar(cp) || cp === 92) {
  2978. this.raise(Errors.MalformedRegExpFlags, {
  2979. at: nextPos()
  2980. });
  2981. } else {
  2982. break;
  2983. }
  2984. ++pos;
  2985. mods += char;
  2986. }
  2987. this.state.pos = pos;
  2988. this.finishToken(135, {
  2989. pattern: content,
  2990. flags: mods
  2991. });
  2992. }
  2993. readInt(radix, len, forceLen = false, allowNumSeparator = true) {
  2994. const {
  2995. n,
  2996. pos
  2997. } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
  2998. this.state.pos = pos;
  2999. return n;
  3000. }
  3001. readRadixNumber(radix) {
  3002. const startLoc = this.state.curPosition();
  3003. let isBigInt = false;
  3004. this.state.pos += 2;
  3005. const val = this.readInt(radix);
  3006. if (val == null) {
  3007. this.raise(Errors.InvalidDigit, {
  3008. at: createPositionWithColumnOffset(startLoc, 2),
  3009. radix
  3010. });
  3011. }
  3012. const next = this.input.charCodeAt(this.state.pos);
  3013. if (next === 110) {
  3014. ++this.state.pos;
  3015. isBigInt = true;
  3016. } else if (next === 109) {
  3017. throw this.raise(Errors.InvalidDecimal, {
  3018. at: startLoc
  3019. });
  3020. }
  3021. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3022. throw this.raise(Errors.NumberIdentifier, {
  3023. at: this.state.curPosition()
  3024. });
  3025. }
  3026. if (isBigInt) {
  3027. const str = this.input.slice(startLoc.index, this.state.pos).replace(/[_n]/g, "");
  3028. this.finishToken(133, str);
  3029. return;
  3030. }
  3031. this.finishToken(132, val);
  3032. }
  3033. readNumber(startsWithDot) {
  3034. const start = this.state.pos;
  3035. const startLoc = this.state.curPosition();
  3036. let isFloat = false;
  3037. let isBigInt = false;
  3038. let isDecimal = false;
  3039. let hasExponent = false;
  3040. let isOctal = false;
  3041. if (!startsWithDot && this.readInt(10) === null) {
  3042. this.raise(Errors.InvalidNumber, {
  3043. at: this.state.curPosition()
  3044. });
  3045. }
  3046. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3047. if (hasLeadingZero) {
  3048. const integer = this.input.slice(start, this.state.pos);
  3049. this.recordStrictModeErrors(Errors.StrictOctalLiteral, {
  3050. at: startLoc
  3051. });
  3052. if (!this.state.strict) {
  3053. const underscorePos = integer.indexOf("_");
  3054. if (underscorePos > 0) {
  3055. this.raise(Errors.ZeroDigitNumericSeparator, {
  3056. at: createPositionWithColumnOffset(startLoc, underscorePos)
  3057. });
  3058. }
  3059. }
  3060. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3061. }
  3062. let next = this.input.charCodeAt(this.state.pos);
  3063. if (next === 46 && !isOctal) {
  3064. ++this.state.pos;
  3065. this.readInt(10);
  3066. isFloat = true;
  3067. next = this.input.charCodeAt(this.state.pos);
  3068. }
  3069. if ((next === 69 || next === 101) && !isOctal) {
  3070. next = this.input.charCodeAt(++this.state.pos);
  3071. if (next === 43 || next === 45) {
  3072. ++this.state.pos;
  3073. }
  3074. if (this.readInt(10) === null) {
  3075. this.raise(Errors.InvalidOrMissingExponent, {
  3076. at: startLoc
  3077. });
  3078. }
  3079. isFloat = true;
  3080. hasExponent = true;
  3081. next = this.input.charCodeAt(this.state.pos);
  3082. }
  3083. if (next === 110) {
  3084. if (isFloat || hasLeadingZero) {
  3085. this.raise(Errors.InvalidBigIntLiteral, {
  3086. at: startLoc
  3087. });
  3088. }
  3089. ++this.state.pos;
  3090. isBigInt = true;
  3091. }
  3092. if (next === 109) {
  3093. this.expectPlugin("decimal", this.state.curPosition());
  3094. if (hasExponent || hasLeadingZero) {
  3095. this.raise(Errors.InvalidDecimal, {
  3096. at: startLoc
  3097. });
  3098. }
  3099. ++this.state.pos;
  3100. isDecimal = true;
  3101. }
  3102. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3103. throw this.raise(Errors.NumberIdentifier, {
  3104. at: this.state.curPosition()
  3105. });
  3106. }
  3107. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3108. if (isBigInt) {
  3109. this.finishToken(133, str);
  3110. return;
  3111. }
  3112. if (isDecimal) {
  3113. this.finishToken(134, str);
  3114. return;
  3115. }
  3116. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3117. this.finishToken(132, val);
  3118. }
  3119. readCodePoint(throwOnInvalid) {
  3120. const {
  3121. code,
  3122. pos
  3123. } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
  3124. this.state.pos = pos;
  3125. return code;
  3126. }
  3127. readString(quote) {
  3128. const {
  3129. str,
  3130. pos,
  3131. curLine,
  3132. lineStart
  3133. } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1,
  3134. this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
  3135. this.state.pos = pos + 1;
  3136. this.state.lineStart = lineStart;
  3137. this.state.curLine = curLine;
  3138. this.finishToken(131, str);
  3139. }
  3140. readTemplateContinuation() {
  3141. if (!this.match(8)) {
  3142. this.unexpected(null, 8);
  3143. }
  3144. this.state.pos--;
  3145. this.readTemplateToken();
  3146. }
  3147. readTemplateToken() {
  3148. const opening = this.input[this.state.pos];
  3149. const {
  3150. str,
  3151. firstInvalidLoc,
  3152. pos,
  3153. curLine,
  3154. lineStart
  3155. } = readStringContents("template", this.input, this.state.pos + 1,
  3156. this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
  3157. this.state.pos = pos + 1;
  3158. this.state.lineStart = lineStart;
  3159. this.state.curLine = curLine;
  3160. if (firstInvalidLoc) {
  3161. this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, firstInvalidLoc.pos);
  3162. }
  3163. if (this.input.codePointAt(pos) === 96) {
  3164. this.finishToken(24, firstInvalidLoc ? null : opening + str + "`");
  3165. } else {
  3166. this.state.pos++;
  3167. this.finishToken(25, firstInvalidLoc ? null : opening + str + "${");
  3168. }
  3169. }
  3170. recordStrictModeErrors(toParseError, {
  3171. at
  3172. }) {
  3173. const index = at.index;
  3174. if (this.state.strict && !this.state.strictErrors.has(index)) {
  3175. this.raise(toParseError, {
  3176. at
  3177. });
  3178. } else {
  3179. this.state.strictErrors.set(index, [toParseError, at]);
  3180. }
  3181. }
  3182. readWord1(firstCode) {
  3183. this.state.containsEsc = false;
  3184. let word = "";
  3185. const start = this.state.pos;
  3186. let chunkStart = this.state.pos;
  3187. if (firstCode !== undefined) {
  3188. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3189. }
  3190. while (this.state.pos < this.length) {
  3191. const ch = this.codePointAtPos(this.state.pos);
  3192. if (isIdentifierChar(ch)) {
  3193. this.state.pos += ch <= 0xffff ? 1 : 2;
  3194. } else if (ch === 92) {
  3195. this.state.containsEsc = true;
  3196. word += this.input.slice(chunkStart, this.state.pos);
  3197. const escStart = this.state.curPosition();
  3198. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3199. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3200. this.raise(Errors.MissingUnicodeEscape, {
  3201. at: this.state.curPosition()
  3202. });
  3203. chunkStart = this.state.pos - 1;
  3204. continue;
  3205. }
  3206. ++this.state.pos;
  3207. const esc = this.readCodePoint(true);
  3208. if (esc !== null) {
  3209. if (!identifierCheck(esc)) {
  3210. this.raise(Errors.EscapedCharNotAnIdentifier, {
  3211. at: escStart
  3212. });
  3213. }
  3214. word += String.fromCodePoint(esc);
  3215. }
  3216. chunkStart = this.state.pos;
  3217. } else {
  3218. break;
  3219. }
  3220. }
  3221. return word + this.input.slice(chunkStart, this.state.pos);
  3222. }
  3223. readWord(firstCode) {
  3224. const word = this.readWord1(firstCode);
  3225. const type = keywords$1.get(word);
  3226. if (type !== undefined) {
  3227. this.finishToken(type, tokenLabelName(type));
  3228. } else {
  3229. this.finishToken(130, word);
  3230. }
  3231. }
  3232. checkKeywordEscapes() {
  3233. const {
  3234. type
  3235. } = this.state;
  3236. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3237. this.raise(Errors.InvalidEscapedReservedWord, {
  3238. at: this.state.startLoc,
  3239. reservedWord: tokenLabelName(type)
  3240. });
  3241. }
  3242. }
  3243. raise(toParseError, raiseProperties) {
  3244. const {
  3245. at
  3246. } = raiseProperties,
  3247. details = _objectWithoutPropertiesLoose(raiseProperties, _excluded);
  3248. const loc = at instanceof Position ? at : at.loc.start;
  3249. const error = toParseError({
  3250. loc,
  3251. details
  3252. });
  3253. if (!this.options.errorRecovery) throw error;
  3254. if (!this.isLookahead) this.state.errors.push(error);
  3255. return error;
  3256. }
  3257. raiseOverwrite(toParseError, raiseProperties) {
  3258. const {
  3259. at
  3260. } = raiseProperties,
  3261. details = _objectWithoutPropertiesLoose(raiseProperties, _excluded2);
  3262. const loc = at instanceof Position ? at : at.loc.start;
  3263. const pos = loc.index;
  3264. const errors = this.state.errors;
  3265. for (let i = errors.length - 1; i >= 0; i--) {
  3266. const error = errors[i];
  3267. if (error.loc.index === pos) {
  3268. return errors[i] = toParseError({
  3269. loc,
  3270. details
  3271. });
  3272. }
  3273. if (error.loc.index < pos) break;
  3274. }
  3275. return this.raise(toParseError, raiseProperties);
  3276. }
  3277. updateContext(prevType) {}
  3278. unexpected(loc, type) {
  3279. throw this.raise(Errors.UnexpectedToken, {
  3280. expected: type ? tokenLabelName(type) : null,
  3281. at: loc != null ? loc : this.state.startLoc
  3282. });
  3283. }
  3284. expectPlugin(pluginName, loc) {
  3285. if (this.hasPlugin(pluginName)) {
  3286. return true;
  3287. }
  3288. throw this.raise(Errors.MissingPlugin, {
  3289. at: loc != null ? loc : this.state.startLoc,
  3290. missingPlugin: [pluginName]
  3291. });
  3292. }
  3293. expectOnePlugin(pluginNames) {
  3294. if (!pluginNames.some(name => this.hasPlugin(name))) {
  3295. throw this.raise(Errors.MissingOneOfPlugins, {
  3296. at: this.state.startLoc,
  3297. missingPlugin: pluginNames
  3298. });
  3299. }
  3300. }
  3301. errorBuilder(error) {
  3302. return (pos, lineStart, curLine) => {
  3303. this.raise(error, {
  3304. at: buildPosition(pos, lineStart, curLine)
  3305. });
  3306. };
  3307. }
  3308. }
  3309. class ClassScope {
  3310. constructor() {
  3311. this.privateNames = new Set();
  3312. this.loneAccessors = new Map();
  3313. this.undefinedPrivateNames = new Map();
  3314. }
  3315. }
  3316. class ClassScopeHandler {
  3317. constructor(parser) {
  3318. this.parser = void 0;
  3319. this.stack = [];
  3320. this.undefinedPrivateNames = new Map();
  3321. this.parser = parser;
  3322. }
  3323. current() {
  3324. return this.stack[this.stack.length - 1];
  3325. }
  3326. enter() {
  3327. this.stack.push(new ClassScope());
  3328. }
  3329. exit() {
  3330. const oldClassScope = this.stack.pop();
  3331. const current = this.current();
  3332. for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3333. if (current) {
  3334. if (!current.undefinedPrivateNames.has(name)) {
  3335. current.undefinedPrivateNames.set(name, loc);
  3336. }
  3337. } else {
  3338. this.parser.raise(Errors.InvalidPrivateFieldResolution, {
  3339. at: loc,
  3340. identifierName: name
  3341. });
  3342. }
  3343. }
  3344. }
  3345. declarePrivateName(name, elementType, loc) {
  3346. const {
  3347. privateNames,
  3348. loneAccessors,
  3349. undefinedPrivateNames
  3350. } = this.current();
  3351. let redefined = privateNames.has(name);
  3352. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  3353. const accessor = redefined && loneAccessors.get(name);
  3354. if (accessor) {
  3355. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  3356. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  3357. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  3358. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  3359. redefined = oldKind === newKind || oldStatic !== newStatic;
  3360. if (!redefined) loneAccessors.delete(name);
  3361. } else if (!redefined) {
  3362. loneAccessors.set(name, elementType);
  3363. }
  3364. }
  3365. if (redefined) {
  3366. this.parser.raise(Errors.PrivateNameRedeclaration, {
  3367. at: loc,
  3368. identifierName: name
  3369. });
  3370. }
  3371. privateNames.add(name);
  3372. undefinedPrivateNames.delete(name);
  3373. }
  3374. usePrivateName(name, loc) {
  3375. let classScope;
  3376. for (classScope of this.stack) {
  3377. if (classScope.privateNames.has(name)) return;
  3378. }
  3379. if (classScope) {
  3380. classScope.undefinedPrivateNames.set(name, loc);
  3381. } else {
  3382. this.parser.raise(Errors.InvalidPrivateFieldResolution, {
  3383. at: loc,
  3384. identifierName: name
  3385. });
  3386. }
  3387. }
  3388. }
  3389. const kExpression = 0,
  3390. kMaybeArrowParameterDeclaration = 1,
  3391. kMaybeAsyncArrowParameterDeclaration = 2,
  3392. kParameterDeclaration = 3;
  3393. class ExpressionScope {
  3394. constructor(type = kExpression) {
  3395. this.type = void 0;
  3396. this.type = type;
  3397. }
  3398. canBeArrowParameterDeclaration() {
  3399. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  3400. }
  3401. isCertainlyParameterDeclaration() {
  3402. return this.type === kParameterDeclaration;
  3403. }
  3404. }
  3405. class ArrowHeadParsingScope extends ExpressionScope {
  3406. constructor(type) {
  3407. super(type);
  3408. this.declarationErrors = new Map();
  3409. }
  3410. recordDeclarationError(ParsingErrorClass, {
  3411. at
  3412. }) {
  3413. const index = at.index;
  3414. this.declarationErrors.set(index, [ParsingErrorClass, at]);
  3415. }
  3416. clearDeclarationError(index) {
  3417. this.declarationErrors.delete(index);
  3418. }
  3419. iterateErrors(iterator) {
  3420. this.declarationErrors.forEach(iterator);
  3421. }
  3422. }
  3423. class ExpressionScopeHandler {
  3424. constructor(parser) {
  3425. this.parser = void 0;
  3426. this.stack = [new ExpressionScope()];
  3427. this.parser = parser;
  3428. }
  3429. enter(scope) {
  3430. this.stack.push(scope);
  3431. }
  3432. exit() {
  3433. this.stack.pop();
  3434. }
  3435. recordParameterInitializerError(toParseError, {
  3436. at: node
  3437. }) {
  3438. const origin = {
  3439. at: node.loc.start
  3440. };
  3441. const {
  3442. stack
  3443. } = this;
  3444. let i = stack.length - 1;
  3445. let scope = stack[i];
  3446. while (!scope.isCertainlyParameterDeclaration()) {
  3447. if (scope.canBeArrowParameterDeclaration()) {
  3448. scope.recordDeclarationError(toParseError, origin);
  3449. } else {
  3450. return;
  3451. }
  3452. scope = stack[--i];
  3453. }
  3454. this.parser.raise(toParseError, origin);
  3455. }
  3456. recordArrowParameterBindingError(error, {
  3457. at: node
  3458. }) {
  3459. const {
  3460. stack
  3461. } = this;
  3462. const scope = stack[stack.length - 1];
  3463. const origin = {
  3464. at: node.loc.start
  3465. };
  3466. if (scope.isCertainlyParameterDeclaration()) {
  3467. this.parser.raise(error, origin);
  3468. } else if (scope.canBeArrowParameterDeclaration()) {
  3469. scope.recordDeclarationError(error, origin);
  3470. } else {
  3471. return;
  3472. }
  3473. }
  3474. recordAsyncArrowParametersError({
  3475. at
  3476. }) {
  3477. const {
  3478. stack
  3479. } = this;
  3480. let i = stack.length - 1;
  3481. let scope = stack[i];
  3482. while (scope.canBeArrowParameterDeclaration()) {
  3483. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  3484. scope.recordDeclarationError(Errors.AwaitBindingIdentifier, {
  3485. at
  3486. });
  3487. }
  3488. scope = stack[--i];
  3489. }
  3490. }
  3491. validateAsPattern() {
  3492. const {
  3493. stack
  3494. } = this;
  3495. const currentScope = stack[stack.length - 1];
  3496. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3497. currentScope.iterateErrors(([toParseError, loc]) => {
  3498. this.parser.raise(toParseError, {
  3499. at: loc
  3500. });
  3501. let i = stack.length - 2;
  3502. let scope = stack[i];
  3503. while (scope.canBeArrowParameterDeclaration()) {
  3504. scope.clearDeclarationError(loc.index);
  3505. scope = stack[--i];
  3506. }
  3507. });
  3508. }
  3509. }
  3510. function newParameterDeclarationScope() {
  3511. return new ExpressionScope(kParameterDeclaration);
  3512. }
  3513. function newArrowHeadScope() {
  3514. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  3515. }
  3516. function newAsyncArrowScope() {
  3517. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  3518. }
  3519. function newExpressionScope() {
  3520. return new ExpressionScope();
  3521. }
  3522. const
  3523. PARAM = 0b0000,
  3524. PARAM_YIELD = 0b0001,
  3525. PARAM_AWAIT = 0b0010,
  3526. PARAM_RETURN = 0b0100,
  3527. PARAM_IN = 0b1000;
  3528. class ProductionParameterHandler {
  3529. constructor() {
  3530. this.stacks = [];
  3531. }
  3532. enter(flags) {
  3533. this.stacks.push(flags);
  3534. }
  3535. exit() {
  3536. this.stacks.pop();
  3537. }
  3538. currentFlags() {
  3539. return this.stacks[this.stacks.length - 1];
  3540. }
  3541. get hasAwait() {
  3542. return (this.currentFlags() & PARAM_AWAIT) > 0;
  3543. }
  3544. get hasYield() {
  3545. return (this.currentFlags() & PARAM_YIELD) > 0;
  3546. }
  3547. get hasReturn() {
  3548. return (this.currentFlags() & PARAM_RETURN) > 0;
  3549. }
  3550. get hasIn() {
  3551. return (this.currentFlags() & PARAM_IN) > 0;
  3552. }
  3553. }
  3554. function functionFlags(isAsync, isGenerator) {
  3555. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  3556. }
  3557. class UtilParser extends Tokenizer {
  3558. addExtra(node, key, value, enumerable = true) {
  3559. if (!node) return;
  3560. const extra = node.extra = node.extra || {};
  3561. if (enumerable) {
  3562. extra[key] = value;
  3563. } else {
  3564. Object.defineProperty(extra, key, {
  3565. enumerable,
  3566. value
  3567. });
  3568. }
  3569. }
  3570. isContextual(token) {
  3571. return this.state.type === token && !this.state.containsEsc;
  3572. }
  3573. isUnparsedContextual(nameStart, name) {
  3574. const nameEnd = nameStart + name.length;
  3575. if (this.input.slice(nameStart, nameEnd) === name) {
  3576. const nextCh = this.input.charCodeAt(nameEnd);
  3577. return !(isIdentifierChar(nextCh) ||
  3578. (nextCh & 0xfc00) === 0xd800);
  3579. }
  3580. return false;
  3581. }
  3582. isLookaheadContextual(name) {
  3583. const next = this.nextTokenStart();
  3584. return this.isUnparsedContextual(next, name);
  3585. }
  3586. eatContextual(token) {
  3587. if (this.isContextual(token)) {
  3588. this.next();
  3589. return true;
  3590. }
  3591. return false;
  3592. }
  3593. expectContextual(token, toParseError) {
  3594. if (!this.eatContextual(token)) {
  3595. if (toParseError != null) {
  3596. throw this.raise(toParseError, {
  3597. at: this.state.startLoc
  3598. });
  3599. }
  3600. throw this.unexpected(null, token);
  3601. }
  3602. }
  3603. canInsertSemicolon() {
  3604. return this.match(137) || this.match(8) || this.hasPrecedingLineBreak();
  3605. }
  3606. hasPrecedingLineBreak() {
  3607. return lineBreak.test(this.input.slice(this.state.lastTokEndLoc.index, this.state.start));
  3608. }
  3609. hasFollowingLineBreak() {
  3610. skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
  3611. return skipWhiteSpaceToLineBreak.test(this.input);
  3612. }
  3613. isLineTerminator() {
  3614. return this.eat(13) || this.canInsertSemicolon();
  3615. }
  3616. semicolon(allowAsi = true) {
  3617. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3618. this.raise(Errors.MissingSemicolon, {
  3619. at: this.state.lastTokEndLoc
  3620. });
  3621. }
  3622. expect(type, loc) {
  3623. this.eat(type) || this.unexpected(loc, type);
  3624. }
  3625. tryParse(fn, oldState = this.state.clone()) {
  3626. const abortSignal = {
  3627. node: null
  3628. };
  3629. try {
  3630. const node = fn((node = null) => {
  3631. abortSignal.node = node;
  3632. throw abortSignal;
  3633. });
  3634. if (this.state.errors.length > oldState.errors.length) {
  3635. const failState = this.state;
  3636. this.state = oldState;
  3637. this.state.tokensLength = failState.tokensLength;
  3638. return {
  3639. node,
  3640. error: failState.errors[oldState.errors.length],
  3641. thrown: false,
  3642. aborted: false,
  3643. failState
  3644. };
  3645. }
  3646. return {
  3647. node,
  3648. error: null,
  3649. thrown: false,
  3650. aborted: false,
  3651. failState: null
  3652. };
  3653. } catch (error) {
  3654. const failState = this.state;
  3655. this.state = oldState;
  3656. if (error instanceof SyntaxError) {
  3657. return {
  3658. node: null,
  3659. error,
  3660. thrown: true,
  3661. aborted: false,
  3662. failState
  3663. };
  3664. }
  3665. if (error === abortSignal) {
  3666. return {
  3667. node: abortSignal.node,
  3668. error: null,
  3669. thrown: false,
  3670. aborted: true,
  3671. failState
  3672. };
  3673. }
  3674. throw error;
  3675. }
  3676. }
  3677. checkExpressionErrors(refExpressionErrors, andThrow) {
  3678. if (!refExpressionErrors) return false;
  3679. const {
  3680. shorthandAssignLoc,
  3681. doubleProtoLoc,
  3682. privateKeyLoc,
  3683. optionalParametersLoc
  3684. } = refExpressionErrors;
  3685. const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc;
  3686. if (!andThrow) {
  3687. return hasErrors;
  3688. }
  3689. if (shorthandAssignLoc != null) {
  3690. this.raise(Errors.InvalidCoverInitializedName, {
  3691. at: shorthandAssignLoc
  3692. });
  3693. }
  3694. if (doubleProtoLoc != null) {
  3695. this.raise(Errors.DuplicateProto, {
  3696. at: doubleProtoLoc
  3697. });
  3698. }
  3699. if (privateKeyLoc != null) {
  3700. this.raise(Errors.UnexpectedPrivateField, {
  3701. at: privateKeyLoc
  3702. });
  3703. }
  3704. if (optionalParametersLoc != null) {
  3705. this.unexpected(optionalParametersLoc);
  3706. }
  3707. }
  3708. isLiteralPropertyName() {
  3709. return tokenIsLiteralPropertyName(this.state.type);
  3710. }
  3711. isPrivateName(node) {
  3712. return node.type === "PrivateName";
  3713. }
  3714. getPrivateNameSV(node) {
  3715. return node.id.name;
  3716. }
  3717. hasPropertyAsPrivateName(node) {
  3718. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3719. }
  3720. isOptionalChain(node) {
  3721. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  3722. }
  3723. isObjectProperty(node) {
  3724. return node.type === "ObjectProperty";
  3725. }
  3726. isObjectMethod(node) {
  3727. return node.type === "ObjectMethod";
  3728. }
  3729. initializeScopes(inModule = this.options.sourceType === "module") {
  3730. const oldLabels = this.state.labels;
  3731. this.state.labels = [];
  3732. const oldExportedIdentifiers = this.exportedIdentifiers;
  3733. this.exportedIdentifiers = new Set();
  3734. const oldInModule = this.inModule;
  3735. this.inModule = inModule;
  3736. const oldScope = this.scope;
  3737. const ScopeHandler = this.getScopeHandler();
  3738. this.scope = new ScopeHandler(this, inModule);
  3739. const oldProdParam = this.prodParam;
  3740. this.prodParam = new ProductionParameterHandler();
  3741. const oldClassScope = this.classScope;
  3742. this.classScope = new ClassScopeHandler(this);
  3743. const oldExpressionScope = this.expressionScope;
  3744. this.expressionScope = new ExpressionScopeHandler(this);
  3745. return () => {
  3746. this.state.labels = oldLabels;
  3747. this.exportedIdentifiers = oldExportedIdentifiers;
  3748. this.inModule = oldInModule;
  3749. this.scope = oldScope;
  3750. this.prodParam = oldProdParam;
  3751. this.classScope = oldClassScope;
  3752. this.expressionScope = oldExpressionScope;
  3753. };
  3754. }
  3755. enterInitialScopes() {
  3756. let paramFlags = PARAM;
  3757. if (this.inModule) {
  3758. paramFlags |= PARAM_AWAIT;
  3759. }
  3760. this.scope.enter(SCOPE_PROGRAM);
  3761. this.prodParam.enter(paramFlags);
  3762. }
  3763. checkDestructuringPrivate(refExpressionErrors) {
  3764. const {
  3765. privateKeyLoc
  3766. } = refExpressionErrors;
  3767. if (privateKeyLoc !== null) {
  3768. this.expectPlugin("destructuringPrivate", privateKeyLoc);
  3769. }
  3770. }
  3771. }
  3772. class ExpressionErrors {
  3773. constructor() {
  3774. this.shorthandAssignLoc = null;
  3775. this.doubleProtoLoc = null;
  3776. this.privateKeyLoc = null;
  3777. this.optionalParametersLoc = null;
  3778. }
  3779. }
  3780. class Node {
  3781. constructor(parser, pos, loc) {
  3782. this.type = "";
  3783. this.start = pos;
  3784. this.end = 0;
  3785. this.loc = new SourceLocation(loc);
  3786. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  3787. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  3788. }
  3789. }
  3790. const NodePrototype = Node.prototype;
  3791. {
  3792. NodePrototype.__clone = function () {
  3793. const newNode = new Node(undefined, this.start, this.loc.start);
  3794. const keys = Object.keys(this);
  3795. for (let i = 0, length = keys.length; i < length; i++) {
  3796. const key = keys[i];
  3797. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  3798. newNode[key] = this[key];
  3799. }
  3800. }
  3801. return newNode;
  3802. };
  3803. }
  3804. function clonePlaceholder(node) {
  3805. return cloneIdentifier(node);
  3806. }
  3807. function cloneIdentifier(node) {
  3808. const {
  3809. type,
  3810. start,
  3811. end,
  3812. loc,
  3813. range,
  3814. extra,
  3815. name
  3816. } = node;
  3817. const cloned = Object.create(NodePrototype);
  3818. cloned.type = type;
  3819. cloned.start = start;
  3820. cloned.end = end;
  3821. cloned.loc = loc;
  3822. cloned.range = range;
  3823. cloned.extra = extra;
  3824. cloned.name = name;
  3825. if (type === "Placeholder") {
  3826. cloned.expectedNode = node.expectedNode;
  3827. }
  3828. return cloned;
  3829. }
  3830. function cloneStringLiteral(node) {
  3831. const {
  3832. type,
  3833. start,
  3834. end,
  3835. loc,
  3836. range,
  3837. extra
  3838. } = node;
  3839. if (type === "Placeholder") {
  3840. return clonePlaceholder(node);
  3841. }
  3842. const cloned = Object.create(NodePrototype);
  3843. cloned.type = type;
  3844. cloned.start = start;
  3845. cloned.end = end;
  3846. cloned.loc = loc;
  3847. cloned.range = range;
  3848. if (node.raw !== undefined) {
  3849. cloned.raw = node.raw;
  3850. } else {
  3851. cloned.extra = extra;
  3852. }
  3853. cloned.value = node.value;
  3854. return cloned;
  3855. }
  3856. class NodeUtils extends UtilParser {
  3857. startNode() {
  3858. return new Node(this, this.state.start, this.state.startLoc);
  3859. }
  3860. startNodeAt(loc) {
  3861. return new Node(this, loc.index, loc);
  3862. }
  3863. startNodeAtNode(type) {
  3864. return this.startNodeAt(type.loc.start);
  3865. }
  3866. finishNode(node, type) {
  3867. return this.finishNodeAt(node, type, this.state.lastTokEndLoc);
  3868. }
  3869. finishNodeAt(node, type, endLoc) {
  3870. node.type = type;
  3871. node.end = endLoc.index;
  3872. node.loc.end = endLoc;
  3873. if (this.options.ranges) node.range[1] = endLoc.index;
  3874. if (this.options.attachComment) this.processComment(node);
  3875. return node;
  3876. }
  3877. resetStartLocation(node, startLoc) {
  3878. node.start = startLoc.index;
  3879. node.loc.start = startLoc;
  3880. if (this.options.ranges) node.range[0] = startLoc.index;
  3881. }
  3882. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  3883. node.end = endLoc.index;
  3884. node.loc.end = endLoc;
  3885. if (this.options.ranges) node.range[1] = endLoc.index;
  3886. }
  3887. resetStartLocationFromNode(node, locationNode) {
  3888. this.resetStartLocation(node, locationNode.loc.start);
  3889. }
  3890. }
  3891. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  3892. const FlowErrors = ParseErrorEnum`flow`({
  3893. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  3894. 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.",
  3895. AssignReservedType: ({
  3896. reservedType
  3897. }) => `Cannot overwrite reserved type ${reservedType}.`,
  3898. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  3899. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  3900. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  3901. EnumBooleanMemberNotInitialized: ({
  3902. memberName,
  3903. enumName
  3904. }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  3905. EnumDuplicateMemberName: ({
  3906. memberName,
  3907. enumName
  3908. }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  3909. EnumInconsistentMemberValues: ({
  3910. enumName
  3911. }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  3912. EnumInvalidExplicitType: ({
  3913. invalidEnumType,
  3914. enumName
  3915. }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3916. EnumInvalidExplicitTypeUnknownSupplied: ({
  3917. enumName
  3918. }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3919. EnumInvalidMemberInitializerPrimaryType: ({
  3920. enumName,
  3921. memberName,
  3922. explicitType
  3923. }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  3924. EnumInvalidMemberInitializerSymbolType: ({
  3925. enumName,
  3926. memberName
  3927. }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  3928. EnumInvalidMemberInitializerUnknownType: ({
  3929. enumName,
  3930. memberName
  3931. }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  3932. EnumInvalidMemberName: ({
  3933. enumName,
  3934. memberName,
  3935. suggestion
  3936. }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  3937. EnumNumberMemberNotInitialized: ({
  3938. enumName,
  3939. memberName
  3940. }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  3941. EnumStringMemberInconsistentlyInitailized: ({
  3942. enumName
  3943. }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  3944. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  3945. ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  3946. 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.",
  3947. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  3948. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  3949. InexactVariance: "Explicit inexact syntax cannot have variance.",
  3950. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  3951. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  3952. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  3953. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  3954. PatternIsOptional: Object.assign({
  3955. message: "A binding pattern parameter cannot be optional in an implementation signature."
  3956. }, {
  3957. reasonCode: "OptionalBindingPattern"
  3958. }),
  3959. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  3960. SpreadVariance: "Spread properties cannot have variance.",
  3961. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  3962. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  3963. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  3964. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  3965. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  3966. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  3967. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  3968. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  3969. UnexpectedReservedType: ({
  3970. reservedType
  3971. }) => `Unexpected reserved type ${reservedType}.`,
  3972. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  3973. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  3974. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  3975. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  3976. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  3977. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  3978. UnsupportedDeclareExportKind: ({
  3979. unsupportedExportKind,
  3980. suggestion
  3981. }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  3982. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  3983. UnterminatedFlowComment: "Unterminated flow-comment."
  3984. });
  3985. function isEsModuleType(bodyElement) {
  3986. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  3987. }
  3988. function hasTypeImportKind(node) {
  3989. return node.importKind === "type" || node.importKind === "typeof";
  3990. }
  3991. function isMaybeDefaultImport(type) {
  3992. return tokenIsKeywordOrIdentifier(type) && type !== 97;
  3993. }
  3994. const exportSuggestions = {
  3995. const: "declare export var",
  3996. let: "declare export var",
  3997. type: "export type",
  3998. interface: "export interface"
  3999. };
  4000. function partition(list, test) {
  4001. const list1 = [];
  4002. const list2 = [];
  4003. for (let i = 0; i < list.length; i++) {
  4004. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  4005. }
  4006. return [list1, list2];
  4007. }
  4008. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  4009. var flow = (superClass => class FlowParserMixin extends superClass {
  4010. constructor(...args) {
  4011. super(...args);
  4012. this.flowPragma = undefined;
  4013. }
  4014. getScopeHandler() {
  4015. return FlowScopeHandler;
  4016. }
  4017. shouldParseTypes() {
  4018. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  4019. }
  4020. shouldParseEnums() {
  4021. return !!this.getPluginOption("flow", "enums");
  4022. }
  4023. finishToken(type, val) {
  4024. if (type !== 131 && type !== 13 && type !== 28) {
  4025. if (this.flowPragma === undefined) {
  4026. this.flowPragma = null;
  4027. }
  4028. }
  4029. return super.finishToken(type, val);
  4030. }
  4031. addComment(comment) {
  4032. if (this.flowPragma === undefined) {
  4033. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  4034. if (!matches) ; else if (matches[1] === "flow") {
  4035. this.flowPragma = "flow";
  4036. } else if (matches[1] === "noflow") {
  4037. this.flowPragma = "noflow";
  4038. } else {
  4039. throw new Error("Unexpected flow pragma");
  4040. }
  4041. }
  4042. return super.addComment(comment);
  4043. }
  4044. flowParseTypeInitialiser(tok) {
  4045. const oldInType = this.state.inType;
  4046. this.state.inType = true;
  4047. this.expect(tok || 14);
  4048. const type = this.flowParseType();
  4049. this.state.inType = oldInType;
  4050. return type;
  4051. }
  4052. flowParsePredicate() {
  4053. const node = this.startNode();
  4054. const moduloLoc = this.state.startLoc;
  4055. this.next();
  4056. this.expectContextual(108);
  4057. if (this.state.lastTokStart > moduloLoc.index + 1) {
  4058. this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, {
  4059. at: moduloLoc
  4060. });
  4061. }
  4062. if (this.eat(10)) {
  4063. node.value = super.parseExpression();
  4064. this.expect(11);
  4065. return this.finishNode(node, "DeclaredPredicate");
  4066. } else {
  4067. return this.finishNode(node, "InferredPredicate");
  4068. }
  4069. }
  4070. flowParseTypeAndPredicateInitialiser() {
  4071. const oldInType = this.state.inType;
  4072. this.state.inType = true;
  4073. this.expect(14);
  4074. let type = null;
  4075. let predicate = null;
  4076. if (this.match(54)) {
  4077. this.state.inType = oldInType;
  4078. predicate = this.flowParsePredicate();
  4079. } else {
  4080. type = this.flowParseType();
  4081. this.state.inType = oldInType;
  4082. if (this.match(54)) {
  4083. predicate = this.flowParsePredicate();
  4084. }
  4085. }
  4086. return [type, predicate];
  4087. }
  4088. flowParseDeclareClass(node) {
  4089. this.next();
  4090. this.flowParseInterfaceish(node, true);
  4091. return this.finishNode(node, "DeclareClass");
  4092. }
  4093. flowParseDeclareFunction(node) {
  4094. this.next();
  4095. const id = node.id = this.parseIdentifier();
  4096. const typeNode = this.startNode();
  4097. const typeContainer = this.startNode();
  4098. if (this.match(47)) {
  4099. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4100. } else {
  4101. typeNode.typeParameters = null;
  4102. }
  4103. this.expect(10);
  4104. const tmp = this.flowParseFunctionTypeParams();
  4105. typeNode.params = tmp.params;
  4106. typeNode.rest = tmp.rest;
  4107. typeNode.this = tmp._this;
  4108. this.expect(11);
  4109. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4110. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4111. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4112. this.resetEndLocation(id);
  4113. this.semicolon();
  4114. this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.loc.start);
  4115. return this.finishNode(node, "DeclareFunction");
  4116. }
  4117. flowParseDeclare(node, insideModule) {
  4118. if (this.match(80)) {
  4119. return this.flowParseDeclareClass(node);
  4120. } else if (this.match(68)) {
  4121. return this.flowParseDeclareFunction(node);
  4122. } else if (this.match(74)) {
  4123. return this.flowParseDeclareVariable(node);
  4124. } else if (this.eatContextual(125)) {
  4125. if (this.match(16)) {
  4126. return this.flowParseDeclareModuleExports(node);
  4127. } else {
  4128. if (insideModule) {
  4129. this.raise(FlowErrors.NestedDeclareModule, {
  4130. at: this.state.lastTokStartLoc
  4131. });
  4132. }
  4133. return this.flowParseDeclareModule(node);
  4134. }
  4135. } else if (this.isContextual(128)) {
  4136. return this.flowParseDeclareTypeAlias(node);
  4137. } else if (this.isContextual(129)) {
  4138. return this.flowParseDeclareOpaqueType(node);
  4139. } else if (this.isContextual(127)) {
  4140. return this.flowParseDeclareInterface(node);
  4141. } else if (this.match(82)) {
  4142. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4143. } else {
  4144. throw this.unexpected();
  4145. }
  4146. }
  4147. flowParseDeclareVariable(node) {
  4148. this.next();
  4149. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4150. this.scope.declareName(node.id.name, BIND_VAR, node.id.loc.start);
  4151. this.semicolon();
  4152. return this.finishNode(node, "DeclareVariable");
  4153. }
  4154. flowParseDeclareModule(node) {
  4155. this.scope.enter(SCOPE_OTHER);
  4156. if (this.match(131)) {
  4157. node.id = super.parseExprAtom();
  4158. } else {
  4159. node.id = this.parseIdentifier();
  4160. }
  4161. const bodyNode = node.body = this.startNode();
  4162. const body = bodyNode.body = [];
  4163. this.expect(5);
  4164. while (!this.match(8)) {
  4165. let bodyNode = this.startNode();
  4166. if (this.match(83)) {
  4167. this.next();
  4168. if (!this.isContextual(128) && !this.match(87)) {
  4169. this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, {
  4170. at: this.state.lastTokStartLoc
  4171. });
  4172. }
  4173. super.parseImport(bodyNode);
  4174. } else {
  4175. this.expectContextual(123, FlowErrors.UnsupportedStatementInDeclareModule);
  4176. bodyNode = this.flowParseDeclare(bodyNode, true);
  4177. }
  4178. body.push(bodyNode);
  4179. }
  4180. this.scope.exit();
  4181. this.expect(8);
  4182. this.finishNode(bodyNode, "BlockStatement");
  4183. let kind = null;
  4184. let hasModuleExport = false;
  4185. body.forEach(bodyElement => {
  4186. if (isEsModuleType(bodyElement)) {
  4187. if (kind === "CommonJS") {
  4188. this.raise(FlowErrors.AmbiguousDeclareModuleKind, {
  4189. at: bodyElement
  4190. });
  4191. }
  4192. kind = "ES";
  4193. } else if (bodyElement.type === "DeclareModuleExports") {
  4194. if (hasModuleExport) {
  4195. this.raise(FlowErrors.DuplicateDeclareModuleExports, {
  4196. at: bodyElement
  4197. });
  4198. }
  4199. if (kind === "ES") {
  4200. this.raise(FlowErrors.AmbiguousDeclareModuleKind, {
  4201. at: bodyElement
  4202. });
  4203. }
  4204. kind = "CommonJS";
  4205. hasModuleExport = true;
  4206. }
  4207. });
  4208. node.kind = kind || "CommonJS";
  4209. return this.finishNode(node, "DeclareModule");
  4210. }
  4211. flowParseDeclareExportDeclaration(node, insideModule) {
  4212. this.expect(82);
  4213. if (this.eat(65)) {
  4214. if (this.match(68) || this.match(80)) {
  4215. node.declaration = this.flowParseDeclare(this.startNode());
  4216. } else {
  4217. node.declaration = this.flowParseType();
  4218. this.semicolon();
  4219. }
  4220. node.default = true;
  4221. return this.finishNode(node, "DeclareExportDeclaration");
  4222. } else {
  4223. if (this.match(75) || this.isLet() || (this.isContextual(128) || this.isContextual(127)) && !insideModule) {
  4224. const label = this.state.value;
  4225. throw this.raise(FlowErrors.UnsupportedDeclareExportKind, {
  4226. at: this.state.startLoc,
  4227. unsupportedExportKind: label,
  4228. suggestion: exportSuggestions[label]
  4229. });
  4230. }
  4231. if (this.match(74) ||
  4232. this.match(68) ||
  4233. this.match(80) ||
  4234. this.isContextual(129)) {
  4235. node.declaration = this.flowParseDeclare(this.startNode());
  4236. node.default = false;
  4237. return this.finishNode(node, "DeclareExportDeclaration");
  4238. } else if (this.match(55) ||
  4239. this.match(5) ||
  4240. this.isContextual(127) ||
  4241. this.isContextual(128) ||
  4242. this.isContextual(129)) {
  4243. node = this.parseExport(node, null);
  4244. if (node.type === "ExportNamedDeclaration") {
  4245. node.type = "ExportDeclaration";
  4246. node.default = false;
  4247. delete node.exportKind;
  4248. }
  4249. node.type = "Declare" + node.type;
  4250. return node;
  4251. }
  4252. }
  4253. throw this.unexpected();
  4254. }
  4255. flowParseDeclareModuleExports(node) {
  4256. this.next();
  4257. this.expectContextual(109);
  4258. node.typeAnnotation = this.flowParseTypeAnnotation();
  4259. this.semicolon();
  4260. return this.finishNode(node, "DeclareModuleExports");
  4261. }
  4262. flowParseDeclareTypeAlias(node) {
  4263. this.next();
  4264. const finished = this.flowParseTypeAlias(node);
  4265. finished.type = "DeclareTypeAlias";
  4266. return finished;
  4267. }
  4268. flowParseDeclareOpaqueType(node) {
  4269. this.next();
  4270. const finished = this.flowParseOpaqueType(node, true);
  4271. finished.type = "DeclareOpaqueType";
  4272. return finished;
  4273. }
  4274. flowParseDeclareInterface(node) {
  4275. this.next();
  4276. this.flowParseInterfaceish(node);
  4277. return this.finishNode(node, "DeclareInterface");
  4278. }
  4279. flowParseInterfaceish(node, isClass = false) {
  4280. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4281. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.loc.start);
  4282. if (this.match(47)) {
  4283. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4284. } else {
  4285. node.typeParameters = null;
  4286. }
  4287. node.extends = [];
  4288. node.implements = [];
  4289. node.mixins = [];
  4290. if (this.eat(81)) {
  4291. do {
  4292. node.extends.push(this.flowParseInterfaceExtends());
  4293. } while (!isClass && this.eat(12));
  4294. }
  4295. if (this.isContextual(115)) {
  4296. this.next();
  4297. do {
  4298. node.mixins.push(this.flowParseInterfaceExtends());
  4299. } while (this.eat(12));
  4300. }
  4301. if (this.isContextual(111)) {
  4302. this.next();
  4303. do {
  4304. node.implements.push(this.flowParseInterfaceExtends());
  4305. } while (this.eat(12));
  4306. }
  4307. node.body = this.flowParseObjectType({
  4308. allowStatic: isClass,
  4309. allowExact: false,
  4310. allowSpread: false,
  4311. allowProto: isClass,
  4312. allowInexact: false
  4313. });
  4314. }
  4315. flowParseInterfaceExtends() {
  4316. const node = this.startNode();
  4317. node.id = this.flowParseQualifiedTypeIdentifier();
  4318. if (this.match(47)) {
  4319. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4320. } else {
  4321. node.typeParameters = null;
  4322. }
  4323. return this.finishNode(node, "InterfaceExtends");
  4324. }
  4325. flowParseInterface(node) {
  4326. this.flowParseInterfaceish(node);
  4327. return this.finishNode(node, "InterfaceDeclaration");
  4328. }
  4329. checkNotUnderscore(word) {
  4330. if (word === "_") {
  4331. this.raise(FlowErrors.UnexpectedReservedUnderscore, {
  4332. at: this.state.startLoc
  4333. });
  4334. }
  4335. }
  4336. checkReservedType(word, startLoc, declaration) {
  4337. if (!reservedTypes.has(word)) return;
  4338. this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, {
  4339. at: startLoc,
  4340. reservedType: word
  4341. });
  4342. }
  4343. flowParseRestrictedIdentifier(liberal, declaration) {
  4344. this.checkReservedType(this.state.value, this.state.startLoc, declaration);
  4345. return this.parseIdentifier(liberal);
  4346. }
  4347. flowParseTypeAlias(node) {
  4348. node.id = this.flowParseRestrictedIdentifier(false, true);
  4349. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.loc.start);
  4350. if (this.match(47)) {
  4351. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4352. } else {
  4353. node.typeParameters = null;
  4354. }
  4355. node.right = this.flowParseTypeInitialiser(29);
  4356. this.semicolon();
  4357. return this.finishNode(node, "TypeAlias");
  4358. }
  4359. flowParseOpaqueType(node, declare) {
  4360. this.expectContextual(128);
  4361. node.id = this.flowParseRestrictedIdentifier(true, true);
  4362. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.loc.start);
  4363. if (this.match(47)) {
  4364. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4365. } else {
  4366. node.typeParameters = null;
  4367. }
  4368. node.supertype = null;
  4369. if (this.match(14)) {
  4370. node.supertype = this.flowParseTypeInitialiser(14);
  4371. }
  4372. node.impltype = null;
  4373. if (!declare) {
  4374. node.impltype = this.flowParseTypeInitialiser(29);
  4375. }
  4376. this.semicolon();
  4377. return this.finishNode(node, "OpaqueType");
  4378. }
  4379. flowParseTypeParameter(requireDefault = false) {
  4380. const nodeStartLoc = this.state.startLoc;
  4381. const node = this.startNode();
  4382. const variance = this.flowParseVariance();
  4383. const ident = this.flowParseTypeAnnotatableIdentifier();
  4384. node.name = ident.name;
  4385. node.variance = variance;
  4386. node.bound = ident.typeAnnotation;
  4387. if (this.match(29)) {
  4388. this.eat(29);
  4389. node.default = this.flowParseType();
  4390. } else {
  4391. if (requireDefault) {
  4392. this.raise(FlowErrors.MissingTypeParamDefault, {
  4393. at: nodeStartLoc
  4394. });
  4395. }
  4396. }
  4397. return this.finishNode(node, "TypeParameter");
  4398. }
  4399. flowParseTypeParameterDeclaration() {
  4400. const oldInType = this.state.inType;
  4401. const node = this.startNode();
  4402. node.params = [];
  4403. this.state.inType = true;
  4404. if (this.match(47) || this.match(140)) {
  4405. this.next();
  4406. } else {
  4407. this.unexpected();
  4408. }
  4409. let defaultRequired = false;
  4410. do {
  4411. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4412. node.params.push(typeParameter);
  4413. if (typeParameter.default) {
  4414. defaultRequired = true;
  4415. }
  4416. if (!this.match(48)) {
  4417. this.expect(12);
  4418. }
  4419. } while (!this.match(48));
  4420. this.expect(48);
  4421. this.state.inType = oldInType;
  4422. return this.finishNode(node, "TypeParameterDeclaration");
  4423. }
  4424. flowParseTypeParameterInstantiation() {
  4425. const node = this.startNode();
  4426. const oldInType = this.state.inType;
  4427. node.params = [];
  4428. this.state.inType = true;
  4429. this.expect(47);
  4430. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4431. this.state.noAnonFunctionType = false;
  4432. while (!this.match(48)) {
  4433. node.params.push(this.flowParseType());
  4434. if (!this.match(48)) {
  4435. this.expect(12);
  4436. }
  4437. }
  4438. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4439. this.expect(48);
  4440. this.state.inType = oldInType;
  4441. return this.finishNode(node, "TypeParameterInstantiation");
  4442. }
  4443. flowParseTypeParameterInstantiationCallOrNew() {
  4444. const node = this.startNode();
  4445. const oldInType = this.state.inType;
  4446. node.params = [];
  4447. this.state.inType = true;
  4448. this.expect(47);
  4449. while (!this.match(48)) {
  4450. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4451. if (!this.match(48)) {
  4452. this.expect(12);
  4453. }
  4454. }
  4455. this.expect(48);
  4456. this.state.inType = oldInType;
  4457. return this.finishNode(node, "TypeParameterInstantiation");
  4458. }
  4459. flowParseInterfaceType() {
  4460. const node = this.startNode();
  4461. this.expectContextual(127);
  4462. node.extends = [];
  4463. if (this.eat(81)) {
  4464. do {
  4465. node.extends.push(this.flowParseInterfaceExtends());
  4466. } while (this.eat(12));
  4467. }
  4468. node.body = this.flowParseObjectType({
  4469. allowStatic: false,
  4470. allowExact: false,
  4471. allowSpread: false,
  4472. allowProto: false,
  4473. allowInexact: false
  4474. });
  4475. return this.finishNode(node, "InterfaceTypeAnnotation");
  4476. }
  4477. flowParseObjectPropertyKey() {
  4478. return this.match(132) || this.match(131) ? super.parseExprAtom() : this.parseIdentifier(true);
  4479. }
  4480. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4481. node.static = isStatic;
  4482. if (this.lookahead().type === 14) {
  4483. node.id = this.flowParseObjectPropertyKey();
  4484. node.key = this.flowParseTypeInitialiser();
  4485. } else {
  4486. node.id = null;
  4487. node.key = this.flowParseType();
  4488. }
  4489. this.expect(3);
  4490. node.value = this.flowParseTypeInitialiser();
  4491. node.variance = variance;
  4492. return this.finishNode(node, "ObjectTypeIndexer");
  4493. }
  4494. flowParseObjectTypeInternalSlot(node, isStatic) {
  4495. node.static = isStatic;
  4496. node.id = this.flowParseObjectPropertyKey();
  4497. this.expect(3);
  4498. this.expect(3);
  4499. if (this.match(47) || this.match(10)) {
  4500. node.method = true;
  4501. node.optional = false;
  4502. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4503. } else {
  4504. node.method = false;
  4505. if (this.eat(17)) {
  4506. node.optional = true;
  4507. }
  4508. node.value = this.flowParseTypeInitialiser();
  4509. }
  4510. return this.finishNode(node, "ObjectTypeInternalSlot");
  4511. }
  4512. flowParseObjectTypeMethodish(node) {
  4513. node.params = [];
  4514. node.rest = null;
  4515. node.typeParameters = null;
  4516. node.this = null;
  4517. if (this.match(47)) {
  4518. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4519. }
  4520. this.expect(10);
  4521. if (this.match(78)) {
  4522. node.this = this.flowParseFunctionTypeParam(true);
  4523. node.this.name = null;
  4524. if (!this.match(11)) {
  4525. this.expect(12);
  4526. }
  4527. }
  4528. while (!this.match(11) && !this.match(21)) {
  4529. node.params.push(this.flowParseFunctionTypeParam(false));
  4530. if (!this.match(11)) {
  4531. this.expect(12);
  4532. }
  4533. }
  4534. if (this.eat(21)) {
  4535. node.rest = this.flowParseFunctionTypeParam(false);
  4536. }
  4537. this.expect(11);
  4538. node.returnType = this.flowParseTypeInitialiser();
  4539. return this.finishNode(node, "FunctionTypeAnnotation");
  4540. }
  4541. flowParseObjectTypeCallProperty(node, isStatic) {
  4542. const valueNode = this.startNode();
  4543. node.static = isStatic;
  4544. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4545. return this.finishNode(node, "ObjectTypeCallProperty");
  4546. }
  4547. flowParseObjectType({
  4548. allowStatic,
  4549. allowExact,
  4550. allowSpread,
  4551. allowProto,
  4552. allowInexact
  4553. }) {
  4554. const oldInType = this.state.inType;
  4555. this.state.inType = true;
  4556. const nodeStart = this.startNode();
  4557. nodeStart.callProperties = [];
  4558. nodeStart.properties = [];
  4559. nodeStart.indexers = [];
  4560. nodeStart.internalSlots = [];
  4561. let endDelim;
  4562. let exact;
  4563. let inexact = false;
  4564. if (allowExact && this.match(6)) {
  4565. this.expect(6);
  4566. endDelim = 9;
  4567. exact = true;
  4568. } else {
  4569. this.expect(5);
  4570. endDelim = 8;
  4571. exact = false;
  4572. }
  4573. nodeStart.exact = exact;
  4574. while (!this.match(endDelim)) {
  4575. let isStatic = false;
  4576. let protoStartLoc = null;
  4577. let inexactStartLoc = null;
  4578. const node = this.startNode();
  4579. if (allowProto && this.isContextual(116)) {
  4580. const lookahead = this.lookahead();
  4581. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4582. this.next();
  4583. protoStartLoc = this.state.startLoc;
  4584. allowStatic = false;
  4585. }
  4586. }
  4587. if (allowStatic && this.isContextual(104)) {
  4588. const lookahead = this.lookahead();
  4589. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4590. this.next();
  4591. isStatic = true;
  4592. }
  4593. }
  4594. const variance = this.flowParseVariance();
  4595. if (this.eat(0)) {
  4596. if (protoStartLoc != null) {
  4597. this.unexpected(protoStartLoc);
  4598. }
  4599. if (this.eat(0)) {
  4600. if (variance) {
  4601. this.unexpected(variance.loc.start);
  4602. }
  4603. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4604. } else {
  4605. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4606. }
  4607. } else if (this.match(10) || this.match(47)) {
  4608. if (protoStartLoc != null) {
  4609. this.unexpected(protoStartLoc);
  4610. }
  4611. if (variance) {
  4612. this.unexpected(variance.loc.start);
  4613. }
  4614. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4615. } else {
  4616. let kind = "init";
  4617. if (this.isContextual(98) || this.isContextual(103)) {
  4618. const lookahead = this.lookahead();
  4619. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4620. kind = this.state.value;
  4621. this.next();
  4622. }
  4623. }
  4624. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4625. if (propOrInexact === null) {
  4626. inexact = true;
  4627. inexactStartLoc = this.state.lastTokStartLoc;
  4628. } else {
  4629. nodeStart.properties.push(propOrInexact);
  4630. }
  4631. }
  4632. this.flowObjectTypeSemicolon();
  4633. if (inexactStartLoc && !this.match(8) && !this.match(9)) {
  4634. this.raise(FlowErrors.UnexpectedExplicitInexactInObject, {
  4635. at: inexactStartLoc
  4636. });
  4637. }
  4638. }
  4639. this.expect(endDelim);
  4640. if (allowSpread) {
  4641. nodeStart.inexact = inexact;
  4642. }
  4643. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4644. this.state.inType = oldInType;
  4645. return out;
  4646. }
  4647. flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
  4648. if (this.eat(21)) {
  4649. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4650. if (isInexactToken) {
  4651. if (!allowSpread) {
  4652. this.raise(FlowErrors.InexactInsideNonObject, {
  4653. at: this.state.lastTokStartLoc
  4654. });
  4655. } else if (!allowInexact) {
  4656. this.raise(FlowErrors.InexactInsideExact, {
  4657. at: this.state.lastTokStartLoc
  4658. });
  4659. }
  4660. if (variance) {
  4661. this.raise(FlowErrors.InexactVariance, {
  4662. at: variance
  4663. });
  4664. }
  4665. return null;
  4666. }
  4667. if (!allowSpread) {
  4668. this.raise(FlowErrors.UnexpectedSpreadType, {
  4669. at: this.state.lastTokStartLoc
  4670. });
  4671. }
  4672. if (protoStartLoc != null) {
  4673. this.unexpected(protoStartLoc);
  4674. }
  4675. if (variance) {
  4676. this.raise(FlowErrors.SpreadVariance, {
  4677. at: variance
  4678. });
  4679. }
  4680. node.argument = this.flowParseType();
  4681. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4682. } else {
  4683. node.key = this.flowParseObjectPropertyKey();
  4684. node.static = isStatic;
  4685. node.proto = protoStartLoc != null;
  4686. node.kind = kind;
  4687. let optional = false;
  4688. if (this.match(47) || this.match(10)) {
  4689. node.method = true;
  4690. if (protoStartLoc != null) {
  4691. this.unexpected(protoStartLoc);
  4692. }
  4693. if (variance) {
  4694. this.unexpected(variance.loc.start);
  4695. }
  4696. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4697. if (kind === "get" || kind === "set") {
  4698. this.flowCheckGetterSetterParams(node);
  4699. }
  4700. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4701. this.raise(FlowErrors.ThisParamBannedInConstructor, {
  4702. at: node.value.this
  4703. });
  4704. }
  4705. } else {
  4706. if (kind !== "init") this.unexpected();
  4707. node.method = false;
  4708. if (this.eat(17)) {
  4709. optional = true;
  4710. }
  4711. node.value = this.flowParseTypeInitialiser();
  4712. node.variance = variance;
  4713. }
  4714. node.optional = optional;
  4715. return this.finishNode(node, "ObjectTypeProperty");
  4716. }
  4717. }
  4718. flowCheckGetterSetterParams(property) {
  4719. const paramCount = property.kind === "get" ? 0 : 1;
  4720. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4721. if (property.value.this) {
  4722. this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, {
  4723. at: property.value.this
  4724. });
  4725. }
  4726. if (length !== paramCount) {
  4727. this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, {
  4728. at: property
  4729. });
  4730. }
  4731. if (property.kind === "set" && property.value.rest) {
  4732. this.raise(Errors.BadSetterRestParameter, {
  4733. at: property
  4734. });
  4735. }
  4736. }
  4737. flowObjectTypeSemicolon() {
  4738. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4739. this.unexpected();
  4740. }
  4741. }
  4742. flowParseQualifiedTypeIdentifier(startLoc, id) {
  4743. var _startLoc;
  4744. (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
  4745. let node = id || this.flowParseRestrictedIdentifier(true);
  4746. while (this.eat(16)) {
  4747. const node2 = this.startNodeAt(startLoc);
  4748. node2.qualification = node;
  4749. node2.id = this.flowParseRestrictedIdentifier(true);
  4750. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4751. }
  4752. return node;
  4753. }
  4754. flowParseGenericType(startLoc, id) {
  4755. const node = this.startNodeAt(startLoc);
  4756. node.typeParameters = null;
  4757. node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);
  4758. if (this.match(47)) {
  4759. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4760. }
  4761. return this.finishNode(node, "GenericTypeAnnotation");
  4762. }
  4763. flowParseTypeofType() {
  4764. const node = this.startNode();
  4765. this.expect(87);
  4766. node.argument = this.flowParsePrimaryType();
  4767. return this.finishNode(node, "TypeofTypeAnnotation");
  4768. }
  4769. flowParseTupleType() {
  4770. const node = this.startNode();
  4771. node.types = [];
  4772. this.expect(0);
  4773. while (this.state.pos < this.length && !this.match(3)) {
  4774. node.types.push(this.flowParseType());
  4775. if (this.match(3)) break;
  4776. this.expect(12);
  4777. }
  4778. this.expect(3);
  4779. return this.finishNode(node, "TupleTypeAnnotation");
  4780. }
  4781. flowParseFunctionTypeParam(first) {
  4782. let name = null;
  4783. let optional = false;
  4784. let typeAnnotation = null;
  4785. const node = this.startNode();
  4786. const lh = this.lookahead();
  4787. const isThis = this.state.type === 78;
  4788. if (lh.type === 14 || lh.type === 17) {
  4789. if (isThis && !first) {
  4790. this.raise(FlowErrors.ThisParamMustBeFirst, {
  4791. at: node
  4792. });
  4793. }
  4794. name = this.parseIdentifier(isThis);
  4795. if (this.eat(17)) {
  4796. optional = true;
  4797. if (isThis) {
  4798. this.raise(FlowErrors.ThisParamMayNotBeOptional, {
  4799. at: node
  4800. });
  4801. }
  4802. }
  4803. typeAnnotation = this.flowParseTypeInitialiser();
  4804. } else {
  4805. typeAnnotation = this.flowParseType();
  4806. }
  4807. node.name = name;
  4808. node.optional = optional;
  4809. node.typeAnnotation = typeAnnotation;
  4810. return this.finishNode(node, "FunctionTypeParam");
  4811. }
  4812. reinterpretTypeAsFunctionTypeParam(type) {
  4813. const node = this.startNodeAt(type.loc.start);
  4814. node.name = null;
  4815. node.optional = false;
  4816. node.typeAnnotation = type;
  4817. return this.finishNode(node, "FunctionTypeParam");
  4818. }
  4819. flowParseFunctionTypeParams(params = []) {
  4820. let rest = null;
  4821. let _this = null;
  4822. if (this.match(78)) {
  4823. _this = this.flowParseFunctionTypeParam(true);
  4824. _this.name = null;
  4825. if (!this.match(11)) {
  4826. this.expect(12);
  4827. }
  4828. }
  4829. while (!this.match(11) && !this.match(21)) {
  4830. params.push(this.flowParseFunctionTypeParam(false));
  4831. if (!this.match(11)) {
  4832. this.expect(12);
  4833. }
  4834. }
  4835. if (this.eat(21)) {
  4836. rest = this.flowParseFunctionTypeParam(false);
  4837. }
  4838. return {
  4839. params,
  4840. rest,
  4841. _this
  4842. };
  4843. }
  4844. flowIdentToTypeAnnotation(startLoc, node, id) {
  4845. switch (id.name) {
  4846. case "any":
  4847. return this.finishNode(node, "AnyTypeAnnotation");
  4848. case "bool":
  4849. case "boolean":
  4850. return this.finishNode(node, "BooleanTypeAnnotation");
  4851. case "mixed":
  4852. return this.finishNode(node, "MixedTypeAnnotation");
  4853. case "empty":
  4854. return this.finishNode(node, "EmptyTypeAnnotation");
  4855. case "number":
  4856. return this.finishNode(node, "NumberTypeAnnotation");
  4857. case "string":
  4858. return this.finishNode(node, "StringTypeAnnotation");
  4859. case "symbol":
  4860. return this.finishNode(node, "SymbolTypeAnnotation");
  4861. default:
  4862. this.checkNotUnderscore(id.name);
  4863. return this.flowParseGenericType(startLoc, id);
  4864. }
  4865. }
  4866. flowParsePrimaryType() {
  4867. const startLoc = this.state.startLoc;
  4868. const node = this.startNode();
  4869. let tmp;
  4870. let type;
  4871. let isGroupedType = false;
  4872. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4873. switch (this.state.type) {
  4874. case 5:
  4875. return this.flowParseObjectType({
  4876. allowStatic: false,
  4877. allowExact: false,
  4878. allowSpread: true,
  4879. allowProto: false,
  4880. allowInexact: true
  4881. });
  4882. case 6:
  4883. return this.flowParseObjectType({
  4884. allowStatic: false,
  4885. allowExact: true,
  4886. allowSpread: true,
  4887. allowProto: false,
  4888. allowInexact: false
  4889. });
  4890. case 0:
  4891. this.state.noAnonFunctionType = false;
  4892. type = this.flowParseTupleType();
  4893. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4894. return type;
  4895. case 47:
  4896. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4897. this.expect(10);
  4898. tmp = this.flowParseFunctionTypeParams();
  4899. node.params = tmp.params;
  4900. node.rest = tmp.rest;
  4901. node.this = tmp._this;
  4902. this.expect(11);
  4903. this.expect(19);
  4904. node.returnType = this.flowParseType();
  4905. return this.finishNode(node, "FunctionTypeAnnotation");
  4906. case 10:
  4907. this.next();
  4908. if (!this.match(11) && !this.match(21)) {
  4909. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  4910. const token = this.lookahead().type;
  4911. isGroupedType = token !== 17 && token !== 14;
  4912. } else {
  4913. isGroupedType = true;
  4914. }
  4915. }
  4916. if (isGroupedType) {
  4917. this.state.noAnonFunctionType = false;
  4918. type = this.flowParseType();
  4919. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4920. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  4921. this.expect(11);
  4922. return type;
  4923. } else {
  4924. this.eat(12);
  4925. }
  4926. }
  4927. if (type) {
  4928. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  4929. } else {
  4930. tmp = this.flowParseFunctionTypeParams();
  4931. }
  4932. node.params = tmp.params;
  4933. node.rest = tmp.rest;
  4934. node.this = tmp._this;
  4935. this.expect(11);
  4936. this.expect(19);
  4937. node.returnType = this.flowParseType();
  4938. node.typeParameters = null;
  4939. return this.finishNode(node, "FunctionTypeAnnotation");
  4940. case 131:
  4941. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  4942. case 85:
  4943. case 86:
  4944. node.value = this.match(85);
  4945. this.next();
  4946. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  4947. case 53:
  4948. if (this.state.value === "-") {
  4949. this.next();
  4950. if (this.match(132)) {
  4951. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  4952. }
  4953. if (this.match(133)) {
  4954. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  4955. }
  4956. throw this.raise(FlowErrors.UnexpectedSubtractionOperand, {
  4957. at: this.state.startLoc
  4958. });
  4959. }
  4960. throw this.unexpected();
  4961. case 132:
  4962. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  4963. case 133:
  4964. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  4965. case 88:
  4966. this.next();
  4967. return this.finishNode(node, "VoidTypeAnnotation");
  4968. case 84:
  4969. this.next();
  4970. return this.finishNode(node, "NullLiteralTypeAnnotation");
  4971. case 78:
  4972. this.next();
  4973. return this.finishNode(node, "ThisTypeAnnotation");
  4974. case 55:
  4975. this.next();
  4976. return this.finishNode(node, "ExistsTypeAnnotation");
  4977. case 87:
  4978. return this.flowParseTypeofType();
  4979. default:
  4980. if (tokenIsKeyword(this.state.type)) {
  4981. const label = tokenLabelName(this.state.type);
  4982. this.next();
  4983. return super.createIdentifier(node, label);
  4984. } else if (tokenIsIdentifier(this.state.type)) {
  4985. if (this.isContextual(127)) {
  4986. return this.flowParseInterfaceType();
  4987. }
  4988. return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier());
  4989. }
  4990. }
  4991. throw this.unexpected();
  4992. }
  4993. flowParsePostfixType() {
  4994. const startLoc = this.state.startLoc;
  4995. let type = this.flowParsePrimaryType();
  4996. let seenOptionalIndexedAccess = false;
  4997. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  4998. const node = this.startNodeAt(startLoc);
  4999. const optional = this.eat(18);
  5000. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  5001. this.expect(0);
  5002. if (!optional && this.match(3)) {
  5003. node.elementType = type;
  5004. this.next();
  5005. type = this.finishNode(node, "ArrayTypeAnnotation");
  5006. } else {
  5007. node.objectType = type;
  5008. node.indexType = this.flowParseType();
  5009. this.expect(3);
  5010. if (seenOptionalIndexedAccess) {
  5011. node.optional = optional;
  5012. type = this.finishNode(
  5013. node, "OptionalIndexedAccessType");
  5014. } else {
  5015. type = this.finishNode(
  5016. node, "IndexedAccessType");
  5017. }
  5018. }
  5019. }
  5020. return type;
  5021. }
  5022. flowParsePrefixType() {
  5023. const node = this.startNode();
  5024. if (this.eat(17)) {
  5025. node.typeAnnotation = this.flowParsePrefixType();
  5026. return this.finishNode(node, "NullableTypeAnnotation");
  5027. } else {
  5028. return this.flowParsePostfixType();
  5029. }
  5030. }
  5031. flowParseAnonFunctionWithoutParens() {
  5032. const param = this.flowParsePrefixType();
  5033. if (!this.state.noAnonFunctionType && this.eat(19)) {
  5034. const node = this.startNodeAt(param.loc.start);
  5035. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  5036. node.rest = null;
  5037. node.this = null;
  5038. node.returnType = this.flowParseType();
  5039. node.typeParameters = null;
  5040. return this.finishNode(node, "FunctionTypeAnnotation");
  5041. }
  5042. return param;
  5043. }
  5044. flowParseIntersectionType() {
  5045. const node = this.startNode();
  5046. this.eat(45);
  5047. const type = this.flowParseAnonFunctionWithoutParens();
  5048. node.types = [type];
  5049. while (this.eat(45)) {
  5050. node.types.push(this.flowParseAnonFunctionWithoutParens());
  5051. }
  5052. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  5053. }
  5054. flowParseUnionType() {
  5055. const node = this.startNode();
  5056. this.eat(43);
  5057. const type = this.flowParseIntersectionType();
  5058. node.types = [type];
  5059. while (this.eat(43)) {
  5060. node.types.push(this.flowParseIntersectionType());
  5061. }
  5062. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  5063. }
  5064. flowParseType() {
  5065. const oldInType = this.state.inType;
  5066. this.state.inType = true;
  5067. const type = this.flowParseUnionType();
  5068. this.state.inType = oldInType;
  5069. return type;
  5070. }
  5071. flowParseTypeOrImplicitInstantiation() {
  5072. if (this.state.type === 130 && this.state.value === "_") {
  5073. const startLoc = this.state.startLoc;
  5074. const node = this.parseIdentifier();
  5075. return this.flowParseGenericType(startLoc, node);
  5076. } else {
  5077. return this.flowParseType();
  5078. }
  5079. }
  5080. flowParseTypeAnnotation() {
  5081. const node = this.startNode();
  5082. node.typeAnnotation = this.flowParseTypeInitialiser();
  5083. return this.finishNode(node, "TypeAnnotation");
  5084. }
  5085. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  5086. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  5087. if (this.match(14)) {
  5088. ident.typeAnnotation = this.flowParseTypeAnnotation();
  5089. this.resetEndLocation(ident);
  5090. }
  5091. return ident;
  5092. }
  5093. typeCastToParameter(node) {
  5094. node.expression.typeAnnotation = node.typeAnnotation;
  5095. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  5096. return node.expression;
  5097. }
  5098. flowParseVariance() {
  5099. let variance = null;
  5100. if (this.match(53)) {
  5101. variance = this.startNode();
  5102. if (this.state.value === "+") {
  5103. variance.kind = "plus";
  5104. } else {
  5105. variance.kind = "minus";
  5106. }
  5107. this.next();
  5108. return this.finishNode(variance, "Variance");
  5109. }
  5110. return variance;
  5111. }
  5112. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5113. if (allowExpressionBody) {
  5114. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5115. }
  5116. return super.parseFunctionBody(node, false, isMethod);
  5117. }
  5118. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5119. if (this.match(14)) {
  5120. const typeNode = this.startNode();
  5121. [typeNode.typeAnnotation,
  5122. node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5123. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5124. }
  5125. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  5126. }
  5127. parseStatementLike(flags) {
  5128. if (this.state.strict && this.isContextual(127)) {
  5129. const lookahead = this.lookahead();
  5130. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5131. const node = this.startNode();
  5132. this.next();
  5133. return this.flowParseInterface(node);
  5134. }
  5135. } else if (this.shouldParseEnums() && this.isContextual(124)) {
  5136. const node = this.startNode();
  5137. this.next();
  5138. return this.flowParseEnumDeclaration(node);
  5139. }
  5140. const stmt = super.parseStatementLike(flags);
  5141. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5142. this.flowPragma = null;
  5143. }
  5144. return stmt;
  5145. }
  5146. parseExpressionStatement(node, expr, decorators) {
  5147. if (expr.type === "Identifier") {
  5148. if (expr.name === "declare") {
  5149. if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
  5150. return this.flowParseDeclare(node);
  5151. }
  5152. } else if (tokenIsIdentifier(this.state.type)) {
  5153. if (expr.name === "interface") {
  5154. return this.flowParseInterface(node);
  5155. } else if (expr.name === "type") {
  5156. return this.flowParseTypeAlias(node);
  5157. } else if (expr.name === "opaque") {
  5158. return this.flowParseOpaqueType(node, false);
  5159. }
  5160. }
  5161. }
  5162. return super.parseExpressionStatement(node, expr, decorators);
  5163. }
  5164. shouldParseExportDeclaration() {
  5165. const {
  5166. type
  5167. } = this.state;
  5168. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 124) {
  5169. return !this.state.containsEsc;
  5170. }
  5171. return super.shouldParseExportDeclaration();
  5172. }
  5173. isExportDefaultSpecifier() {
  5174. const {
  5175. type
  5176. } = this.state;
  5177. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 124) {
  5178. return this.state.containsEsc;
  5179. }
  5180. return super.isExportDefaultSpecifier();
  5181. }
  5182. parseExportDefaultExpression() {
  5183. if (this.shouldParseEnums() && this.isContextual(124)) {
  5184. const node = this.startNode();
  5185. this.next();
  5186. return this.flowParseEnumDeclaration(node);
  5187. }
  5188. return super.parseExportDefaultExpression();
  5189. }
  5190. parseConditional(expr, startLoc, refExpressionErrors) {
  5191. if (!this.match(17)) return expr;
  5192. if (this.state.maybeInArrowParameters) {
  5193. const nextCh = this.lookaheadCharCode();
  5194. if (nextCh === 44 ||
  5195. nextCh === 61 ||
  5196. nextCh === 58 ||
  5197. nextCh === 41) {
  5198. this.setOptionalParametersError(refExpressionErrors);
  5199. return expr;
  5200. }
  5201. }
  5202. this.expect(17);
  5203. const state = this.state.clone();
  5204. const originalNoArrowAt = this.state.noArrowAt;
  5205. const node = this.startNodeAt(startLoc);
  5206. let {
  5207. consequent,
  5208. failed
  5209. } = this.tryParseConditionalConsequent();
  5210. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5211. if (failed || invalid.length > 0) {
  5212. const noArrowAt = [...originalNoArrowAt];
  5213. if (invalid.length > 0) {
  5214. this.state = state;
  5215. this.state.noArrowAt = noArrowAt;
  5216. for (let i = 0; i < invalid.length; i++) {
  5217. noArrowAt.push(invalid[i].start);
  5218. }
  5219. ({
  5220. consequent,
  5221. failed
  5222. } = this.tryParseConditionalConsequent());
  5223. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5224. }
  5225. if (failed && valid.length > 1) {
  5226. this.raise(FlowErrors.AmbiguousConditionalArrow, {
  5227. at: state.startLoc
  5228. });
  5229. }
  5230. if (failed && valid.length === 1) {
  5231. this.state = state;
  5232. noArrowAt.push(valid[0].start);
  5233. this.state.noArrowAt = noArrowAt;
  5234. ({
  5235. consequent,
  5236. failed
  5237. } = this.tryParseConditionalConsequent());
  5238. }
  5239. }
  5240. this.getArrowLikeExpressions(consequent, true);
  5241. this.state.noArrowAt = originalNoArrowAt;
  5242. this.expect(14);
  5243. node.test = expr;
  5244. node.consequent = consequent;
  5245. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5246. return this.finishNode(node, "ConditionalExpression");
  5247. }
  5248. tryParseConditionalConsequent() {
  5249. this.state.noArrowParamsConversionAt.push(this.state.start);
  5250. const consequent = this.parseMaybeAssignAllowIn();
  5251. const failed = !this.match(14);
  5252. this.state.noArrowParamsConversionAt.pop();
  5253. return {
  5254. consequent,
  5255. failed
  5256. };
  5257. }
  5258. getArrowLikeExpressions(node, disallowInvalid) {
  5259. const stack = [node];
  5260. const arrows = [];
  5261. while (stack.length !== 0) {
  5262. const node = stack.pop();
  5263. if (node.type === "ArrowFunctionExpression") {
  5264. if (node.typeParameters || !node.returnType) {
  5265. this.finishArrowValidation(node);
  5266. } else {
  5267. arrows.push(node);
  5268. }
  5269. stack.push(node.body);
  5270. } else if (node.type === "ConditionalExpression") {
  5271. stack.push(node.consequent);
  5272. stack.push(node.alternate);
  5273. }
  5274. }
  5275. if (disallowInvalid) {
  5276. arrows.forEach(node => this.finishArrowValidation(node));
  5277. return [arrows, []];
  5278. }
  5279. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5280. }
  5281. finishArrowValidation(node) {
  5282. var _node$extra;
  5283. this.toAssignableList(
  5284. node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
  5285. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  5286. super.checkParams(node, false, true);
  5287. this.scope.exit();
  5288. }
  5289. forwardNoArrowParamsConversionAt(node, parse) {
  5290. let result;
  5291. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5292. this.state.noArrowParamsConversionAt.push(this.state.start);
  5293. result = parse();
  5294. this.state.noArrowParamsConversionAt.pop();
  5295. } else {
  5296. result = parse();
  5297. }
  5298. return result;
  5299. }
  5300. parseParenItem(node, startLoc) {
  5301. node = super.parseParenItem(node, startLoc);
  5302. if (this.eat(17)) {
  5303. node.optional = true;
  5304. this.resetEndLocation(node);
  5305. }
  5306. if (this.match(14)) {
  5307. const typeCastNode = this.startNodeAt(startLoc);
  5308. typeCastNode.expression = node;
  5309. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5310. return this.finishNode(typeCastNode, "TypeCastExpression");
  5311. }
  5312. return node;
  5313. }
  5314. assertModuleNodeAllowed(node) {
  5315. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5316. return;
  5317. }
  5318. super.assertModuleNodeAllowed(node);
  5319. }
  5320. parseExport(node, decorators) {
  5321. const decl = super.parseExport(node, decorators);
  5322. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  5323. decl.exportKind = decl.exportKind || "value";
  5324. }
  5325. return decl;
  5326. }
  5327. parseExportDeclaration(node) {
  5328. if (this.isContextual(128)) {
  5329. node.exportKind = "type";
  5330. const declarationNode = this.startNode();
  5331. this.next();
  5332. if (this.match(5)) {
  5333. node.specifiers = this.parseExportSpecifiers(true);
  5334. super.parseExportFrom(node);
  5335. return null;
  5336. } else {
  5337. return this.flowParseTypeAlias(declarationNode);
  5338. }
  5339. } else if (this.isContextual(129)) {
  5340. node.exportKind = "type";
  5341. const declarationNode = this.startNode();
  5342. this.next();
  5343. return this.flowParseOpaqueType(declarationNode, false);
  5344. } else if (this.isContextual(127)) {
  5345. node.exportKind = "type";
  5346. const declarationNode = this.startNode();
  5347. this.next();
  5348. return this.flowParseInterface(declarationNode);
  5349. } else if (this.shouldParseEnums() && this.isContextual(124)) {
  5350. node.exportKind = "value";
  5351. const declarationNode = this.startNode();
  5352. this.next();
  5353. return this.flowParseEnumDeclaration(declarationNode);
  5354. } else {
  5355. return super.parseExportDeclaration(node);
  5356. }
  5357. }
  5358. eatExportStar(node) {
  5359. if (super.eatExportStar(node)) return true;
  5360. if (this.isContextual(128) && this.lookahead().type === 55) {
  5361. node.exportKind = "type";
  5362. this.next();
  5363. this.next();
  5364. return true;
  5365. }
  5366. return false;
  5367. }
  5368. maybeParseExportNamespaceSpecifier(node) {
  5369. const {
  5370. startLoc
  5371. } = this.state;
  5372. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5373. if (hasNamespace && node.exportKind === "type") {
  5374. this.unexpected(startLoc);
  5375. }
  5376. return hasNamespace;
  5377. }
  5378. parseClassId(node, isStatement, optionalId) {
  5379. super.parseClassId(node, isStatement, optionalId);
  5380. if (this.match(47)) {
  5381. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5382. }
  5383. }
  5384. parseClassMember(classBody, member, state) {
  5385. const {
  5386. startLoc
  5387. } = this.state;
  5388. if (this.isContextual(123)) {
  5389. if (super.parseClassMemberFromModifier(classBody, member)) {
  5390. return;
  5391. }
  5392. member.declare = true;
  5393. }
  5394. super.parseClassMember(classBody, member, state);
  5395. if (member.declare) {
  5396. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5397. this.raise(FlowErrors.DeclareClassElement, {
  5398. at: startLoc
  5399. });
  5400. } else if (member.value) {
  5401. this.raise(FlowErrors.DeclareClassFieldInitializer, {
  5402. at: member.value
  5403. });
  5404. }
  5405. }
  5406. }
  5407. isIterator(word) {
  5408. return word === "iterator" || word === "asyncIterator";
  5409. }
  5410. readIterator() {
  5411. const word = super.readWord1();
  5412. const fullWord = "@@" + word;
  5413. if (!this.isIterator(word) || !this.state.inType) {
  5414. this.raise(Errors.InvalidIdentifier, {
  5415. at: this.state.curPosition(),
  5416. identifierName: fullWord
  5417. });
  5418. }
  5419. this.finishToken(130, fullWord);
  5420. }
  5421. getTokenFromCode(code) {
  5422. const next = this.input.charCodeAt(this.state.pos + 1);
  5423. if (code === 123 && next === 124) {
  5424. return this.finishOp(6, 2);
  5425. } else if (this.state.inType && (code === 62 || code === 60)) {
  5426. return this.finishOp(code === 62 ? 48 : 47, 1);
  5427. } else if (this.state.inType && code === 63) {
  5428. if (next === 46) {
  5429. return this.finishOp(18, 2);
  5430. }
  5431. return this.finishOp(17, 1);
  5432. } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
  5433. this.state.pos += 2;
  5434. return this.readIterator();
  5435. } else {
  5436. return super.getTokenFromCode(code);
  5437. }
  5438. }
  5439. isAssignable(node, isBinding) {
  5440. if (node.type === "TypeCastExpression") {
  5441. return this.isAssignable(node.expression, isBinding);
  5442. } else {
  5443. return super.isAssignable(node, isBinding);
  5444. }
  5445. }
  5446. toAssignable(node, isLHS = false) {
  5447. if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") {
  5448. node.left = this.typeCastToParameter(node.left);
  5449. }
  5450. super.toAssignable(node, isLHS);
  5451. }
  5452. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  5453. for (let i = 0; i < exprList.length; i++) {
  5454. const expr = exprList[i];
  5455. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5456. exprList[i] = this.typeCastToParameter(expr);
  5457. }
  5458. }
  5459. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  5460. }
  5461. toReferencedList(exprList, isParenthesizedExpr) {
  5462. for (let i = 0; i < exprList.length; i++) {
  5463. var _expr$extra;
  5464. const expr = exprList[i];
  5465. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5466. this.raise(FlowErrors.TypeCastInPattern, {
  5467. at: expr.typeAnnotation
  5468. });
  5469. }
  5470. }
  5471. return exprList;
  5472. }
  5473. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5474. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5475. if (canBePattern && !this.state.maybeInArrowParameters) {
  5476. this.toReferencedList(node.elements);
  5477. }
  5478. return node;
  5479. }
  5480. isValidLVal(type, isParenthesized, binding) {
  5481. return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding);
  5482. }
  5483. parseClassProperty(node) {
  5484. if (this.match(14)) {
  5485. node.typeAnnotation = this.flowParseTypeAnnotation();
  5486. }
  5487. return super.parseClassProperty(node);
  5488. }
  5489. parseClassPrivateProperty(node) {
  5490. if (this.match(14)) {
  5491. node.typeAnnotation = this.flowParseTypeAnnotation();
  5492. }
  5493. return super.parseClassPrivateProperty(node);
  5494. }
  5495. isClassMethod() {
  5496. return this.match(47) || super.isClassMethod();
  5497. }
  5498. isClassProperty() {
  5499. return this.match(14) || super.isClassProperty();
  5500. }
  5501. isNonstaticConstructor(method) {
  5502. return !this.match(14) && super.isNonstaticConstructor(method);
  5503. }
  5504. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5505. if (method.variance) {
  5506. this.unexpected(method.variance.loc.start);
  5507. }
  5508. delete method.variance;
  5509. if (this.match(47)) {
  5510. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5511. }
  5512. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5513. if (method.params && isConstructor) {
  5514. const params = method.params;
  5515. if (params.length > 0 && this.isThisParam(params[0])) {
  5516. this.raise(FlowErrors.ThisParamBannedInConstructor, {
  5517. at: method
  5518. });
  5519. }
  5520. } else if (
  5521. method.type === "MethodDefinition" && isConstructor &&
  5522. method.value.params) {
  5523. const params = method.value.params;
  5524. if (params.length > 0 && this.isThisParam(params[0])) {
  5525. this.raise(FlowErrors.ThisParamBannedInConstructor, {
  5526. at: method
  5527. });
  5528. }
  5529. }
  5530. }
  5531. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5532. if (method.variance) {
  5533. this.unexpected(method.variance.loc.start);
  5534. }
  5535. delete method.variance;
  5536. if (this.match(47)) {
  5537. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5538. }
  5539. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5540. }
  5541. parseClassSuper(node) {
  5542. super.parseClassSuper(node);
  5543. if (node.superClass && this.match(47)) {
  5544. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  5545. }
  5546. if (this.isContextual(111)) {
  5547. this.next();
  5548. const implemented = node.implements = [];
  5549. do {
  5550. const node = this.startNode();
  5551. node.id = this.flowParseRestrictedIdentifier(true);
  5552. if (this.match(47)) {
  5553. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5554. } else {
  5555. node.typeParameters = null;
  5556. }
  5557. implemented.push(this.finishNode(node, "ClassImplements"));
  5558. } while (this.eat(12));
  5559. }
  5560. }
  5561. checkGetterSetterParams(method) {
  5562. super.checkGetterSetterParams(method);
  5563. const params = this.getObjectOrClassMethodParams(method);
  5564. if (params.length > 0) {
  5565. const param = params[0];
  5566. if (this.isThisParam(param) && method.kind === "get") {
  5567. this.raise(FlowErrors.GetterMayNotHaveThisParam, {
  5568. at: param
  5569. });
  5570. } else if (this.isThisParam(param)) {
  5571. this.raise(FlowErrors.SetterMayNotHaveThisParam, {
  5572. at: param
  5573. });
  5574. }
  5575. }
  5576. }
  5577. parsePropertyNamePrefixOperator(node) {
  5578. node.variance = this.flowParseVariance();
  5579. }
  5580. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5581. if (prop.variance) {
  5582. this.unexpected(prop.variance.loc.start);
  5583. }
  5584. delete prop.variance;
  5585. let typeParameters;
  5586. if (this.match(47) && !isAccessor) {
  5587. typeParameters = this.flowParseTypeParameterDeclaration();
  5588. if (!this.match(10)) this.unexpected();
  5589. }
  5590. const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5591. if (typeParameters) {
  5592. (result.value || result).typeParameters = typeParameters;
  5593. }
  5594. return result;
  5595. }
  5596. parseAssignableListItemTypes(param) {
  5597. if (this.eat(17)) {
  5598. if (param.type !== "Identifier") {
  5599. this.raise(FlowErrors.PatternIsOptional, {
  5600. at: param
  5601. });
  5602. }
  5603. if (this.isThisParam(param)) {
  5604. this.raise(FlowErrors.ThisParamMayNotBeOptional, {
  5605. at: param
  5606. });
  5607. }
  5608. param.optional = true;
  5609. }
  5610. if (this.match(14)) {
  5611. param.typeAnnotation = this.flowParseTypeAnnotation();
  5612. } else if (this.isThisParam(param)) {
  5613. this.raise(FlowErrors.ThisParamAnnotationRequired, {
  5614. at: param
  5615. });
  5616. }
  5617. if (this.match(29) && this.isThisParam(param)) {
  5618. this.raise(FlowErrors.ThisParamNoDefault, {
  5619. at: param
  5620. });
  5621. }
  5622. this.resetEndLocation(param);
  5623. return param;
  5624. }
  5625. parseMaybeDefault(startLoc, left) {
  5626. const node = super.parseMaybeDefault(startLoc, left);
  5627. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5628. this.raise(FlowErrors.TypeBeforeInitializer, {
  5629. at: node.typeAnnotation
  5630. });
  5631. }
  5632. return node;
  5633. }
  5634. shouldParseDefaultImport(node) {
  5635. if (!hasTypeImportKind(node)) {
  5636. return super.shouldParseDefaultImport(node);
  5637. }
  5638. return isMaybeDefaultImport(this.state.type);
  5639. }
  5640. checkImportReflection(node) {
  5641. super.checkImportReflection(node);
  5642. if (node.module && node.importKind !== "value") {
  5643. this.raise(FlowErrors.ImportReflectionHasImportType, {
  5644. at: node.specifiers[0].loc.start
  5645. });
  5646. }
  5647. }
  5648. parseImportSpecifierLocal(node, specifier, type) {
  5649. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5650. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  5651. }
  5652. maybeParseDefaultImportSpecifier(node) {
  5653. node.importKind = "value";
  5654. let kind = null;
  5655. if (this.match(87)) {
  5656. kind = "typeof";
  5657. } else if (this.isContextual(128)) {
  5658. kind = "type";
  5659. }
  5660. if (kind) {
  5661. const lh = this.lookahead();
  5662. const {
  5663. type
  5664. } = lh;
  5665. if (kind === "type" && type === 55) {
  5666. this.unexpected(null, lh.type);
  5667. }
  5668. if (isMaybeDefaultImport(type) || type === 5 || type === 55) {
  5669. this.next();
  5670. node.importKind = kind;
  5671. }
  5672. }
  5673. return super.maybeParseDefaultImportSpecifier(node);
  5674. }
  5675. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport,
  5676. isMaybeTypeOnly,
  5677. bindingType) {
  5678. const firstIdent = specifier.imported;
  5679. let specifierTypeKind = null;
  5680. if (firstIdent.type === "Identifier") {
  5681. if (firstIdent.name === "type") {
  5682. specifierTypeKind = "type";
  5683. } else if (firstIdent.name === "typeof") {
  5684. specifierTypeKind = "typeof";
  5685. }
  5686. }
  5687. let isBinding = false;
  5688. if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
  5689. const as_ident = this.parseIdentifier(true);
  5690. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5691. specifier.imported = as_ident;
  5692. specifier.importKind = specifierTypeKind;
  5693. specifier.local = cloneIdentifier(as_ident);
  5694. } else {
  5695. specifier.imported = firstIdent;
  5696. specifier.importKind = null;
  5697. specifier.local = this.parseIdentifier();
  5698. }
  5699. } else {
  5700. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5701. specifier.imported = this.parseIdentifier(true);
  5702. specifier.importKind = specifierTypeKind;
  5703. } else {
  5704. if (importedIsString) {
  5705. throw this.raise(Errors.ImportBindingIsString, {
  5706. at: specifier,
  5707. importName: firstIdent.value
  5708. });
  5709. }
  5710. specifier.imported = firstIdent;
  5711. specifier.importKind = null;
  5712. }
  5713. if (this.eatContextual(93)) {
  5714. specifier.local = this.parseIdentifier();
  5715. } else {
  5716. isBinding = true;
  5717. specifier.local = cloneIdentifier(specifier.imported);
  5718. }
  5719. }
  5720. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5721. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5722. this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, {
  5723. at: specifier
  5724. });
  5725. }
  5726. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5727. this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
  5728. }
  5729. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5730. this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
  5731. }
  5732. return this.finishImportSpecifier(specifier, "ImportSpecifier");
  5733. }
  5734. parseBindingAtom() {
  5735. switch (this.state.type) {
  5736. case 78:
  5737. return this.parseIdentifier(true);
  5738. default:
  5739. return super.parseBindingAtom();
  5740. }
  5741. }
  5742. parseFunctionParams(node, allowModifiers) {
  5743. const kind = node.kind;
  5744. if (kind !== "get" && kind !== "set" && this.match(47)) {
  5745. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5746. }
  5747. super.parseFunctionParams(node, allowModifiers);
  5748. }
  5749. parseVarId(decl, kind) {
  5750. super.parseVarId(decl, kind);
  5751. if (this.match(14)) {
  5752. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5753. this.resetEndLocation(decl.id);
  5754. }
  5755. }
  5756. parseAsyncArrowFromCallExpression(node, call) {
  5757. if (this.match(14)) {
  5758. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5759. this.state.noAnonFunctionType = true;
  5760. node.returnType = this.flowParseTypeAnnotation();
  5761. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5762. }
  5763. return super.parseAsyncArrowFromCallExpression(node, call);
  5764. }
  5765. shouldParseAsyncArrow() {
  5766. return this.match(14) || super.shouldParseAsyncArrow();
  5767. }
  5768. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5769. var _jsx;
  5770. let state = null;
  5771. let jsx;
  5772. if (this.hasPlugin("jsx") && (this.match(140) || this.match(47))) {
  5773. state = this.state.clone();
  5774. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5775. if (!jsx.error) return jsx.node;
  5776. const {
  5777. context
  5778. } = this.state;
  5779. const currentContext = context[context.length - 1];
  5780. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  5781. context.pop();
  5782. }
  5783. }
  5784. if ((_jsx = jsx) != null && _jsx.error || this.match(47)) {
  5785. var _jsx2, _jsx3;
  5786. state = state || this.state.clone();
  5787. let typeParameters;
  5788. const arrow = this.tryParse(abort => {
  5789. var _arrowExpression$extr;
  5790. typeParameters = this.flowParseTypeParameterDeclaration();
  5791. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5792. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5793. this.resetStartLocationFromNode(result, typeParameters);
  5794. return result;
  5795. });
  5796. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5797. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5798. if (expr.type !== "ArrowFunctionExpression") abort();
  5799. expr.typeParameters = typeParameters;
  5800. this.resetStartLocationFromNode(expr, typeParameters);
  5801. return arrowExpression;
  5802. }, state);
  5803. let arrowExpression = null;
  5804. if (arrow.node &&
  5805. this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5806. if (!arrow.error && !arrow.aborted) {
  5807. if (arrow.node.async) {
  5808. this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, {
  5809. at: typeParameters
  5810. });
  5811. }
  5812. return arrow.node;
  5813. }
  5814. arrowExpression = arrow.node;
  5815. }
  5816. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5817. this.state = jsx.failState;
  5818. return jsx.node;
  5819. }
  5820. if (arrowExpression) {
  5821. this.state = arrow.failState;
  5822. return arrowExpression;
  5823. }
  5824. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5825. if (arrow.thrown) throw arrow.error;
  5826. throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, {
  5827. at: typeParameters
  5828. });
  5829. }
  5830. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5831. }
  5832. parseArrow(node) {
  5833. if (this.match(14)) {
  5834. const result = this.tryParse(() => {
  5835. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5836. this.state.noAnonFunctionType = true;
  5837. const typeNode = this.startNode();
  5838. [typeNode.typeAnnotation,
  5839. node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5840. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5841. if (this.canInsertSemicolon()) this.unexpected();
  5842. if (!this.match(19)) this.unexpected();
  5843. return typeNode;
  5844. });
  5845. if (result.thrown) return null;
  5846. if (result.error) this.state = result.failState;
  5847. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5848. }
  5849. return super.parseArrow(node);
  5850. }
  5851. shouldParseArrow(params) {
  5852. return this.match(14) || super.shouldParseArrow(params);
  5853. }
  5854. setArrowFunctionParameters(node, params) {
  5855. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5856. node.params = params;
  5857. } else {
  5858. super.setArrowFunctionParameters(node, params);
  5859. }
  5860. }
  5861. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  5862. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5863. return;
  5864. }
  5865. for (let i = 0; i < node.params.length; i++) {
  5866. if (this.isThisParam(node.params[i]) && i > 0) {
  5867. this.raise(FlowErrors.ThisParamMustBeFirst, {
  5868. at: node.params[i]
  5869. });
  5870. }
  5871. }
  5872. return super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
  5873. }
  5874. parseParenAndDistinguishExpression(canBeArrow) {
  5875. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  5876. }
  5877. parseSubscripts(base, startLoc, noCalls) {
  5878. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startLoc.index) !== -1) {
  5879. this.next();
  5880. const node = this.startNodeAt(startLoc);
  5881. node.callee = base;
  5882. node.arguments = super.parseCallExpressionArguments(11, false);
  5883. base = this.finishNode(node, "CallExpression");
  5884. } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) {
  5885. const state = this.state.clone();
  5886. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
  5887. if (!arrow.error && !arrow.aborted) return arrow.node;
  5888. const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state);
  5889. if (result.node && !result.error) return result.node;
  5890. if (arrow.node) {
  5891. this.state = arrow.failState;
  5892. return arrow.node;
  5893. }
  5894. if (result.node) {
  5895. this.state = result.failState;
  5896. return result.node;
  5897. }
  5898. throw arrow.error || result.error;
  5899. }
  5900. return super.parseSubscripts(base, startLoc, noCalls);
  5901. }
  5902. parseSubscript(base, startLoc, noCalls, subscriptState) {
  5903. if (this.match(18) && this.isLookaheadToken_lt()) {
  5904. subscriptState.optionalChainMember = true;
  5905. if (noCalls) {
  5906. subscriptState.stop = true;
  5907. return base;
  5908. }
  5909. this.next();
  5910. const node = this.startNodeAt(startLoc);
  5911. node.callee = base;
  5912. node.typeArguments = this.flowParseTypeParameterInstantiation();
  5913. this.expect(10);
  5914. node.arguments = this.parseCallExpressionArguments(11, false);
  5915. node.optional = true;
  5916. return this.finishCallExpression(node, true);
  5917. } else if (!noCalls && this.shouldParseTypes() && this.match(47)) {
  5918. const node = this.startNodeAt(startLoc);
  5919. node.callee = base;
  5920. const result = this.tryParse(() => {
  5921. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5922. this.expect(10);
  5923. node.arguments = super.parseCallExpressionArguments(11, false);
  5924. if (subscriptState.optionalChainMember) {
  5925. node.optional = false;
  5926. }
  5927. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  5928. });
  5929. if (result.node) {
  5930. if (result.error) this.state = result.failState;
  5931. return result.node;
  5932. }
  5933. }
  5934. return super.parseSubscript(base, startLoc, noCalls, subscriptState);
  5935. }
  5936. parseNewCallee(node) {
  5937. super.parseNewCallee(node);
  5938. let targs = null;
  5939. if (this.shouldParseTypes() && this.match(47)) {
  5940. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  5941. }
  5942. node.typeArguments = targs;
  5943. }
  5944. parseAsyncArrowWithTypeParameters(startLoc) {
  5945. const node = this.startNodeAt(startLoc);
  5946. this.parseFunctionParams(node);
  5947. if (!this.parseArrow(node)) return;
  5948. return super.parseArrowExpression(node, undefined, true);
  5949. }
  5950. readToken_mult_modulo(code) {
  5951. const next = this.input.charCodeAt(this.state.pos + 1);
  5952. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  5953. this.state.hasFlowComment = false;
  5954. this.state.pos += 2;
  5955. this.nextToken();
  5956. return;
  5957. }
  5958. super.readToken_mult_modulo(code);
  5959. }
  5960. readToken_pipe_amp(code) {
  5961. const next = this.input.charCodeAt(this.state.pos + 1);
  5962. if (code === 124 && next === 125) {
  5963. this.finishOp(9, 2);
  5964. return;
  5965. }
  5966. super.readToken_pipe_amp(code);
  5967. }
  5968. parseTopLevel(file, program) {
  5969. const fileNode = super.parseTopLevel(file, program);
  5970. if (this.state.hasFlowComment) {
  5971. this.raise(FlowErrors.UnterminatedFlowComment, {
  5972. at: this.state.curPosition()
  5973. });
  5974. }
  5975. return fileNode;
  5976. }
  5977. skipBlockComment() {
  5978. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  5979. if (this.state.hasFlowComment) {
  5980. throw this.raise(FlowErrors.NestedFlowComment, {
  5981. at: this.state.startLoc
  5982. });
  5983. }
  5984. this.hasFlowCommentCompletion();
  5985. const commentSkip = this.skipFlowComment();
  5986. if (commentSkip) {
  5987. this.state.pos += commentSkip;
  5988. this.state.hasFlowComment = true;
  5989. }
  5990. return;
  5991. }
  5992. return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  5993. }
  5994. skipFlowComment() {
  5995. const {
  5996. pos
  5997. } = this.state;
  5998. let shiftToFirstNonWhiteSpace = 2;
  5999. while ([32, 9].includes(
  6000. this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  6001. shiftToFirstNonWhiteSpace++;
  6002. }
  6003. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  6004. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  6005. if (ch2 === 58 && ch3 === 58) {
  6006. return shiftToFirstNonWhiteSpace + 2;
  6007. }
  6008. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  6009. return shiftToFirstNonWhiteSpace + 12;
  6010. }
  6011. if (ch2 === 58 && ch3 !== 58) {
  6012. return shiftToFirstNonWhiteSpace;
  6013. }
  6014. return false;
  6015. }
  6016. hasFlowCommentCompletion() {
  6017. const end = this.input.indexOf("*/", this.state.pos);
  6018. if (end === -1) {
  6019. throw this.raise(Errors.UnterminatedComment, {
  6020. at: this.state.curPosition()
  6021. });
  6022. }
  6023. }
  6024. flowEnumErrorBooleanMemberNotInitialized(loc, {
  6025. enumName,
  6026. memberName
  6027. }) {
  6028. this.raise(FlowErrors.EnumBooleanMemberNotInitialized, {
  6029. at: loc,
  6030. memberName,
  6031. enumName
  6032. });
  6033. }
  6034. flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
  6035. return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, Object.assign({
  6036. at: loc
  6037. }, enumContext));
  6038. }
  6039. flowEnumErrorNumberMemberNotInitialized(loc, {
  6040. enumName,
  6041. memberName
  6042. }) {
  6043. this.raise(FlowErrors.EnumNumberMemberNotInitialized, {
  6044. at: loc,
  6045. enumName,
  6046. memberName
  6047. });
  6048. }
  6049. flowEnumErrorStringMemberInconsistentlyInitailized(node, {
  6050. enumName
  6051. }) {
  6052. this.raise(FlowErrors.EnumStringMemberInconsistentlyInitailized, {
  6053. at: node,
  6054. enumName
  6055. });
  6056. }
  6057. flowEnumMemberInit() {
  6058. const startLoc = this.state.startLoc;
  6059. const endOfInit = () => this.match(12) || this.match(8);
  6060. switch (this.state.type) {
  6061. case 132:
  6062. {
  6063. const literal = this.parseNumericLiteral(this.state.value);
  6064. if (endOfInit()) {
  6065. return {
  6066. type: "number",
  6067. loc: literal.loc.start,
  6068. value: literal
  6069. };
  6070. }
  6071. return {
  6072. type: "invalid",
  6073. loc: startLoc
  6074. };
  6075. }
  6076. case 131:
  6077. {
  6078. const literal = this.parseStringLiteral(this.state.value);
  6079. if (endOfInit()) {
  6080. return {
  6081. type: "string",
  6082. loc: literal.loc.start,
  6083. value: literal
  6084. };
  6085. }
  6086. return {
  6087. type: "invalid",
  6088. loc: startLoc
  6089. };
  6090. }
  6091. case 85:
  6092. case 86:
  6093. {
  6094. const literal = this.parseBooleanLiteral(this.match(85));
  6095. if (endOfInit()) {
  6096. return {
  6097. type: "boolean",
  6098. loc: literal.loc.start,
  6099. value: literal
  6100. };
  6101. }
  6102. return {
  6103. type: "invalid",
  6104. loc: startLoc
  6105. };
  6106. }
  6107. default:
  6108. return {
  6109. type: "invalid",
  6110. loc: startLoc
  6111. };
  6112. }
  6113. }
  6114. flowEnumMemberRaw() {
  6115. const loc = this.state.startLoc;
  6116. const id = this.parseIdentifier(true);
  6117. const init = this.eat(29) ? this.flowEnumMemberInit() : {
  6118. type: "none",
  6119. loc
  6120. };
  6121. return {
  6122. id,
  6123. init
  6124. };
  6125. }
  6126. flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
  6127. const {
  6128. explicitType
  6129. } = context;
  6130. if (explicitType === null) {
  6131. return;
  6132. }
  6133. if (explicitType !== expectedType) {
  6134. this.flowEnumErrorInvalidMemberInitializer(loc, context);
  6135. }
  6136. }
  6137. flowEnumMembers({
  6138. enumName,
  6139. explicitType
  6140. }) {
  6141. const seenNames = new Set();
  6142. const members = {
  6143. booleanMembers: [],
  6144. numberMembers: [],
  6145. stringMembers: [],
  6146. defaultedMembers: []
  6147. };
  6148. let hasUnknownMembers = false;
  6149. while (!this.match(8)) {
  6150. if (this.eat(21)) {
  6151. hasUnknownMembers = true;
  6152. break;
  6153. }
  6154. const memberNode = this.startNode();
  6155. const {
  6156. id,
  6157. init
  6158. } = this.flowEnumMemberRaw();
  6159. const memberName = id.name;
  6160. if (memberName === "") {
  6161. continue;
  6162. }
  6163. if (/^[a-z]/.test(memberName)) {
  6164. this.raise(FlowErrors.EnumInvalidMemberName, {
  6165. at: id,
  6166. memberName,
  6167. suggestion: memberName[0].toUpperCase() + memberName.slice(1),
  6168. enumName
  6169. });
  6170. }
  6171. if (seenNames.has(memberName)) {
  6172. this.raise(FlowErrors.EnumDuplicateMemberName, {
  6173. at: id,
  6174. memberName,
  6175. enumName
  6176. });
  6177. }
  6178. seenNames.add(memberName);
  6179. const context = {
  6180. enumName,
  6181. explicitType,
  6182. memberName
  6183. };
  6184. memberNode.id = id;
  6185. switch (init.type) {
  6186. case "boolean":
  6187. {
  6188. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean");
  6189. memberNode.init = init.value;
  6190. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6191. break;
  6192. }
  6193. case "number":
  6194. {
  6195. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number");
  6196. memberNode.init = init.value;
  6197. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6198. break;
  6199. }
  6200. case "string":
  6201. {
  6202. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string");
  6203. memberNode.init = init.value;
  6204. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6205. break;
  6206. }
  6207. case "invalid":
  6208. {
  6209. throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);
  6210. }
  6211. case "none":
  6212. {
  6213. switch (explicitType) {
  6214. case "boolean":
  6215. this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context);
  6216. break;
  6217. case "number":
  6218. this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);
  6219. break;
  6220. default:
  6221. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6222. }
  6223. }
  6224. }
  6225. if (!this.match(8)) {
  6226. this.expect(12);
  6227. }
  6228. }
  6229. return {
  6230. members,
  6231. hasUnknownMembers
  6232. };
  6233. }
  6234. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6235. enumName
  6236. }) {
  6237. if (initializedMembers.length === 0) {
  6238. return defaultedMembers;
  6239. } else if (defaultedMembers.length === 0) {
  6240. return initializedMembers;
  6241. } else if (defaultedMembers.length > initializedMembers.length) {
  6242. for (const member of initializedMembers) {
  6243. this.flowEnumErrorStringMemberInconsistentlyInitailized(member, {
  6244. enumName
  6245. });
  6246. }
  6247. return defaultedMembers;
  6248. } else {
  6249. for (const member of defaultedMembers) {
  6250. this.flowEnumErrorStringMemberInconsistentlyInitailized(member, {
  6251. enumName
  6252. });
  6253. }
  6254. return initializedMembers;
  6255. }
  6256. }
  6257. flowEnumParseExplicitType({
  6258. enumName
  6259. }) {
  6260. if (!this.eatContextual(101)) return null;
  6261. if (!tokenIsIdentifier(this.state.type)) {
  6262. throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, {
  6263. at: this.state.startLoc,
  6264. enumName
  6265. });
  6266. }
  6267. const {
  6268. value
  6269. } = this.state;
  6270. this.next();
  6271. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6272. this.raise(FlowErrors.EnumInvalidExplicitType, {
  6273. at: this.state.startLoc,
  6274. enumName,
  6275. invalidEnumType: value
  6276. });
  6277. }
  6278. return value;
  6279. }
  6280. flowEnumBody(node, id) {
  6281. const enumName = id.name;
  6282. const nameLoc = id.loc.start;
  6283. const explicitType = this.flowEnumParseExplicitType({
  6284. enumName
  6285. });
  6286. this.expect(5);
  6287. const {
  6288. members,
  6289. hasUnknownMembers
  6290. } = this.flowEnumMembers({
  6291. enumName,
  6292. explicitType
  6293. });
  6294. node.hasUnknownMembers = hasUnknownMembers;
  6295. switch (explicitType) {
  6296. case "boolean":
  6297. node.explicitType = true;
  6298. node.members = members.booleanMembers;
  6299. this.expect(8);
  6300. return this.finishNode(node, "EnumBooleanBody");
  6301. case "number":
  6302. node.explicitType = true;
  6303. node.members = members.numberMembers;
  6304. this.expect(8);
  6305. return this.finishNode(node, "EnumNumberBody");
  6306. case "string":
  6307. node.explicitType = true;
  6308. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6309. enumName
  6310. });
  6311. this.expect(8);
  6312. return this.finishNode(node, "EnumStringBody");
  6313. case "symbol":
  6314. node.members = members.defaultedMembers;
  6315. this.expect(8);
  6316. return this.finishNode(node, "EnumSymbolBody");
  6317. default:
  6318. {
  6319. const empty = () => {
  6320. node.members = [];
  6321. this.expect(8);
  6322. return this.finishNode(node, "EnumStringBody");
  6323. };
  6324. node.explicitType = false;
  6325. const boolsLen = members.booleanMembers.length;
  6326. const numsLen = members.numberMembers.length;
  6327. const strsLen = members.stringMembers.length;
  6328. const defaultedLen = members.defaultedMembers.length;
  6329. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6330. return empty();
  6331. } else if (!boolsLen && !numsLen) {
  6332. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6333. enumName
  6334. });
  6335. this.expect(8);
  6336. return this.finishNode(node, "EnumStringBody");
  6337. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6338. for (const member of members.defaultedMembers) {
  6339. this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
  6340. enumName,
  6341. memberName: member.id.name
  6342. });
  6343. }
  6344. node.members = members.booleanMembers;
  6345. this.expect(8);
  6346. return this.finishNode(node, "EnumBooleanBody");
  6347. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6348. for (const member of members.defaultedMembers) {
  6349. this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
  6350. enumName,
  6351. memberName: member.id.name
  6352. });
  6353. }
  6354. node.members = members.numberMembers;
  6355. this.expect(8);
  6356. return this.finishNode(node, "EnumNumberBody");
  6357. } else {
  6358. this.raise(FlowErrors.EnumInconsistentMemberValues, {
  6359. at: nameLoc,
  6360. enumName
  6361. });
  6362. return empty();
  6363. }
  6364. }
  6365. }
  6366. }
  6367. flowParseEnumDeclaration(node) {
  6368. const id = this.parseIdentifier();
  6369. node.id = id;
  6370. node.body = this.flowEnumBody(this.startNode(), id);
  6371. return this.finishNode(node, "EnumDeclaration");
  6372. }
  6373. isLookaheadToken_lt() {
  6374. const next = this.nextTokenStart();
  6375. if (this.input.charCodeAt(next) === 60) {
  6376. const afterNext = this.input.charCodeAt(next + 1);
  6377. return afterNext !== 60 && afterNext !== 61;
  6378. }
  6379. return false;
  6380. }
  6381. maybeUnwrapTypeCastExpression(node) {
  6382. return node.type === "TypeCastExpression" ? node.expression : node;
  6383. }
  6384. });
  6385. const entities = {
  6386. __proto__: null,
  6387. quot: "\u0022",
  6388. amp: "&",
  6389. apos: "\u0027",
  6390. lt: "<",
  6391. gt: ">",
  6392. nbsp: "\u00A0",
  6393. iexcl: "\u00A1",
  6394. cent: "\u00A2",
  6395. pound: "\u00A3",
  6396. curren: "\u00A4",
  6397. yen: "\u00A5",
  6398. brvbar: "\u00A6",
  6399. sect: "\u00A7",
  6400. uml: "\u00A8",
  6401. copy: "\u00A9",
  6402. ordf: "\u00AA",
  6403. laquo: "\u00AB",
  6404. not: "\u00AC",
  6405. shy: "\u00AD",
  6406. reg: "\u00AE",
  6407. macr: "\u00AF",
  6408. deg: "\u00B0",
  6409. plusmn: "\u00B1",
  6410. sup2: "\u00B2",
  6411. sup3: "\u00B3",
  6412. acute: "\u00B4",
  6413. micro: "\u00B5",
  6414. para: "\u00B6",
  6415. middot: "\u00B7",
  6416. cedil: "\u00B8",
  6417. sup1: "\u00B9",
  6418. ordm: "\u00BA",
  6419. raquo: "\u00BB",
  6420. frac14: "\u00BC",
  6421. frac12: "\u00BD",
  6422. frac34: "\u00BE",
  6423. iquest: "\u00BF",
  6424. Agrave: "\u00C0",
  6425. Aacute: "\u00C1",
  6426. Acirc: "\u00C2",
  6427. Atilde: "\u00C3",
  6428. Auml: "\u00C4",
  6429. Aring: "\u00C5",
  6430. AElig: "\u00C6",
  6431. Ccedil: "\u00C7",
  6432. Egrave: "\u00C8",
  6433. Eacute: "\u00C9",
  6434. Ecirc: "\u00CA",
  6435. Euml: "\u00CB",
  6436. Igrave: "\u00CC",
  6437. Iacute: "\u00CD",
  6438. Icirc: "\u00CE",
  6439. Iuml: "\u00CF",
  6440. ETH: "\u00D0",
  6441. Ntilde: "\u00D1",
  6442. Ograve: "\u00D2",
  6443. Oacute: "\u00D3",
  6444. Ocirc: "\u00D4",
  6445. Otilde: "\u00D5",
  6446. Ouml: "\u00D6",
  6447. times: "\u00D7",
  6448. Oslash: "\u00D8",
  6449. Ugrave: "\u00D9",
  6450. Uacute: "\u00DA",
  6451. Ucirc: "\u00DB",
  6452. Uuml: "\u00DC",
  6453. Yacute: "\u00DD",
  6454. THORN: "\u00DE",
  6455. szlig: "\u00DF",
  6456. agrave: "\u00E0",
  6457. aacute: "\u00E1",
  6458. acirc: "\u00E2",
  6459. atilde: "\u00E3",
  6460. auml: "\u00E4",
  6461. aring: "\u00E5",
  6462. aelig: "\u00E6",
  6463. ccedil: "\u00E7",
  6464. egrave: "\u00E8",
  6465. eacute: "\u00E9",
  6466. ecirc: "\u00EA",
  6467. euml: "\u00EB",
  6468. igrave: "\u00EC",
  6469. iacute: "\u00ED",
  6470. icirc: "\u00EE",
  6471. iuml: "\u00EF",
  6472. eth: "\u00F0",
  6473. ntilde: "\u00F1",
  6474. ograve: "\u00F2",
  6475. oacute: "\u00F3",
  6476. ocirc: "\u00F4",
  6477. otilde: "\u00F5",
  6478. ouml: "\u00F6",
  6479. divide: "\u00F7",
  6480. oslash: "\u00F8",
  6481. ugrave: "\u00F9",
  6482. uacute: "\u00FA",
  6483. ucirc: "\u00FB",
  6484. uuml: "\u00FC",
  6485. yacute: "\u00FD",
  6486. thorn: "\u00FE",
  6487. yuml: "\u00FF",
  6488. OElig: "\u0152",
  6489. oelig: "\u0153",
  6490. Scaron: "\u0160",
  6491. scaron: "\u0161",
  6492. Yuml: "\u0178",
  6493. fnof: "\u0192",
  6494. circ: "\u02C6",
  6495. tilde: "\u02DC",
  6496. Alpha: "\u0391",
  6497. Beta: "\u0392",
  6498. Gamma: "\u0393",
  6499. Delta: "\u0394",
  6500. Epsilon: "\u0395",
  6501. Zeta: "\u0396",
  6502. Eta: "\u0397",
  6503. Theta: "\u0398",
  6504. Iota: "\u0399",
  6505. Kappa: "\u039A",
  6506. Lambda: "\u039B",
  6507. Mu: "\u039C",
  6508. Nu: "\u039D",
  6509. Xi: "\u039E",
  6510. Omicron: "\u039F",
  6511. Pi: "\u03A0",
  6512. Rho: "\u03A1",
  6513. Sigma: "\u03A3",
  6514. Tau: "\u03A4",
  6515. Upsilon: "\u03A5",
  6516. Phi: "\u03A6",
  6517. Chi: "\u03A7",
  6518. Psi: "\u03A8",
  6519. Omega: "\u03A9",
  6520. alpha: "\u03B1",
  6521. beta: "\u03B2",
  6522. gamma: "\u03B3",
  6523. delta: "\u03B4",
  6524. epsilon: "\u03B5",
  6525. zeta: "\u03B6",
  6526. eta: "\u03B7",
  6527. theta: "\u03B8",
  6528. iota: "\u03B9",
  6529. kappa: "\u03BA",
  6530. lambda: "\u03BB",
  6531. mu: "\u03BC",
  6532. nu: "\u03BD",
  6533. xi: "\u03BE",
  6534. omicron: "\u03BF",
  6535. pi: "\u03C0",
  6536. rho: "\u03C1",
  6537. sigmaf: "\u03C2",
  6538. sigma: "\u03C3",
  6539. tau: "\u03C4",
  6540. upsilon: "\u03C5",
  6541. phi: "\u03C6",
  6542. chi: "\u03C7",
  6543. psi: "\u03C8",
  6544. omega: "\u03C9",
  6545. thetasym: "\u03D1",
  6546. upsih: "\u03D2",
  6547. piv: "\u03D6",
  6548. ensp: "\u2002",
  6549. emsp: "\u2003",
  6550. thinsp: "\u2009",
  6551. zwnj: "\u200C",
  6552. zwj: "\u200D",
  6553. lrm: "\u200E",
  6554. rlm: "\u200F",
  6555. ndash: "\u2013",
  6556. mdash: "\u2014",
  6557. lsquo: "\u2018",
  6558. rsquo: "\u2019",
  6559. sbquo: "\u201A",
  6560. ldquo: "\u201C",
  6561. rdquo: "\u201D",
  6562. bdquo: "\u201E",
  6563. dagger: "\u2020",
  6564. Dagger: "\u2021",
  6565. bull: "\u2022",
  6566. hellip: "\u2026",
  6567. permil: "\u2030",
  6568. prime: "\u2032",
  6569. Prime: "\u2033",
  6570. lsaquo: "\u2039",
  6571. rsaquo: "\u203A",
  6572. oline: "\u203E",
  6573. frasl: "\u2044",
  6574. euro: "\u20AC",
  6575. image: "\u2111",
  6576. weierp: "\u2118",
  6577. real: "\u211C",
  6578. trade: "\u2122",
  6579. alefsym: "\u2135",
  6580. larr: "\u2190",
  6581. uarr: "\u2191",
  6582. rarr: "\u2192",
  6583. darr: "\u2193",
  6584. harr: "\u2194",
  6585. crarr: "\u21B5",
  6586. lArr: "\u21D0",
  6587. uArr: "\u21D1",
  6588. rArr: "\u21D2",
  6589. dArr: "\u21D3",
  6590. hArr: "\u21D4",
  6591. forall: "\u2200",
  6592. part: "\u2202",
  6593. exist: "\u2203",
  6594. empty: "\u2205",
  6595. nabla: "\u2207",
  6596. isin: "\u2208",
  6597. notin: "\u2209",
  6598. ni: "\u220B",
  6599. prod: "\u220F",
  6600. sum: "\u2211",
  6601. minus: "\u2212",
  6602. lowast: "\u2217",
  6603. radic: "\u221A",
  6604. prop: "\u221D",
  6605. infin: "\u221E",
  6606. ang: "\u2220",
  6607. and: "\u2227",
  6608. or: "\u2228",
  6609. cap: "\u2229",
  6610. cup: "\u222A",
  6611. int: "\u222B",
  6612. there4: "\u2234",
  6613. sim: "\u223C",
  6614. cong: "\u2245",
  6615. asymp: "\u2248",
  6616. ne: "\u2260",
  6617. equiv: "\u2261",
  6618. le: "\u2264",
  6619. ge: "\u2265",
  6620. sub: "\u2282",
  6621. sup: "\u2283",
  6622. nsub: "\u2284",
  6623. sube: "\u2286",
  6624. supe: "\u2287",
  6625. oplus: "\u2295",
  6626. otimes: "\u2297",
  6627. perp: "\u22A5",
  6628. sdot: "\u22C5",
  6629. lceil: "\u2308",
  6630. rceil: "\u2309",
  6631. lfloor: "\u230A",
  6632. rfloor: "\u230B",
  6633. lang: "\u2329",
  6634. rang: "\u232A",
  6635. loz: "\u25CA",
  6636. spades: "\u2660",
  6637. clubs: "\u2663",
  6638. hearts: "\u2665",
  6639. diams: "\u2666"
  6640. };
  6641. const JsxErrors = ParseErrorEnum`jsx`({
  6642. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6643. MissingClosingTagElement: ({
  6644. openingTagName
  6645. }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  6646. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6647. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6648. UnexpectedToken: ({
  6649. unexpected,
  6650. HTMLEntity
  6651. }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  6652. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6653. UnterminatedJsxContent: "Unterminated JSX contents.",
  6654. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6655. });
  6656. function isFragment(object) {
  6657. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6658. }
  6659. function getQualifiedJSXName(object) {
  6660. if (object.type === "JSXIdentifier") {
  6661. return object.name;
  6662. }
  6663. if (object.type === "JSXNamespacedName") {
  6664. return object.namespace.name + ":" + object.name.name;
  6665. }
  6666. if (object.type === "JSXMemberExpression") {
  6667. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6668. }
  6669. throw new Error("Node had unexpected type: " + object.type);
  6670. }
  6671. var jsx = (superClass => class JSXParserMixin extends superClass {
  6672. jsxReadToken() {
  6673. let out = "";
  6674. let chunkStart = this.state.pos;
  6675. for (;;) {
  6676. if (this.state.pos >= this.length) {
  6677. throw this.raise(JsxErrors.UnterminatedJsxContent, {
  6678. at: this.state.startLoc
  6679. });
  6680. }
  6681. const ch = this.input.charCodeAt(this.state.pos);
  6682. switch (ch) {
  6683. case 60:
  6684. case 123:
  6685. if (this.state.pos === this.state.start) {
  6686. if (ch === 60 && this.state.canStartJSXElement) {
  6687. ++this.state.pos;
  6688. return this.finishToken(140);
  6689. }
  6690. return super.getTokenFromCode(ch);
  6691. }
  6692. out += this.input.slice(chunkStart, this.state.pos);
  6693. return this.finishToken(139, out);
  6694. case 38:
  6695. out += this.input.slice(chunkStart, this.state.pos);
  6696. out += this.jsxReadEntity();
  6697. chunkStart = this.state.pos;
  6698. break;
  6699. case 62:
  6700. case 125:
  6701. default:
  6702. if (isNewLine(ch)) {
  6703. out += this.input.slice(chunkStart, this.state.pos);
  6704. out += this.jsxReadNewLine(true);
  6705. chunkStart = this.state.pos;
  6706. } else {
  6707. ++this.state.pos;
  6708. }
  6709. }
  6710. }
  6711. }
  6712. jsxReadNewLine(normalizeCRLF) {
  6713. const ch = this.input.charCodeAt(this.state.pos);
  6714. let out;
  6715. ++this.state.pos;
  6716. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6717. ++this.state.pos;
  6718. out = normalizeCRLF ? "\n" : "\r\n";
  6719. } else {
  6720. out = String.fromCharCode(ch);
  6721. }
  6722. ++this.state.curLine;
  6723. this.state.lineStart = this.state.pos;
  6724. return out;
  6725. }
  6726. jsxReadString(quote) {
  6727. let out = "";
  6728. let chunkStart = ++this.state.pos;
  6729. for (;;) {
  6730. if (this.state.pos >= this.length) {
  6731. throw this.raise(Errors.UnterminatedString, {
  6732. at: this.state.startLoc
  6733. });
  6734. }
  6735. const ch = this.input.charCodeAt(this.state.pos);
  6736. if (ch === quote) break;
  6737. if (ch === 38) {
  6738. out += this.input.slice(chunkStart, this.state.pos);
  6739. out += this.jsxReadEntity();
  6740. chunkStart = this.state.pos;
  6741. } else if (isNewLine(ch)) {
  6742. out += this.input.slice(chunkStart, this.state.pos);
  6743. out += this.jsxReadNewLine(false);
  6744. chunkStart = this.state.pos;
  6745. } else {
  6746. ++this.state.pos;
  6747. }
  6748. }
  6749. out += this.input.slice(chunkStart, this.state.pos++);
  6750. return this.finishToken(131, out);
  6751. }
  6752. jsxReadEntity() {
  6753. const startPos = ++this.state.pos;
  6754. if (this.codePointAtPos(this.state.pos) === 35) {
  6755. ++this.state.pos;
  6756. let radix = 10;
  6757. if (this.codePointAtPos(this.state.pos) === 120) {
  6758. radix = 16;
  6759. ++this.state.pos;
  6760. }
  6761. const codePoint = this.readInt(radix, undefined, false, "bail");
  6762. if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
  6763. ++this.state.pos;
  6764. return String.fromCodePoint(codePoint);
  6765. }
  6766. } else {
  6767. let count = 0;
  6768. let semi = false;
  6769. while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) == 59)) {
  6770. ++this.state.pos;
  6771. }
  6772. if (semi) {
  6773. const desc = this.input.slice(startPos, this.state.pos);
  6774. const entity = entities[desc];
  6775. ++this.state.pos;
  6776. if (entity) {
  6777. return entity;
  6778. }
  6779. }
  6780. }
  6781. this.state.pos = startPos;
  6782. return "&";
  6783. }
  6784. jsxReadWord() {
  6785. let ch;
  6786. const start = this.state.pos;
  6787. do {
  6788. ch = this.input.charCodeAt(++this.state.pos);
  6789. } while (isIdentifierChar(ch) || ch === 45);
  6790. return this.finishToken(138, this.input.slice(start, this.state.pos));
  6791. }
  6792. jsxParseIdentifier() {
  6793. const node = this.startNode();
  6794. if (this.match(138)) {
  6795. node.name = this.state.value;
  6796. } else if (tokenIsKeyword(this.state.type)) {
  6797. node.name = tokenLabelName(this.state.type);
  6798. } else {
  6799. this.unexpected();
  6800. }
  6801. this.next();
  6802. return this.finishNode(node, "JSXIdentifier");
  6803. }
  6804. jsxParseNamespacedName() {
  6805. const startLoc = this.state.startLoc;
  6806. const name = this.jsxParseIdentifier();
  6807. if (!this.eat(14)) return name;
  6808. const node = this.startNodeAt(startLoc);
  6809. node.namespace = name;
  6810. node.name = this.jsxParseIdentifier();
  6811. return this.finishNode(node, "JSXNamespacedName");
  6812. }
  6813. jsxParseElementName() {
  6814. const startLoc = this.state.startLoc;
  6815. let node = this.jsxParseNamespacedName();
  6816. if (node.type === "JSXNamespacedName") {
  6817. return node;
  6818. }
  6819. while (this.eat(16)) {
  6820. const newNode = this.startNodeAt(startLoc);
  6821. newNode.object = node;
  6822. newNode.property = this.jsxParseIdentifier();
  6823. node = this.finishNode(newNode, "JSXMemberExpression");
  6824. }
  6825. return node;
  6826. }
  6827. jsxParseAttributeValue() {
  6828. let node;
  6829. switch (this.state.type) {
  6830. case 5:
  6831. node = this.startNode();
  6832. this.setContext(types.brace);
  6833. this.next();
  6834. node = this.jsxParseExpressionContainer(node, types.j_oTag);
  6835. if (node.expression.type === "JSXEmptyExpression") {
  6836. this.raise(JsxErrors.AttributeIsEmpty, {
  6837. at: node
  6838. });
  6839. }
  6840. return node;
  6841. case 140:
  6842. case 131:
  6843. return this.parseExprAtom();
  6844. default:
  6845. throw this.raise(JsxErrors.UnsupportedJsxValue, {
  6846. at: this.state.startLoc
  6847. });
  6848. }
  6849. }
  6850. jsxParseEmptyExpression() {
  6851. const node = this.startNodeAt(this.state.lastTokEndLoc);
  6852. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
  6853. }
  6854. jsxParseSpreadChild(node) {
  6855. this.next();
  6856. node.expression = this.parseExpression();
  6857. this.setContext(types.j_expr);
  6858. this.state.canStartJSXElement = true;
  6859. this.expect(8);
  6860. return this.finishNode(node, "JSXSpreadChild");
  6861. }
  6862. jsxParseExpressionContainer(node, previousContext) {
  6863. if (this.match(8)) {
  6864. node.expression = this.jsxParseEmptyExpression();
  6865. } else {
  6866. const expression = this.parseExpression();
  6867. node.expression = expression;
  6868. }
  6869. this.setContext(previousContext);
  6870. this.state.canStartJSXElement = true;
  6871. this.expect(8);
  6872. return this.finishNode(node, "JSXExpressionContainer");
  6873. }
  6874. jsxParseAttribute() {
  6875. const node = this.startNode();
  6876. if (this.match(5)) {
  6877. this.setContext(types.brace);
  6878. this.next();
  6879. this.expect(21);
  6880. node.argument = this.parseMaybeAssignAllowIn();
  6881. this.setContext(types.j_oTag);
  6882. this.state.canStartJSXElement = true;
  6883. this.expect(8);
  6884. return this.finishNode(node, "JSXSpreadAttribute");
  6885. }
  6886. node.name = this.jsxParseNamespacedName();
  6887. node.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
  6888. return this.finishNode(node, "JSXAttribute");
  6889. }
  6890. jsxParseOpeningElementAt(startLoc) {
  6891. const node = this.startNodeAt(startLoc);
  6892. if (this.eat(141)) {
  6893. return this.finishNode(node, "JSXOpeningFragment");
  6894. }
  6895. node.name = this.jsxParseElementName();
  6896. return this.jsxParseOpeningElementAfterName(node);
  6897. }
  6898. jsxParseOpeningElementAfterName(node) {
  6899. const attributes = [];
  6900. while (!this.match(56) && !this.match(141)) {
  6901. attributes.push(this.jsxParseAttribute());
  6902. }
  6903. node.attributes = attributes;
  6904. node.selfClosing = this.eat(56);
  6905. this.expect(141);
  6906. return this.finishNode(node, "JSXOpeningElement");
  6907. }
  6908. jsxParseClosingElementAt(startLoc) {
  6909. const node = this.startNodeAt(startLoc);
  6910. if (this.eat(141)) {
  6911. return this.finishNode(node, "JSXClosingFragment");
  6912. }
  6913. node.name = this.jsxParseElementName();
  6914. this.expect(141);
  6915. return this.finishNode(node, "JSXClosingElement");
  6916. }
  6917. jsxParseElementAt(startLoc) {
  6918. const node = this.startNodeAt(startLoc);
  6919. const children = [];
  6920. const openingElement = this.jsxParseOpeningElementAt(startLoc);
  6921. let closingElement = null;
  6922. if (!openingElement.selfClosing) {
  6923. contents: for (;;) {
  6924. switch (this.state.type) {
  6925. case 140:
  6926. startLoc = this.state.startLoc;
  6927. this.next();
  6928. if (this.eat(56)) {
  6929. closingElement = this.jsxParseClosingElementAt(startLoc);
  6930. break contents;
  6931. }
  6932. children.push(this.jsxParseElementAt(startLoc));
  6933. break;
  6934. case 139:
  6935. children.push(this.parseExprAtom());
  6936. break;
  6937. case 5:
  6938. {
  6939. const node = this.startNode();
  6940. this.setContext(types.brace);
  6941. this.next();
  6942. if (this.match(21)) {
  6943. children.push(this.jsxParseSpreadChild(node));
  6944. } else {
  6945. children.push(this.jsxParseExpressionContainer(node, types.j_expr));
  6946. }
  6947. break;
  6948. }
  6949. default:
  6950. throw this.unexpected();
  6951. }
  6952. }
  6953. if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
  6954. this.raise(JsxErrors.MissingClosingTagFragment, {
  6955. at: closingElement
  6956. });
  6957. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  6958. this.raise(JsxErrors.MissingClosingTagElement, {
  6959. at: closingElement,
  6960. openingTagName: getQualifiedJSXName(openingElement.name)
  6961. });
  6962. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  6963. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  6964. this.raise(JsxErrors.MissingClosingTagElement, {
  6965. at: closingElement,
  6966. openingTagName: getQualifiedJSXName(openingElement.name)
  6967. });
  6968. }
  6969. }
  6970. }
  6971. if (isFragment(openingElement)) {
  6972. node.openingFragment = openingElement;
  6973. node.closingFragment = closingElement;
  6974. } else {
  6975. node.openingElement = openingElement;
  6976. node.closingElement = closingElement;
  6977. }
  6978. node.children = children;
  6979. if (this.match(47)) {
  6980. throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, {
  6981. at: this.state.startLoc
  6982. });
  6983. }
  6984. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  6985. }
  6986. jsxParseElement() {
  6987. const startLoc = this.state.startLoc;
  6988. this.next();
  6989. return this.jsxParseElementAt(startLoc);
  6990. }
  6991. setContext(newContext) {
  6992. const {
  6993. context
  6994. } = this.state;
  6995. context[context.length - 1] = newContext;
  6996. }
  6997. parseExprAtom(refExpressionErrors) {
  6998. if (this.match(139)) {
  6999. return this.parseLiteral(this.state.value, "JSXText");
  7000. } else if (this.match(140)) {
  7001. return this.jsxParseElement();
  7002. } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
  7003. this.replaceToken(140);
  7004. return this.jsxParseElement();
  7005. } else {
  7006. return super.parseExprAtom(refExpressionErrors);
  7007. }
  7008. }
  7009. skipSpace() {
  7010. const curContext = this.curContext();
  7011. if (!curContext.preserveSpace) super.skipSpace();
  7012. }
  7013. getTokenFromCode(code) {
  7014. const context = this.curContext();
  7015. if (context === types.j_expr) {
  7016. return this.jsxReadToken();
  7017. }
  7018. if (context === types.j_oTag || context === types.j_cTag) {
  7019. if (isIdentifierStart(code)) {
  7020. return this.jsxReadWord();
  7021. }
  7022. if (code === 62) {
  7023. ++this.state.pos;
  7024. return this.finishToken(141);
  7025. }
  7026. if ((code === 34 || code === 39) && context === types.j_oTag) {
  7027. return this.jsxReadString(code);
  7028. }
  7029. }
  7030. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  7031. ++this.state.pos;
  7032. return this.finishToken(140);
  7033. }
  7034. return super.getTokenFromCode(code);
  7035. }
  7036. updateContext(prevType) {
  7037. const {
  7038. context,
  7039. type
  7040. } = this.state;
  7041. if (type === 56 && prevType === 140) {
  7042. context.splice(-2, 2, types.j_cTag);
  7043. this.state.canStartJSXElement = false;
  7044. } else if (type === 140) {
  7045. context.push(types.j_oTag);
  7046. } else if (type === 141) {
  7047. const out = context[context.length - 1];
  7048. if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) {
  7049. context.pop();
  7050. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  7051. } else {
  7052. this.setContext(types.j_expr);
  7053. this.state.canStartJSXElement = true;
  7054. }
  7055. } else {
  7056. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  7057. }
  7058. }
  7059. });
  7060. class TypeScriptScope extends Scope {
  7061. constructor(...args) {
  7062. super(...args);
  7063. this.types = new Set();
  7064. this.enums = new Set();
  7065. this.constEnums = new Set();
  7066. this.classes = new Set();
  7067. this.exportOnlyBindings = new Set();
  7068. }
  7069. }
  7070. class TypeScriptScopeHandler extends ScopeHandler {
  7071. constructor(...args) {
  7072. super(...args);
  7073. this.importsStack = [];
  7074. }
  7075. createScope(flags) {
  7076. this.importsStack.push(new Set());
  7077. return new TypeScriptScope(flags);
  7078. }
  7079. enter(flags) {
  7080. if (flags == SCOPE_TS_MODULE) {
  7081. this.importsStack.push(new Set());
  7082. }
  7083. super.enter(flags);
  7084. }
  7085. exit() {
  7086. const flags = super.exit();
  7087. if (flags == SCOPE_TS_MODULE) {
  7088. this.importsStack.pop();
  7089. }
  7090. return flags;
  7091. }
  7092. hasImport(name, allowShadow) {
  7093. const len = this.importsStack.length;
  7094. if (this.importsStack[len - 1].has(name)) {
  7095. return true;
  7096. }
  7097. if (!allowShadow && len > 1) {
  7098. for (let i = 0; i < len - 1; i++) {
  7099. if (this.importsStack[i].has(name)) return true;
  7100. }
  7101. }
  7102. return false;
  7103. }
  7104. declareName(name, bindingType, loc) {
  7105. if (bindingType & BIND_FLAGS_TS_IMPORT) {
  7106. if (this.hasImport(name, true)) {
  7107. this.parser.raise(Errors.VarRedeclaration, {
  7108. at: loc,
  7109. identifierName: name
  7110. });
  7111. }
  7112. this.importsStack[this.importsStack.length - 1].add(name);
  7113. return;
  7114. }
  7115. const scope = this.currentScope();
  7116. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  7117. this.maybeExportDefined(scope, name);
  7118. scope.exportOnlyBindings.add(name);
  7119. return;
  7120. }
  7121. super.declareName(name, bindingType, loc);
  7122. if (bindingType & BIND_KIND_TYPE) {
  7123. if (!(bindingType & BIND_KIND_VALUE)) {
  7124. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  7125. this.maybeExportDefined(scope, name);
  7126. }
  7127. scope.types.add(name);
  7128. }
  7129. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name);
  7130. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
  7131. if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name);
  7132. }
  7133. isRedeclaredInScope(scope, name, bindingType) {
  7134. if (scope.enums.has(name)) {
  7135. if (bindingType & BIND_FLAGS_TS_ENUM) {
  7136. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  7137. const wasConst = scope.constEnums.has(name);
  7138. return isConst !== wasConst;
  7139. }
  7140. return true;
  7141. }
  7142. if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
  7143. if (scope.lexical.has(name)) {
  7144. return !!(bindingType & BIND_KIND_VALUE);
  7145. } else {
  7146. return false;
  7147. }
  7148. }
  7149. if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
  7150. return true;
  7151. }
  7152. return super.isRedeclaredInScope(scope, name, bindingType);
  7153. }
  7154. checkLocalExport(id) {
  7155. const {
  7156. name
  7157. } = id;
  7158. if (this.hasImport(name)) return;
  7159. const len = this.scopeStack.length;
  7160. for (let i = len - 1; i >= 0; i--) {
  7161. const scope = this.scopeStack[i];
  7162. if (scope.types.has(name) || scope.exportOnlyBindings.has(name)) return;
  7163. }
  7164. super.checkLocalExport(id);
  7165. }
  7166. }
  7167. const getOwn$1 = (object, key) => Object.hasOwnProperty.call(object, key) && object[key];
  7168. function nonNull(x) {
  7169. if (x == null) {
  7170. throw new Error(`Unexpected ${x} value.`);
  7171. }
  7172. return x;
  7173. }
  7174. function assert(x) {
  7175. if (!x) {
  7176. throw new Error("Assert fail");
  7177. }
  7178. }
  7179. const TSErrors = ParseErrorEnum`typescript`({
  7180. AbstractMethodHasImplementation: ({
  7181. methodName
  7182. }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  7183. AbstractPropertyHasInitializer: ({
  7184. propertyName
  7185. }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  7186. AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7187. AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7188. AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  7189. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7190. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7191. ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  7192. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7193. DeclareAccessor: ({
  7194. kind
  7195. }) => `'declare' is not allowed in ${kind}ters.`,
  7196. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7197. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7198. DuplicateAccessibilityModifier:
  7199. ({
  7200. modifier
  7201. }) => `Accessibility modifier already seen.`,
  7202. DuplicateModifier: ({
  7203. modifier
  7204. }) => `Duplicate modifier: '${modifier}'.`,
  7205. EmptyHeritageClauseType: ({
  7206. token
  7207. }) => `'${token}' list cannot be empty.`,
  7208. EmptyTypeArguments: "Type argument list cannot be empty.",
  7209. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7210. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7211. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7212. ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  7213. IncompatibleModifiers: ({
  7214. modifiers
  7215. }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  7216. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7217. IndexSignatureHasAccessibility: ({
  7218. modifier
  7219. }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  7220. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7221. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7222. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7223. InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  7224. InvalidModifierOnTypeMember: ({
  7225. modifier
  7226. }) => `'${modifier}' modifier cannot appear on a type member.`,
  7227. InvalidModifierOnTypeParameter: ({
  7228. modifier
  7229. }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  7230. InvalidModifierOnTypeParameterPositions: ({
  7231. modifier
  7232. }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  7233. InvalidModifiersOrder: ({
  7234. orderedModifiers
  7235. }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  7236. InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  7237. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7238. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7239. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  7240. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7241. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7242. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7243. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7244. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7245. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7246. PrivateElementHasAccessibility: ({
  7247. modifier
  7248. }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  7249. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7250. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7251. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7252. SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7253. SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7254. SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7255. SingleTypeParameterWithoutTrailingComma: ({
  7256. typeParameterName
  7257. }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  7258. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7259. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7260. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7261. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7262. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7263. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7264. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7265. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7266. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7267. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7268. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7269. UnsupportedSignatureParameterKind: ({
  7270. type
  7271. }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`
  7272. });
  7273. function keywordTypeFromName(value) {
  7274. switch (value) {
  7275. case "any":
  7276. return "TSAnyKeyword";
  7277. case "boolean":
  7278. return "TSBooleanKeyword";
  7279. case "bigint":
  7280. return "TSBigIntKeyword";
  7281. case "never":
  7282. return "TSNeverKeyword";
  7283. case "number":
  7284. return "TSNumberKeyword";
  7285. case "object":
  7286. return "TSObjectKeyword";
  7287. case "string":
  7288. return "TSStringKeyword";
  7289. case "symbol":
  7290. return "TSSymbolKeyword";
  7291. case "undefined":
  7292. return "TSUndefinedKeyword";
  7293. case "unknown":
  7294. return "TSUnknownKeyword";
  7295. default:
  7296. return undefined;
  7297. }
  7298. }
  7299. function tsIsAccessModifier(modifier) {
  7300. return modifier === "private" || modifier === "public" || modifier === "protected";
  7301. }
  7302. function tsIsVarianceAnnotations(modifier) {
  7303. return modifier === "in" || modifier === "out";
  7304. }
  7305. var typescript = (superClass => class TypeScriptParserMixin extends superClass {
  7306. getScopeHandler() {
  7307. return TypeScriptScopeHandler;
  7308. }
  7309. tsIsIdentifier() {
  7310. return tokenIsIdentifier(this.state.type);
  7311. }
  7312. tsTokenCanFollowModifier() {
  7313. return (this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(136) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  7314. }
  7315. tsNextTokenCanFollowModifier() {
  7316. this.next();
  7317. return this.tsTokenCanFollowModifier();
  7318. }
  7319. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7320. if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58) {
  7321. return undefined;
  7322. }
  7323. const modifier = this.state.value;
  7324. if (allowedModifiers.indexOf(modifier) !== -1) {
  7325. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7326. return undefined;
  7327. }
  7328. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7329. return modifier;
  7330. }
  7331. }
  7332. return undefined;
  7333. }
  7334. tsParseModifiers({
  7335. modified,
  7336. allowedModifiers,
  7337. disallowedModifiers,
  7338. stopOnStartOfClassStaticBlock,
  7339. errorTemplate = TSErrors.InvalidModifierOnTypeMember
  7340. }) {
  7341. const enforceOrder = (loc, modifier, before, after) => {
  7342. if (modifier === before && modified[after]) {
  7343. this.raise(TSErrors.InvalidModifiersOrder, {
  7344. at: loc,
  7345. orderedModifiers: [before, after]
  7346. });
  7347. }
  7348. };
  7349. const incompatible = (loc, modifier, mod1, mod2) => {
  7350. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7351. this.raise(TSErrors.IncompatibleModifiers, {
  7352. at: loc,
  7353. modifiers: [mod1, mod2]
  7354. });
  7355. }
  7356. };
  7357. for (;;) {
  7358. const {
  7359. startLoc
  7360. } = this.state;
  7361. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7362. if (!modifier) break;
  7363. if (tsIsAccessModifier(modifier)) {
  7364. if (modified.accessibility) {
  7365. this.raise(TSErrors.DuplicateAccessibilityModifier, {
  7366. at: startLoc,
  7367. modifier
  7368. });
  7369. } else {
  7370. enforceOrder(startLoc, modifier, modifier, "override");
  7371. enforceOrder(startLoc, modifier, modifier, "static");
  7372. enforceOrder(startLoc, modifier, modifier, "readonly");
  7373. modified.accessibility = modifier;
  7374. }
  7375. } else if (tsIsVarianceAnnotations(modifier)) {
  7376. if (modified[modifier]) {
  7377. this.raise(TSErrors.DuplicateModifier, {
  7378. at: startLoc,
  7379. modifier
  7380. });
  7381. }
  7382. modified[modifier] = true;
  7383. enforceOrder(startLoc, modifier, "in", "out");
  7384. } else {
  7385. if (Object.hasOwnProperty.call(modified, modifier)) {
  7386. this.raise(TSErrors.DuplicateModifier, {
  7387. at: startLoc,
  7388. modifier
  7389. });
  7390. } else {
  7391. enforceOrder(startLoc, modifier, "static", "readonly");
  7392. enforceOrder(startLoc, modifier, "static", "override");
  7393. enforceOrder(startLoc, modifier, "override", "readonly");
  7394. enforceOrder(startLoc, modifier, "abstract", "override");
  7395. incompatible(startLoc, modifier, "declare", "override");
  7396. incompatible(startLoc, modifier, "static", "abstract");
  7397. }
  7398. modified[modifier] = true;
  7399. }
  7400. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7401. this.raise(errorTemplate, {
  7402. at: startLoc,
  7403. modifier
  7404. });
  7405. }
  7406. }
  7407. }
  7408. tsIsListTerminator(kind) {
  7409. switch (kind) {
  7410. case "EnumMembers":
  7411. case "TypeMembers":
  7412. return this.match(8);
  7413. case "HeritageClauseElement":
  7414. return this.match(5);
  7415. case "TupleElementTypes":
  7416. return this.match(3);
  7417. case "TypeParametersOrArguments":
  7418. return this.match(48);
  7419. }
  7420. throw new Error("Unreachable");
  7421. }
  7422. tsParseList(kind, parseElement) {
  7423. const result = [];
  7424. while (!this.tsIsListTerminator(kind)) {
  7425. result.push(parseElement());
  7426. }
  7427. return result;
  7428. }
  7429. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7430. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7431. }
  7432. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7433. const result = [];
  7434. let trailingCommaPos = -1;
  7435. for (;;) {
  7436. if (this.tsIsListTerminator(kind)) {
  7437. break;
  7438. }
  7439. trailingCommaPos = -1;
  7440. const element = parseElement();
  7441. if (element == null) {
  7442. return undefined;
  7443. }
  7444. result.push(element);
  7445. if (this.eat(12)) {
  7446. trailingCommaPos = this.state.lastTokStart;
  7447. continue;
  7448. }
  7449. if (this.tsIsListTerminator(kind)) {
  7450. break;
  7451. }
  7452. if (expectSuccess) {
  7453. this.expect(12);
  7454. }
  7455. return undefined;
  7456. }
  7457. if (refTrailingCommaPos) {
  7458. refTrailingCommaPos.value = trailingCommaPos;
  7459. }
  7460. return result;
  7461. }
  7462. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7463. if (!skipFirstToken) {
  7464. if (bracket) {
  7465. this.expect(0);
  7466. } else {
  7467. this.expect(47);
  7468. }
  7469. }
  7470. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7471. if (bracket) {
  7472. this.expect(3);
  7473. } else {
  7474. this.expect(48);
  7475. }
  7476. return result;
  7477. }
  7478. tsParseImportType() {
  7479. const node = this.startNode();
  7480. this.expect(83);
  7481. this.expect(10);
  7482. if (!this.match(131)) {
  7483. this.raise(TSErrors.UnsupportedImportTypeArgument, {
  7484. at: this.state.startLoc
  7485. });
  7486. }
  7487. node.argument = super.parseExprAtom();
  7488. this.expect(11);
  7489. if (this.eat(16)) {
  7490. node.qualifier = this.tsParseEntityName();
  7491. }
  7492. if (this.match(47)) {
  7493. node.typeParameters = this.tsParseTypeArguments();
  7494. }
  7495. return this.finishNode(node, "TSImportType");
  7496. }
  7497. tsParseEntityName(allowReservedWords = true) {
  7498. let entity = this.parseIdentifier(allowReservedWords);
  7499. while (this.eat(16)) {
  7500. const node = this.startNodeAtNode(entity);
  7501. node.left = entity;
  7502. node.right = this.parseIdentifier(allowReservedWords);
  7503. entity = this.finishNode(node, "TSQualifiedName");
  7504. }
  7505. return entity;
  7506. }
  7507. tsParseTypeReference() {
  7508. const node = this.startNode();
  7509. node.typeName = this.tsParseEntityName();
  7510. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7511. node.typeParameters = this.tsParseTypeArguments();
  7512. }
  7513. return this.finishNode(node, "TSTypeReference");
  7514. }
  7515. tsParseThisTypePredicate(lhs) {
  7516. this.next();
  7517. const node = this.startNodeAtNode(lhs);
  7518. node.parameterName = lhs;
  7519. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7520. node.asserts = false;
  7521. return this.finishNode(node, "TSTypePredicate");
  7522. }
  7523. tsParseThisTypeNode() {
  7524. const node = this.startNode();
  7525. this.next();
  7526. return this.finishNode(node, "TSThisType");
  7527. }
  7528. tsParseTypeQuery() {
  7529. const node = this.startNode();
  7530. this.expect(87);
  7531. if (this.match(83)) {
  7532. node.exprName = this.tsParseImportType();
  7533. } else {
  7534. node.exprName = this.tsParseEntityName();
  7535. }
  7536. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7537. node.typeParameters = this.tsParseTypeArguments();
  7538. }
  7539. return this.finishNode(node, "TSTypeQuery");
  7540. }
  7541. tsParseInOutModifiers(node) {
  7542. this.tsParseModifiers({
  7543. modified: node,
  7544. allowedModifiers: ["in", "out"],
  7545. disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
  7546. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  7547. });
  7548. }
  7549. tsParseNoneModifiers(node) {
  7550. this.tsParseModifiers({
  7551. modified: node,
  7552. allowedModifiers: [],
  7553. disallowedModifiers: ["in", "out"],
  7554. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  7555. });
  7556. }
  7557. tsParseTypeParameter(parseModifiers = this.tsParseNoneModifiers.bind(this)) {
  7558. const node = this.startNode();
  7559. parseModifiers(node);
  7560. node.name = this.tsParseTypeParameterName();
  7561. node.constraint = this.tsEatThenParseType(81);
  7562. node.default = this.tsEatThenParseType(29);
  7563. return this.finishNode(node, "TSTypeParameter");
  7564. }
  7565. tsTryParseTypeParameters(parseModifiers) {
  7566. if (this.match(47)) {
  7567. return this.tsParseTypeParameters(parseModifiers);
  7568. }
  7569. }
  7570. tsParseTypeParameters(parseModifiers) {
  7571. const node = this.startNode();
  7572. if (this.match(47) || this.match(140)) {
  7573. this.next();
  7574. } else {
  7575. this.unexpected();
  7576. }
  7577. const refTrailingCommaPos = {
  7578. value: -1
  7579. };
  7580. node.params = this.tsParseBracketedList("TypeParametersOrArguments",
  7581. this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
  7582. if (node.params.length === 0) {
  7583. this.raise(TSErrors.EmptyTypeParameters, {
  7584. at: node
  7585. });
  7586. }
  7587. if (refTrailingCommaPos.value !== -1) {
  7588. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7589. }
  7590. return this.finishNode(node, "TSTypeParameterDeclaration");
  7591. }
  7592. tsFillSignature(returnToken, signature) {
  7593. const returnTokenRequired = returnToken === 19;
  7594. const paramsKey = "parameters";
  7595. const returnTypeKey = "typeAnnotation";
  7596. signature.typeParameters = this.tsTryParseTypeParameters();
  7597. this.expect(10);
  7598. signature[paramsKey] = this.tsParseBindingListForSignature();
  7599. if (returnTokenRequired) {
  7600. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7601. } else if (this.match(returnToken)) {
  7602. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7603. }
  7604. }
  7605. tsParseBindingListForSignature() {
  7606. return super.parseBindingList(11, 41).map(pattern => {
  7607. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  7608. this.raise(TSErrors.UnsupportedSignatureParameterKind, {
  7609. at: pattern,
  7610. type: pattern.type
  7611. });
  7612. }
  7613. return pattern;
  7614. });
  7615. }
  7616. tsParseTypeMemberSemicolon() {
  7617. if (!this.eat(12) && !this.isLineTerminator()) {
  7618. this.expect(13);
  7619. }
  7620. }
  7621. tsParseSignatureMember(kind, node) {
  7622. this.tsFillSignature(14, node);
  7623. this.tsParseTypeMemberSemicolon();
  7624. return this.finishNode(node, kind);
  7625. }
  7626. tsIsUnambiguouslyIndexSignature() {
  7627. this.next();
  7628. if (tokenIsIdentifier(this.state.type)) {
  7629. this.next();
  7630. return this.match(14);
  7631. }
  7632. return false;
  7633. }
  7634. tsTryParseIndexSignature(node) {
  7635. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  7636. return undefined;
  7637. }
  7638. this.expect(0);
  7639. const id = this.parseIdentifier();
  7640. id.typeAnnotation = this.tsParseTypeAnnotation();
  7641. this.resetEndLocation(id);
  7642. this.expect(3);
  7643. node.parameters = [id];
  7644. const type = this.tsTryParseTypeAnnotation();
  7645. if (type) node.typeAnnotation = type;
  7646. this.tsParseTypeMemberSemicolon();
  7647. return this.finishNode(node, "TSIndexSignature");
  7648. }
  7649. tsParsePropertyOrMethodSignature(node, readonly) {
  7650. if (this.eat(17)) node.optional = true;
  7651. const nodeAny = node;
  7652. if (this.match(10) || this.match(47)) {
  7653. if (readonly) {
  7654. this.raise(TSErrors.ReadonlyForMethodSignature, {
  7655. at: node
  7656. });
  7657. }
  7658. const method = nodeAny;
  7659. if (method.kind && this.match(47)) {
  7660. this.raise(TSErrors.AccesorCannotHaveTypeParameters, {
  7661. at: this.state.curPosition()
  7662. });
  7663. }
  7664. this.tsFillSignature(14, method);
  7665. this.tsParseTypeMemberSemicolon();
  7666. const paramsKey = "parameters";
  7667. const returnTypeKey = "typeAnnotation";
  7668. if (method.kind === "get") {
  7669. if (method[paramsKey].length > 0) {
  7670. this.raise(Errors.BadGetterArity, {
  7671. at: this.state.curPosition()
  7672. });
  7673. if (this.isThisParam(method[paramsKey][0])) {
  7674. this.raise(TSErrors.AccesorCannotDeclareThisParameter, {
  7675. at: this.state.curPosition()
  7676. });
  7677. }
  7678. }
  7679. } else if (method.kind === "set") {
  7680. if (method[paramsKey].length !== 1) {
  7681. this.raise(Errors.BadSetterArity, {
  7682. at: this.state.curPosition()
  7683. });
  7684. } else {
  7685. const firstParameter = method[paramsKey][0];
  7686. if (this.isThisParam(firstParameter)) {
  7687. this.raise(TSErrors.AccesorCannotDeclareThisParameter, {
  7688. at: this.state.curPosition()
  7689. });
  7690. }
  7691. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  7692. this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, {
  7693. at: this.state.curPosition()
  7694. });
  7695. }
  7696. if (firstParameter.type === "RestElement") {
  7697. this.raise(TSErrors.SetAccesorCannotHaveRestParameter, {
  7698. at: this.state.curPosition()
  7699. });
  7700. }
  7701. }
  7702. if (method[returnTypeKey]) {
  7703. this.raise(TSErrors.SetAccesorCannotHaveReturnType, {
  7704. at: method[returnTypeKey]
  7705. });
  7706. }
  7707. } else {
  7708. method.kind = "method";
  7709. }
  7710. return this.finishNode(method, "TSMethodSignature");
  7711. } else {
  7712. const property = nodeAny;
  7713. if (readonly) property.readonly = true;
  7714. const type = this.tsTryParseTypeAnnotation();
  7715. if (type) property.typeAnnotation = type;
  7716. this.tsParseTypeMemberSemicolon();
  7717. return this.finishNode(property, "TSPropertySignature");
  7718. }
  7719. }
  7720. tsParseTypeMember() {
  7721. const node = this.startNode();
  7722. if (this.match(10) || this.match(47)) {
  7723. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  7724. }
  7725. if (this.match(77)) {
  7726. const id = this.startNode();
  7727. this.next();
  7728. if (this.match(10) || this.match(47)) {
  7729. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  7730. } else {
  7731. node.key = this.createIdentifier(id, "new");
  7732. return this.tsParsePropertyOrMethodSignature(node, false);
  7733. }
  7734. }
  7735. this.tsParseModifiers({
  7736. modified: node,
  7737. allowedModifiers: ["readonly"],
  7738. disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
  7739. });
  7740. const idx = this.tsTryParseIndexSignature(node);
  7741. if (idx) {
  7742. return idx;
  7743. }
  7744. super.parsePropertyName(node);
  7745. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  7746. node.kind = node.key.name;
  7747. super.parsePropertyName(node);
  7748. }
  7749. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  7750. }
  7751. tsParseTypeLiteral() {
  7752. const node = this.startNode();
  7753. node.members = this.tsParseObjectTypeMembers();
  7754. return this.finishNode(node, "TSTypeLiteral");
  7755. }
  7756. tsParseObjectTypeMembers() {
  7757. this.expect(5);
  7758. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  7759. this.expect(8);
  7760. return members;
  7761. }
  7762. tsIsStartOfMappedType() {
  7763. this.next();
  7764. if (this.eat(53)) {
  7765. return this.isContextual(120);
  7766. }
  7767. if (this.isContextual(120)) {
  7768. this.next();
  7769. }
  7770. if (!this.match(0)) {
  7771. return false;
  7772. }
  7773. this.next();
  7774. if (!this.tsIsIdentifier()) {
  7775. return false;
  7776. }
  7777. this.next();
  7778. return this.match(58);
  7779. }
  7780. tsParseMappedTypeParameter() {
  7781. const node = this.startNode();
  7782. node.name = this.tsParseTypeParameterName();
  7783. node.constraint = this.tsExpectThenParseType(58);
  7784. return this.finishNode(node, "TSTypeParameter");
  7785. }
  7786. tsParseMappedType() {
  7787. const node = this.startNode();
  7788. this.expect(5);
  7789. if (this.match(53)) {
  7790. node.readonly = this.state.value;
  7791. this.next();
  7792. this.expectContextual(120);
  7793. } else if (this.eatContextual(120)) {
  7794. node.readonly = true;
  7795. }
  7796. this.expect(0);
  7797. node.typeParameter = this.tsParseMappedTypeParameter();
  7798. node.nameType = this.eatContextual(93) ? this.tsParseType() : null;
  7799. this.expect(3);
  7800. if (this.match(53)) {
  7801. node.optional = this.state.value;
  7802. this.next();
  7803. this.expect(17);
  7804. } else if (this.eat(17)) {
  7805. node.optional = true;
  7806. }
  7807. node.typeAnnotation = this.tsTryParseType();
  7808. this.semicolon();
  7809. this.expect(8);
  7810. return this.finishNode(node, "TSMappedType");
  7811. }
  7812. tsParseTupleType() {
  7813. const node = this.startNode();
  7814. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  7815. let seenOptionalElement = false;
  7816. let labeledElements = null;
  7817. node.elementTypes.forEach(elementNode => {
  7818. var _labeledElements;
  7819. const {
  7820. type
  7821. } = elementNode;
  7822. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  7823. this.raise(TSErrors.OptionalTypeBeforeRequired, {
  7824. at: elementNode
  7825. });
  7826. }
  7827. seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
  7828. let checkType = type;
  7829. if (type === "TSRestType") {
  7830. elementNode = elementNode.typeAnnotation;
  7831. checkType = elementNode.type;
  7832. }
  7833. const isLabeled = checkType === "TSNamedTupleMember";
  7834. (_labeledElements = labeledElements) != null ? _labeledElements : labeledElements = isLabeled;
  7835. if (labeledElements !== isLabeled) {
  7836. this.raise(TSErrors.MixedLabeledAndUnlabeledElements, {
  7837. at: elementNode
  7838. });
  7839. }
  7840. });
  7841. return this.finishNode(node, "TSTupleType");
  7842. }
  7843. tsParseTupleElementType() {
  7844. const {
  7845. startLoc
  7846. } = this.state;
  7847. const rest = this.eat(21);
  7848. let type = this.tsParseType();
  7849. const optional = this.eat(17);
  7850. const labeled = this.eat(14);
  7851. if (labeled) {
  7852. const labeledNode = this.startNodeAtNode(type);
  7853. labeledNode.optional = optional;
  7854. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  7855. labeledNode.label = type.typeName;
  7856. } else {
  7857. this.raise(TSErrors.InvalidTupleMemberLabel, {
  7858. at: type
  7859. });
  7860. labeledNode.label = type;
  7861. }
  7862. labeledNode.elementType = this.tsParseType();
  7863. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  7864. } else if (optional) {
  7865. const optionalTypeNode = this.startNodeAtNode(type);
  7866. optionalTypeNode.typeAnnotation = type;
  7867. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  7868. }
  7869. if (rest) {
  7870. const restNode = this.startNodeAt(startLoc);
  7871. restNode.typeAnnotation = type;
  7872. type = this.finishNode(restNode, "TSRestType");
  7873. }
  7874. return type;
  7875. }
  7876. tsParseParenthesizedType() {
  7877. const node = this.startNode();
  7878. this.expect(10);
  7879. node.typeAnnotation = this.tsParseType();
  7880. this.expect(11);
  7881. return this.finishNode(node, "TSParenthesizedType");
  7882. }
  7883. tsParseFunctionOrConstructorType(type, abstract) {
  7884. const node = this.startNode();
  7885. if (type === "TSConstructorType") {
  7886. node.abstract = !!abstract;
  7887. if (abstract) this.next();
  7888. this.next();
  7889. }
  7890. this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node));
  7891. return this.finishNode(node, type);
  7892. }
  7893. tsParseLiteralTypeNode() {
  7894. const node = this.startNode();
  7895. node.literal = (() => {
  7896. switch (this.state.type) {
  7897. case 132:
  7898. case 133:
  7899. case 131:
  7900. case 85:
  7901. case 86:
  7902. return super.parseExprAtom();
  7903. default:
  7904. throw this.unexpected();
  7905. }
  7906. })();
  7907. return this.finishNode(node, "TSLiteralType");
  7908. }
  7909. tsParseTemplateLiteralType() {
  7910. const node = this.startNode();
  7911. node.literal = super.parseTemplate(false);
  7912. return this.finishNode(node, "TSLiteralType");
  7913. }
  7914. parseTemplateSubstitution() {
  7915. if (this.state.inType) return this.tsParseType();
  7916. return super.parseTemplateSubstitution();
  7917. }
  7918. tsParseThisTypeOrThisTypePredicate() {
  7919. const thisKeyword = this.tsParseThisTypeNode();
  7920. if (this.isContextual(114) && !this.hasPrecedingLineBreak()) {
  7921. return this.tsParseThisTypePredicate(thisKeyword);
  7922. } else {
  7923. return thisKeyword;
  7924. }
  7925. }
  7926. tsParseNonArrayType() {
  7927. switch (this.state.type) {
  7928. case 131:
  7929. case 132:
  7930. case 133:
  7931. case 85:
  7932. case 86:
  7933. return this.tsParseLiteralTypeNode();
  7934. case 53:
  7935. if (this.state.value === "-") {
  7936. const node = this.startNode();
  7937. const nextToken = this.lookahead();
  7938. if (nextToken.type !== 132 && nextToken.type !== 133) {
  7939. throw this.unexpected();
  7940. }
  7941. node.literal = this.parseMaybeUnary();
  7942. return this.finishNode(node, "TSLiteralType");
  7943. }
  7944. break;
  7945. case 78:
  7946. return this.tsParseThisTypeOrThisTypePredicate();
  7947. case 87:
  7948. return this.tsParseTypeQuery();
  7949. case 83:
  7950. return this.tsParseImportType();
  7951. case 5:
  7952. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  7953. case 0:
  7954. return this.tsParseTupleType();
  7955. case 10:
  7956. return this.tsParseParenthesizedType();
  7957. case 25:
  7958. case 24:
  7959. return this.tsParseTemplateLiteralType();
  7960. default:
  7961. {
  7962. const {
  7963. type
  7964. } = this.state;
  7965. if (tokenIsIdentifier(type) || type === 88 || type === 84) {
  7966. const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  7967. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  7968. const node = this.startNode();
  7969. this.next();
  7970. return this.finishNode(node, nodeType);
  7971. }
  7972. return this.tsParseTypeReference();
  7973. }
  7974. }
  7975. }
  7976. throw this.unexpected();
  7977. }
  7978. tsParseArrayTypeOrHigher() {
  7979. let type = this.tsParseNonArrayType();
  7980. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  7981. if (this.match(3)) {
  7982. const node = this.startNodeAtNode(type);
  7983. node.elementType = type;
  7984. this.expect(3);
  7985. type = this.finishNode(node, "TSArrayType");
  7986. } else {
  7987. const node = this.startNodeAtNode(type);
  7988. node.objectType = type;
  7989. node.indexType = this.tsParseType();
  7990. this.expect(3);
  7991. type = this.finishNode(node, "TSIndexedAccessType");
  7992. }
  7993. }
  7994. return type;
  7995. }
  7996. tsParseTypeOperator() {
  7997. const node = this.startNode();
  7998. const operator = this.state.value;
  7999. this.next();
  8000. node.operator = operator;
  8001. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  8002. if (operator === "readonly") {
  8003. this.tsCheckTypeAnnotationForReadOnly(
  8004. node);
  8005. }
  8006. return this.finishNode(node, "TSTypeOperator");
  8007. }
  8008. tsCheckTypeAnnotationForReadOnly(node) {
  8009. switch (node.typeAnnotation.type) {
  8010. case "TSTupleType":
  8011. case "TSArrayType":
  8012. return;
  8013. default:
  8014. this.raise(TSErrors.UnexpectedReadonly, {
  8015. at: node
  8016. });
  8017. }
  8018. }
  8019. tsParseInferType() {
  8020. const node = this.startNode();
  8021. this.expectContextual(113);
  8022. const typeParameter = this.startNode();
  8023. typeParameter.name = this.tsParseTypeParameterName();
  8024. typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
  8025. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  8026. return this.finishNode(node, "TSInferType");
  8027. }
  8028. tsParseConstraintForInferType() {
  8029. if (this.eat(81)) {
  8030. const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
  8031. if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
  8032. return constraint;
  8033. }
  8034. }
  8035. }
  8036. tsParseTypeOperatorOrHigher() {
  8037. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  8038. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(113) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  8039. }
  8040. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  8041. const node = this.startNode();
  8042. const hasLeadingOperator = this.eat(operator);
  8043. const types = [];
  8044. do {
  8045. types.push(parseConstituentType());
  8046. } while (this.eat(operator));
  8047. if (types.length === 1 && !hasLeadingOperator) {
  8048. return types[0];
  8049. }
  8050. node.types = types;
  8051. return this.finishNode(node, kind);
  8052. }
  8053. tsParseIntersectionTypeOrHigher() {
  8054. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  8055. }
  8056. tsParseUnionTypeOrHigher() {
  8057. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  8058. }
  8059. tsIsStartOfFunctionType() {
  8060. if (this.match(47)) {
  8061. return true;
  8062. }
  8063. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  8064. }
  8065. tsSkipParameterStart() {
  8066. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  8067. this.next();
  8068. return true;
  8069. }
  8070. if (this.match(5)) {
  8071. const {
  8072. errors
  8073. } = this.state;
  8074. const previousErrorCount = errors.length;
  8075. try {
  8076. this.parseObjectLike(8, true);
  8077. return errors.length === previousErrorCount;
  8078. } catch (_unused) {
  8079. return false;
  8080. }
  8081. }
  8082. if (this.match(0)) {
  8083. this.next();
  8084. const {
  8085. errors
  8086. } = this.state;
  8087. const previousErrorCount = errors.length;
  8088. try {
  8089. super.parseBindingList(3, 93, true);
  8090. return errors.length === previousErrorCount;
  8091. } catch (_unused2) {
  8092. return false;
  8093. }
  8094. }
  8095. return false;
  8096. }
  8097. tsIsUnambiguouslyStartOfFunctionType() {
  8098. this.next();
  8099. if (this.match(11) || this.match(21)) {
  8100. return true;
  8101. }
  8102. if (this.tsSkipParameterStart()) {
  8103. if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
  8104. return true;
  8105. }
  8106. if (this.match(11)) {
  8107. this.next();
  8108. if (this.match(19)) {
  8109. return true;
  8110. }
  8111. }
  8112. }
  8113. return false;
  8114. }
  8115. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  8116. return this.tsInType(() => {
  8117. const t = this.startNode();
  8118. this.expect(returnToken);
  8119. const node = this.startNode();
  8120. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  8121. if (asserts && this.match(78)) {
  8122. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  8123. if (thisTypePredicate.type === "TSThisType") {
  8124. node.parameterName = thisTypePredicate;
  8125. node.asserts = true;
  8126. node.typeAnnotation = null;
  8127. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  8128. } else {
  8129. this.resetStartLocationFromNode(thisTypePredicate, node);
  8130. thisTypePredicate.asserts = true;
  8131. }
  8132. t.typeAnnotation = thisTypePredicate;
  8133. return this.finishNode(t, "TSTypeAnnotation");
  8134. }
  8135. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  8136. if (!typePredicateVariable) {
  8137. if (!asserts) {
  8138. return this.tsParseTypeAnnotation(false, t);
  8139. }
  8140. node.parameterName = this.parseIdentifier();
  8141. node.asserts = asserts;
  8142. node.typeAnnotation = null;
  8143. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8144. return this.finishNode(t, "TSTypeAnnotation");
  8145. }
  8146. const type = this.tsParseTypeAnnotation(false);
  8147. node.parameterName = typePredicateVariable;
  8148. node.typeAnnotation = type;
  8149. node.asserts = asserts;
  8150. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8151. return this.finishNode(t, "TSTypeAnnotation");
  8152. });
  8153. }
  8154. tsTryParseTypeOrTypePredicateAnnotation() {
  8155. return this.match(14) ? this.tsParseTypeOrTypePredicateAnnotation(14) : undefined;
  8156. }
  8157. tsTryParseTypeAnnotation() {
  8158. return this.match(14) ? this.tsParseTypeAnnotation() : undefined;
  8159. }
  8160. tsTryParseType() {
  8161. return this.tsEatThenParseType(14);
  8162. }
  8163. tsParseTypePredicatePrefix() {
  8164. const id = this.parseIdentifier();
  8165. if (this.isContextual(114) && !this.hasPrecedingLineBreak()) {
  8166. this.next();
  8167. return id;
  8168. }
  8169. }
  8170. tsParseTypePredicateAsserts() {
  8171. if (this.state.type !== 107) {
  8172. return false;
  8173. }
  8174. const containsEsc = this.state.containsEsc;
  8175. this.next();
  8176. if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
  8177. return false;
  8178. }
  8179. if (containsEsc) {
  8180. this.raise(Errors.InvalidEscapedReservedWord, {
  8181. at: this.state.lastTokStartLoc,
  8182. reservedWord: "asserts"
  8183. });
  8184. }
  8185. return true;
  8186. }
  8187. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8188. this.tsInType(() => {
  8189. if (eatColon) this.expect(14);
  8190. t.typeAnnotation = this.tsParseType();
  8191. });
  8192. return this.finishNode(t, "TSTypeAnnotation");
  8193. }
  8194. tsParseType() {
  8195. assert(this.state.inType);
  8196. const type = this.tsParseNonConditionalType();
  8197. if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
  8198. return type;
  8199. }
  8200. const node = this.startNodeAtNode(type);
  8201. node.checkType = type;
  8202. node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
  8203. this.expect(17);
  8204. node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8205. this.expect(14);
  8206. node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8207. return this.finishNode(node, "TSConditionalType");
  8208. }
  8209. isAbstractConstructorSignature() {
  8210. return this.isContextual(122) && this.lookahead().type === 77;
  8211. }
  8212. tsParseNonConditionalType() {
  8213. if (this.tsIsStartOfFunctionType()) {
  8214. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8215. }
  8216. if (this.match(77)) {
  8217. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8218. } else if (this.isAbstractConstructorSignature()) {
  8219. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8220. }
  8221. return this.tsParseUnionTypeOrHigher();
  8222. }
  8223. tsParseTypeAssertion() {
  8224. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8225. this.raise(TSErrors.ReservedTypeAssertion, {
  8226. at: this.state.startLoc
  8227. });
  8228. }
  8229. const node = this.startNode();
  8230. node.typeAnnotation = this.tsInType(() => {
  8231. this.next();
  8232. return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
  8233. });
  8234. this.expect(48);
  8235. node.expression = this.parseMaybeUnary();
  8236. return this.finishNode(node, "TSTypeAssertion");
  8237. }
  8238. tsParseHeritageClause(token) {
  8239. const originalStartLoc = this.state.startLoc;
  8240. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
  8241. const node = this.startNode();
  8242. node.expression = this.tsParseEntityName();
  8243. if (this.match(47)) {
  8244. node.typeParameters = this.tsParseTypeArguments();
  8245. }
  8246. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8247. });
  8248. if (!delimitedList.length) {
  8249. this.raise(TSErrors.EmptyHeritageClauseType, {
  8250. at: originalStartLoc,
  8251. token
  8252. });
  8253. }
  8254. return delimitedList;
  8255. }
  8256. tsParseInterfaceDeclaration(node, properties = {}) {
  8257. if (this.hasFollowingLineBreak()) return null;
  8258. this.expectContextual(127);
  8259. if (properties.declare) node.declare = true;
  8260. if (tokenIsIdentifier(this.state.type)) {
  8261. node.id = this.parseIdentifier();
  8262. this.checkIdentifier(node.id, BIND_TS_INTERFACE);
  8263. } else {
  8264. node.id = null;
  8265. this.raise(TSErrors.MissingInterfaceName, {
  8266. at: this.state.startLoc
  8267. });
  8268. }
  8269. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers.bind(this));
  8270. if (this.eat(81)) {
  8271. node.extends = this.tsParseHeritageClause("extends");
  8272. }
  8273. const body = this.startNode();
  8274. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8275. node.body = this.finishNode(body, "TSInterfaceBody");
  8276. return this.finishNode(node, "TSInterfaceDeclaration");
  8277. }
  8278. tsParseTypeAliasDeclaration(node) {
  8279. node.id = this.parseIdentifier();
  8280. this.checkIdentifier(node.id, BIND_TS_TYPE);
  8281. node.typeAnnotation = this.tsInType(() => {
  8282. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers.bind(this));
  8283. this.expect(29);
  8284. if (this.isContextual(112) && this.lookahead().type !== 16) {
  8285. const node = this.startNode();
  8286. this.next();
  8287. return this.finishNode(node, "TSIntrinsicKeyword");
  8288. }
  8289. return this.tsParseType();
  8290. });
  8291. this.semicolon();
  8292. return this.finishNode(node, "TSTypeAliasDeclaration");
  8293. }
  8294. tsInNoContext(cb) {
  8295. const oldContext = this.state.context;
  8296. this.state.context = [oldContext[0]];
  8297. try {
  8298. return cb();
  8299. } finally {
  8300. this.state.context = oldContext;
  8301. }
  8302. }
  8303. tsInType(cb) {
  8304. const oldInType = this.state.inType;
  8305. this.state.inType = true;
  8306. try {
  8307. return cb();
  8308. } finally {
  8309. this.state.inType = oldInType;
  8310. }
  8311. }
  8312. tsInDisallowConditionalTypesContext(cb) {
  8313. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8314. this.state.inDisallowConditionalTypesContext = true;
  8315. try {
  8316. return cb();
  8317. } finally {
  8318. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8319. }
  8320. }
  8321. tsInAllowConditionalTypesContext(cb) {
  8322. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8323. this.state.inDisallowConditionalTypesContext = false;
  8324. try {
  8325. return cb();
  8326. } finally {
  8327. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8328. }
  8329. }
  8330. tsEatThenParseType(token) {
  8331. return !this.match(token) ? undefined : this.tsNextThenParseType();
  8332. }
  8333. tsExpectThenParseType(token) {
  8334. return this.tsDoThenParseType(() => this.expect(token));
  8335. }
  8336. tsNextThenParseType() {
  8337. return this.tsDoThenParseType(() => this.next());
  8338. }
  8339. tsDoThenParseType(cb) {
  8340. return this.tsInType(() => {
  8341. cb();
  8342. return this.tsParseType();
  8343. });
  8344. }
  8345. tsParseEnumMember() {
  8346. const node = this.startNode();
  8347. node.id = this.match(131) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
  8348. if (this.eat(29)) {
  8349. node.initializer = super.parseMaybeAssignAllowIn();
  8350. }
  8351. return this.finishNode(node, "TSEnumMember");
  8352. }
  8353. tsParseEnumDeclaration(node, properties = {}) {
  8354. if (properties.const) node.const = true;
  8355. if (properties.declare) node.declare = true;
  8356. this.expectContextual(124);
  8357. node.id = this.parseIdentifier();
  8358. this.checkIdentifier(node.id, node.const ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  8359. this.expect(5);
  8360. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8361. this.expect(8);
  8362. return this.finishNode(node, "TSEnumDeclaration");
  8363. }
  8364. tsParseModuleBlock() {
  8365. const node = this.startNode();
  8366. this.scope.enter(SCOPE_OTHER);
  8367. this.expect(5);
  8368. super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8369. this.scope.exit();
  8370. return this.finishNode(node, "TSModuleBlock");
  8371. }
  8372. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8373. node.id = this.parseIdentifier();
  8374. if (!nested) {
  8375. this.checkIdentifier(node.id, BIND_TS_NAMESPACE);
  8376. }
  8377. if (this.eat(16)) {
  8378. const inner = this.startNode();
  8379. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8380. node.body = inner;
  8381. } else {
  8382. this.scope.enter(SCOPE_TS_MODULE);
  8383. this.prodParam.enter(PARAM);
  8384. node.body = this.tsParseModuleBlock();
  8385. this.prodParam.exit();
  8386. this.scope.exit();
  8387. }
  8388. return this.finishNode(node, "TSModuleDeclaration");
  8389. }
  8390. tsParseAmbientExternalModuleDeclaration(node) {
  8391. if (this.isContextual(110)) {
  8392. node.global = true;
  8393. node.id = this.parseIdentifier();
  8394. } else if (this.match(131)) {
  8395. node.id = super.parseStringLiteral(this.state.value);
  8396. } else {
  8397. this.unexpected();
  8398. }
  8399. if (this.match(5)) {
  8400. this.scope.enter(SCOPE_TS_MODULE);
  8401. this.prodParam.enter(PARAM);
  8402. node.body = this.tsParseModuleBlock();
  8403. this.prodParam.exit();
  8404. this.scope.exit();
  8405. } else {
  8406. this.semicolon();
  8407. }
  8408. return this.finishNode(node, "TSModuleDeclaration");
  8409. }
  8410. tsParseImportEqualsDeclaration(node, isExport) {
  8411. node.isExport = isExport || false;
  8412. node.id = this.parseIdentifier();
  8413. this.checkIdentifier(node.id, BIND_FLAGS_TS_IMPORT);
  8414. this.expect(29);
  8415. const moduleReference = this.tsParseModuleReference();
  8416. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8417. this.raise(TSErrors.ImportAliasHasImportType, {
  8418. at: moduleReference
  8419. });
  8420. }
  8421. node.moduleReference = moduleReference;
  8422. this.semicolon();
  8423. return this.finishNode(node, "TSImportEqualsDeclaration");
  8424. }
  8425. tsIsExternalModuleReference() {
  8426. return this.isContextual(117) && this.lookaheadCharCode() === 40;
  8427. }
  8428. tsParseModuleReference() {
  8429. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  8430. }
  8431. tsParseExternalModuleReference() {
  8432. const node = this.startNode();
  8433. this.expectContextual(117);
  8434. this.expect(10);
  8435. if (!this.match(131)) {
  8436. throw this.unexpected();
  8437. }
  8438. node.expression = super.parseExprAtom();
  8439. this.expect(11);
  8440. return this.finishNode(node, "TSExternalModuleReference");
  8441. }
  8442. tsLookAhead(f) {
  8443. const state = this.state.clone();
  8444. const res = f();
  8445. this.state = state;
  8446. return res;
  8447. }
  8448. tsTryParseAndCatch(f) {
  8449. const result = this.tryParse(abort =>
  8450. f() || abort());
  8451. if (result.aborted || !result.node) return undefined;
  8452. if (result.error) this.state = result.failState;
  8453. return result.node;
  8454. }
  8455. tsTryParse(f) {
  8456. const state = this.state.clone();
  8457. const result = f();
  8458. if (result !== undefined && result !== false) {
  8459. return result;
  8460. } else {
  8461. this.state = state;
  8462. return undefined;
  8463. }
  8464. }
  8465. tsTryParseDeclare(nany) {
  8466. if (this.isLineTerminator()) {
  8467. return;
  8468. }
  8469. let starttype = this.state.type;
  8470. let kind;
  8471. if (this.isContextual(99)) {
  8472. starttype = 74;
  8473. kind = "let";
  8474. }
  8475. return this.tsInAmbientContext(() => {
  8476. if (starttype === 68) {
  8477. nany.declare = true;
  8478. return super.parseFunctionStatement(nany, false, false);
  8479. }
  8480. if (starttype === 80) {
  8481. nany.declare = true;
  8482. return this.parseClass(nany, true, false);
  8483. }
  8484. if (starttype === 124) {
  8485. return this.tsParseEnumDeclaration(nany, {
  8486. declare: true
  8487. });
  8488. }
  8489. if (starttype === 110) {
  8490. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8491. }
  8492. if (starttype === 75 || starttype === 74) {
  8493. if (!this.match(75) || !this.isLookaheadContextual("enum")) {
  8494. nany.declare = true;
  8495. return this.parseVarStatement(nany, kind || this.state.value, true);
  8496. }
  8497. this.expect(75);
  8498. return this.tsParseEnumDeclaration(nany, {
  8499. const: true,
  8500. declare: true
  8501. });
  8502. }
  8503. if (starttype === 127) {
  8504. const result = this.tsParseInterfaceDeclaration(nany, {
  8505. declare: true
  8506. });
  8507. if (result) return result;
  8508. }
  8509. if (tokenIsIdentifier(starttype)) {
  8510. return this.tsParseDeclaration(nany, this.state.value, true, null);
  8511. }
  8512. });
  8513. }
  8514. tsTryParseExportDeclaration() {
  8515. return this.tsParseDeclaration(this.startNode(), this.state.value, true, null);
  8516. }
  8517. tsParseExpressionStatement(node, expr, decorators) {
  8518. switch (expr.name) {
  8519. case "declare":
  8520. {
  8521. const declaration = this.tsTryParseDeclare(node);
  8522. if (declaration) {
  8523. declaration.declare = true;
  8524. return declaration;
  8525. }
  8526. break;
  8527. }
  8528. case "global":
  8529. if (this.match(5)) {
  8530. this.scope.enter(SCOPE_TS_MODULE);
  8531. this.prodParam.enter(PARAM);
  8532. const mod = node;
  8533. mod.global = true;
  8534. mod.id = expr;
  8535. mod.body = this.tsParseModuleBlock();
  8536. this.scope.exit();
  8537. this.prodParam.exit();
  8538. return this.finishNode(mod, "TSModuleDeclaration");
  8539. }
  8540. break;
  8541. default:
  8542. return this.tsParseDeclaration(node, expr.name, false, decorators);
  8543. }
  8544. }
  8545. tsParseDeclaration(node, value, next, decorators) {
  8546. switch (value) {
  8547. case "abstract":
  8548. if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
  8549. return this.tsParseAbstractDeclaration(node, decorators);
  8550. }
  8551. break;
  8552. case "module":
  8553. if (this.tsCheckLineTerminator(next)) {
  8554. if (this.match(131)) {
  8555. return this.tsParseAmbientExternalModuleDeclaration(node);
  8556. } else if (tokenIsIdentifier(this.state.type)) {
  8557. return this.tsParseModuleOrNamespaceDeclaration(node);
  8558. }
  8559. }
  8560. break;
  8561. case "namespace":
  8562. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8563. return this.tsParseModuleOrNamespaceDeclaration(node);
  8564. }
  8565. break;
  8566. case "type":
  8567. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8568. return this.tsParseTypeAliasDeclaration(node);
  8569. }
  8570. break;
  8571. }
  8572. }
  8573. tsCheckLineTerminator(next) {
  8574. if (next) {
  8575. if (this.hasFollowingLineBreak()) return false;
  8576. this.next();
  8577. return true;
  8578. }
  8579. return !this.isLineTerminator();
  8580. }
  8581. tsTryParseGenericAsyncArrowFunction(startLoc) {
  8582. if (!this.match(47)) {
  8583. return undefined;
  8584. }
  8585. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8586. this.state.maybeInArrowParameters = true;
  8587. const res = this.tsTryParseAndCatch(() => {
  8588. const node = this.startNodeAt(startLoc);
  8589. node.typeParameters = this.tsParseTypeParameters();
  8590. super.parseFunctionParams(node);
  8591. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8592. this.expect(19);
  8593. return node;
  8594. });
  8595. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8596. if (!res) {
  8597. return undefined;
  8598. }
  8599. return super.parseArrowExpression(res, null, true);
  8600. }
  8601. tsParseTypeArgumentsInExpression() {
  8602. if (this.reScan_lt() !== 47) {
  8603. return undefined;
  8604. }
  8605. return this.tsParseTypeArguments();
  8606. }
  8607. tsParseTypeArguments() {
  8608. const node = this.startNode();
  8609. node.params = this.tsInType(() =>
  8610. this.tsInNoContext(() => {
  8611. this.expect(47);
  8612. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  8613. }));
  8614. if (node.params.length === 0) {
  8615. this.raise(TSErrors.EmptyTypeArguments, {
  8616. at: node
  8617. });
  8618. }
  8619. this.expect(48);
  8620. return this.finishNode(node, "TSTypeParameterInstantiation");
  8621. }
  8622. tsIsDeclarationStart() {
  8623. return tokenIsTSDeclarationStart(this.state.type);
  8624. }
  8625. isExportDefaultSpecifier() {
  8626. if (this.tsIsDeclarationStart()) return false;
  8627. return super.isExportDefaultSpecifier();
  8628. }
  8629. parseAssignableListItem(allowModifiers, decorators) {
  8630. const startLoc = this.state.startLoc;
  8631. let accessibility;
  8632. let readonly = false;
  8633. let override = false;
  8634. if (allowModifiers !== undefined) {
  8635. const modified = {};
  8636. this.tsParseModifiers({
  8637. modified,
  8638. allowedModifiers: ["public", "private", "protected", "override", "readonly"]
  8639. });
  8640. accessibility = modified.accessibility;
  8641. override = modified.override;
  8642. readonly = modified.readonly;
  8643. if (allowModifiers === false && (accessibility || readonly || override)) {
  8644. this.raise(TSErrors.UnexpectedParameterModifier, {
  8645. at: startLoc
  8646. });
  8647. }
  8648. }
  8649. const left = this.parseMaybeDefault();
  8650. this.parseAssignableListItemTypes(left);
  8651. const elt = this.parseMaybeDefault(left.loc.start, left);
  8652. if (accessibility || readonly || override) {
  8653. const pp = this.startNodeAt(startLoc);
  8654. if (decorators.length) {
  8655. pp.decorators = decorators;
  8656. }
  8657. if (accessibility) pp.accessibility = accessibility;
  8658. if (readonly) pp.readonly = readonly;
  8659. if (override) pp.override = override;
  8660. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  8661. this.raise(TSErrors.UnsupportedParameterPropertyKind, {
  8662. at: pp
  8663. });
  8664. }
  8665. pp.parameter = elt;
  8666. return this.finishNode(pp, "TSParameterProperty");
  8667. }
  8668. if (decorators.length) {
  8669. left.decorators = decorators;
  8670. }
  8671. return elt;
  8672. }
  8673. isSimpleParameter(node) {
  8674. return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node);
  8675. }
  8676. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8677. if (this.match(14)) {
  8678. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  8679. }
  8680. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  8681. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  8682. return this.finishNode(node, bodilessType);
  8683. }
  8684. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  8685. this.raise(TSErrors.DeclareFunctionHasImplementation, {
  8686. at: node
  8687. });
  8688. if (node.declare) {
  8689. return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  8690. }
  8691. }
  8692. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  8693. }
  8694. registerFunctionStatementId(node) {
  8695. if (!node.body && node.id) {
  8696. this.checkIdentifier(node.id, BIND_TS_AMBIENT);
  8697. } else {
  8698. super.registerFunctionStatementId(node);
  8699. }
  8700. }
  8701. tsCheckForInvalidTypeCasts(items) {
  8702. items.forEach(node => {
  8703. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  8704. this.raise(TSErrors.UnexpectedTypeAnnotation, {
  8705. at: node.typeAnnotation
  8706. });
  8707. }
  8708. });
  8709. }
  8710. toReferencedList(exprList,
  8711. isInParens) {
  8712. this.tsCheckForInvalidTypeCasts(exprList);
  8713. return exprList;
  8714. }
  8715. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  8716. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  8717. if (node.type === "ArrayExpression") {
  8718. this.tsCheckForInvalidTypeCasts(node.elements);
  8719. }
  8720. return node;
  8721. }
  8722. parseSubscript(base, startLoc, noCalls, state) {
  8723. if (!this.hasPrecedingLineBreak() && this.match(35)) {
  8724. this.state.canStartJSXElement = false;
  8725. this.next();
  8726. const nonNullExpression = this.startNodeAt(startLoc);
  8727. nonNullExpression.expression = base;
  8728. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  8729. }
  8730. let isOptionalCall = false;
  8731. if (this.match(18) && this.lookaheadCharCode() === 60) {
  8732. if (noCalls) {
  8733. state.stop = true;
  8734. return base;
  8735. }
  8736. state.optionalChainMember = isOptionalCall = true;
  8737. this.next();
  8738. }
  8739. if (this.match(47) || this.match(51)) {
  8740. let missingParenErrorLoc;
  8741. const result = this.tsTryParseAndCatch(() => {
  8742. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  8743. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
  8744. if (asyncArrowFn) {
  8745. return asyncArrowFn;
  8746. }
  8747. }
  8748. const typeArguments = this.tsParseTypeArgumentsInExpression();
  8749. if (!typeArguments) return;
  8750. if (isOptionalCall && !this.match(10)) {
  8751. missingParenErrorLoc = this.state.curPosition();
  8752. return;
  8753. }
  8754. if (tokenIsTemplate(this.state.type)) {
  8755. const result = super.parseTaggedTemplateExpression(base, startLoc, state);
  8756. result.typeParameters = typeArguments;
  8757. return result;
  8758. }
  8759. if (!noCalls && this.eat(10)) {
  8760. const node = this.startNodeAt(startLoc);
  8761. node.callee = base;
  8762. node.arguments = this.parseCallExpressionArguments(11, false);
  8763. this.tsCheckForInvalidTypeCasts(node.arguments);
  8764. node.typeParameters = typeArguments;
  8765. if (state.optionalChainMember) {
  8766. node.optional = isOptionalCall;
  8767. }
  8768. return this.finishCallExpression(node, state.optionalChainMember);
  8769. }
  8770. const tokenType = this.state.type;
  8771. if (
  8772. tokenType === 48 ||
  8773. tokenType === 52 ||
  8774. tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
  8775. return;
  8776. }
  8777. const node = this.startNodeAt(startLoc);
  8778. node.expression = base;
  8779. node.typeParameters = typeArguments;
  8780. return this.finishNode(node, "TSInstantiationExpression");
  8781. });
  8782. if (missingParenErrorLoc) {
  8783. this.unexpected(missingParenErrorLoc, 10);
  8784. }
  8785. if (result) {
  8786. if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) {
  8787. this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, {
  8788. at: this.state.startLoc
  8789. });
  8790. }
  8791. return result;
  8792. }
  8793. }
  8794. return super.parseSubscript(base, startLoc, noCalls, state);
  8795. }
  8796. parseNewCallee(node) {
  8797. var _callee$extra;
  8798. super.parseNewCallee(node);
  8799. const {
  8800. callee
  8801. } = node;
  8802. if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
  8803. node.typeParameters = callee.typeParameters;
  8804. node.callee = callee.expression;
  8805. }
  8806. }
  8807. parseExprOp(left, leftStartLoc, minPrec) {
  8808. let isSatisfies;
  8809. if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(118)))) {
  8810. const node = this.startNodeAt(leftStartLoc);
  8811. node.expression = left;
  8812. node.typeAnnotation = this.tsInType(() => {
  8813. this.next();
  8814. if (this.match(75)) {
  8815. if (isSatisfies) {
  8816. this.raise(Errors.UnexpectedKeyword, {
  8817. at: this.state.startLoc,
  8818. keyword: "const"
  8819. });
  8820. }
  8821. return this.tsParseTypeReference();
  8822. }
  8823. return this.tsParseType();
  8824. });
  8825. this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
  8826. this.reScan_lt_gt();
  8827. return this.parseExprOp(
  8828. node, leftStartLoc, minPrec);
  8829. }
  8830. return super.parseExprOp(left, leftStartLoc, minPrec);
  8831. }
  8832. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  8833. if (!this.state.isAmbientContext) {
  8834. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  8835. }
  8836. }
  8837. checkImportReflection(node) {
  8838. super.checkImportReflection(node);
  8839. if (node.module && node.importKind !== "value") {
  8840. this.raise(TSErrors.ImportReflectionHasImportType, {
  8841. at: node.specifiers[0].loc.start
  8842. });
  8843. }
  8844. }
  8845. checkDuplicateExports() {}
  8846. parseImport(node) {
  8847. node.importKind = "value";
  8848. if (tokenIsIdentifier(this.state.type) || this.match(55) || this.match(5)) {
  8849. let ahead = this.lookahead();
  8850. if (this.isContextual(128) &&
  8851. ahead.type !== 12 &&
  8852. ahead.type !== 97 &&
  8853. ahead.type !== 29) {
  8854. node.importKind = "type";
  8855. this.next();
  8856. ahead = this.lookahead();
  8857. }
  8858. if (tokenIsIdentifier(this.state.type) && ahead.type === 29) {
  8859. return this.tsParseImportEqualsDeclaration(node);
  8860. }
  8861. }
  8862. const importNode = super.parseImport(node);
  8863. if (importNode.importKind === "type" &&
  8864. importNode.specifiers.length > 1 &&
  8865. importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  8866. this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, {
  8867. at: importNode
  8868. });
  8869. }
  8870. return importNode;
  8871. }
  8872. parseExport(node, decorators) {
  8873. if (this.match(83)) {
  8874. this.next();
  8875. if (this.isContextual(128) && this.lookaheadCharCode() !== 61) {
  8876. node.importKind = "type";
  8877. this.next();
  8878. } else {
  8879. node.importKind = "value";
  8880. }
  8881. return this.tsParseImportEqualsDeclaration(node, true);
  8882. } else if (this.eat(29)) {
  8883. const assign = node;
  8884. assign.expression = super.parseExpression();
  8885. this.semicolon();
  8886. return this.finishNode(assign, "TSExportAssignment");
  8887. } else if (this.eatContextual(93)) {
  8888. const decl = node;
  8889. this.expectContextual(126);
  8890. decl.id = this.parseIdentifier();
  8891. this.semicolon();
  8892. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  8893. } else {
  8894. if (this.isContextual(128) && this.lookahead().type === 5) {
  8895. this.next();
  8896. node.exportKind = "type";
  8897. } else {
  8898. node.exportKind = "value";
  8899. }
  8900. return super.parseExport(node, decorators);
  8901. }
  8902. }
  8903. isAbstractClass() {
  8904. return this.isContextual(122) && this.lookahead().type === 80;
  8905. }
  8906. parseExportDefaultExpression() {
  8907. if (this.isAbstractClass()) {
  8908. const cls = this.startNode();
  8909. this.next();
  8910. cls.abstract = true;
  8911. return this.parseClass(cls, true, true);
  8912. }
  8913. if (this.match(127)) {
  8914. const result = this.tsParseInterfaceDeclaration(this.startNode());
  8915. if (result) return result;
  8916. }
  8917. return super.parseExportDefaultExpression();
  8918. }
  8919. parseVarStatement(node, kind, allowMissingInitializer = false) {
  8920. const {
  8921. isAmbientContext
  8922. } = this.state;
  8923. const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext);
  8924. if (!isAmbientContext) return declaration;
  8925. for (const {
  8926. id,
  8927. init
  8928. } of declaration.declarations) {
  8929. if (!init) continue;
  8930. if (kind !== "const" || !!id.typeAnnotation) {
  8931. this.raise(TSErrors.InitializerNotAllowedInAmbientContext, {
  8932. at: init
  8933. });
  8934. } else if (init.type !== "StringLiteral" && init.type !== "BooleanLiteral" && init.type !== "NumericLiteral" && init.type !== "BigIntLiteral" && (init.type !== "TemplateLiteral" || init.expressions.length > 0) && !isPossiblyLiteralEnum(init)) {
  8935. this.raise(TSErrors.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference, {
  8936. at: init
  8937. });
  8938. }
  8939. }
  8940. return declaration;
  8941. }
  8942. parseStatementContent(flags, decorators) {
  8943. if (this.match(75) && this.isLookaheadContextual("enum")) {
  8944. const node = this.startNode();
  8945. this.expect(75);
  8946. return this.tsParseEnumDeclaration(node, {
  8947. const: true
  8948. });
  8949. }
  8950. if (this.isContextual(124)) {
  8951. return this.tsParseEnumDeclaration(this.startNode());
  8952. }
  8953. if (this.isContextual(127)) {
  8954. const result = this.tsParseInterfaceDeclaration(this.startNode());
  8955. if (result) return result;
  8956. }
  8957. return super.parseStatementContent(flags, decorators);
  8958. }
  8959. parseAccessModifier() {
  8960. return this.tsParseModifier(["public", "protected", "private"]);
  8961. }
  8962. tsHasSomeModifiers(member, modifiers) {
  8963. return modifiers.some(modifier => {
  8964. if (tsIsAccessModifier(modifier)) {
  8965. return member.accessibility === modifier;
  8966. }
  8967. return !!member[modifier];
  8968. });
  8969. }
  8970. tsIsStartOfStaticBlocks() {
  8971. return this.isContextual(104) && this.lookaheadCharCode() === 123;
  8972. }
  8973. parseClassMember(classBody, member, state) {
  8974. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  8975. this.tsParseModifiers({
  8976. modified: member,
  8977. allowedModifiers: modifiers,
  8978. disallowedModifiers: ["in", "out"],
  8979. stopOnStartOfClassStaticBlock: true,
  8980. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  8981. });
  8982. const callParseClassMemberWithIsStatic = () => {
  8983. if (this.tsIsStartOfStaticBlocks()) {
  8984. this.next();
  8985. this.next();
  8986. if (this.tsHasSomeModifiers(member, modifiers)) {
  8987. this.raise(TSErrors.StaticBlockCannotHaveModifier, {
  8988. at: this.state.curPosition()
  8989. });
  8990. }
  8991. super.parseClassStaticBlock(classBody, member);
  8992. } else {
  8993. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  8994. }
  8995. };
  8996. if (member.declare) {
  8997. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  8998. } else {
  8999. callParseClassMemberWithIsStatic();
  9000. }
  9001. }
  9002. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  9003. const idx = this.tsTryParseIndexSignature(member);
  9004. if (idx) {
  9005. classBody.body.push(idx);
  9006. if (member.abstract) {
  9007. this.raise(TSErrors.IndexSignatureHasAbstract, {
  9008. at: member
  9009. });
  9010. }
  9011. if (member.accessibility) {
  9012. this.raise(TSErrors.IndexSignatureHasAccessibility, {
  9013. at: member,
  9014. modifier: member.accessibility
  9015. });
  9016. }
  9017. if (member.declare) {
  9018. this.raise(TSErrors.IndexSignatureHasDeclare, {
  9019. at: member
  9020. });
  9021. }
  9022. if (member.override) {
  9023. this.raise(TSErrors.IndexSignatureHasOverride, {
  9024. at: member
  9025. });
  9026. }
  9027. return;
  9028. }
  9029. if (!this.state.inAbstractClass && member.abstract) {
  9030. this.raise(TSErrors.NonAbstractClassHasAbstractMethod, {
  9031. at: member
  9032. });
  9033. }
  9034. if (member.override) {
  9035. if (!state.hadSuperClass) {
  9036. this.raise(TSErrors.OverrideNotInSubClass, {
  9037. at: member
  9038. });
  9039. }
  9040. }
  9041. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  9042. }
  9043. parsePostMemberNameModifiers(methodOrProp) {
  9044. const optional = this.eat(17);
  9045. if (optional) methodOrProp.optional = true;
  9046. if (methodOrProp.readonly && this.match(10)) {
  9047. this.raise(TSErrors.ClassMethodHasReadonly, {
  9048. at: methodOrProp
  9049. });
  9050. }
  9051. if (methodOrProp.declare && this.match(10)) {
  9052. this.raise(TSErrors.ClassMethodHasDeclare, {
  9053. at: methodOrProp
  9054. });
  9055. }
  9056. }
  9057. parseExpressionStatement(node, expr, decorators) {
  9058. const decl = expr.type === "Identifier" ?
  9059. this.tsParseExpressionStatement(node, expr, decorators) : undefined;
  9060. return decl || super.parseExpressionStatement(node, expr, decorators);
  9061. }
  9062. shouldParseExportDeclaration() {
  9063. if (this.tsIsDeclarationStart()) return true;
  9064. return super.shouldParseExportDeclaration();
  9065. }
  9066. parseConditional(expr, startLoc, refExpressionErrors) {
  9067. if (!this.state.maybeInArrowParameters || !this.match(17)) {
  9068. return super.parseConditional(expr, startLoc, refExpressionErrors);
  9069. }
  9070. const result = this.tryParse(() => super.parseConditional(expr, startLoc));
  9071. if (!result.node) {
  9072. if (result.error) {
  9073. super.setOptionalParametersError(refExpressionErrors, result.error);
  9074. }
  9075. return expr;
  9076. }
  9077. if (result.error) this.state = result.failState;
  9078. return result.node;
  9079. }
  9080. parseParenItem(node, startLoc) {
  9081. node = super.parseParenItem(node, startLoc);
  9082. if (this.eat(17)) {
  9083. node.optional = true;
  9084. this.resetEndLocation(node);
  9085. }
  9086. if (this.match(14)) {
  9087. const typeCastNode = this.startNodeAt(startLoc);
  9088. typeCastNode.expression = node;
  9089. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  9090. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  9091. }
  9092. return node;
  9093. }
  9094. parseExportDeclaration(node) {
  9095. if (!this.state.isAmbientContext && this.isContextual(123)) {
  9096. return this.tsInAmbientContext(() => this.parseExportDeclaration(node));
  9097. }
  9098. const startLoc = this.state.startLoc;
  9099. const isDeclare = this.eatContextual(123);
  9100. if (isDeclare && (this.isContextual(123) || !this.shouldParseExportDeclaration())) {
  9101. throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, {
  9102. at: this.state.startLoc
  9103. });
  9104. }
  9105. const isIdentifier = tokenIsIdentifier(this.state.type);
  9106. const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node);
  9107. if (!declaration) return null;
  9108. if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) {
  9109. node.exportKind = "type";
  9110. }
  9111. if (isDeclare) {
  9112. this.resetStartLocation(declaration, startLoc);
  9113. declaration.declare = true;
  9114. }
  9115. return declaration;
  9116. }
  9117. parseClassId(node, isStatement, optionalId,
  9118. bindingType) {
  9119. if ((!isStatement || optionalId) && this.isContextual(111)) {
  9120. return;
  9121. }
  9122. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  9123. const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers.bind(this));
  9124. if (typeParameters) node.typeParameters = typeParameters;
  9125. }
  9126. parseClassPropertyAnnotation(node) {
  9127. if (!node.optional) {
  9128. if (this.eat(35)) {
  9129. node.definite = true;
  9130. } else if (this.eat(17)) {
  9131. node.optional = true;
  9132. }
  9133. }
  9134. const type = this.tsTryParseTypeAnnotation();
  9135. if (type) node.typeAnnotation = type;
  9136. }
  9137. parseClassProperty(node) {
  9138. this.parseClassPropertyAnnotation(node);
  9139. if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) {
  9140. this.raise(TSErrors.DeclareClassFieldHasInitializer, {
  9141. at: this.state.startLoc
  9142. });
  9143. }
  9144. if (node.abstract && this.match(29)) {
  9145. const {
  9146. key
  9147. } = node;
  9148. this.raise(TSErrors.AbstractPropertyHasInitializer, {
  9149. at: this.state.startLoc,
  9150. propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`
  9151. });
  9152. }
  9153. return super.parseClassProperty(node);
  9154. }
  9155. parseClassPrivateProperty(node) {
  9156. if (node.abstract) {
  9157. this.raise(TSErrors.PrivateElementHasAbstract, {
  9158. at: node
  9159. });
  9160. }
  9161. if (node.accessibility) {
  9162. this.raise(TSErrors.PrivateElementHasAccessibility, {
  9163. at: node,
  9164. modifier: node.accessibility
  9165. });
  9166. }
  9167. this.parseClassPropertyAnnotation(node);
  9168. return super.parseClassPrivateProperty(node);
  9169. }
  9170. parseClassAccessorProperty(node) {
  9171. this.parseClassPropertyAnnotation(node);
  9172. if (node.optional) {
  9173. this.raise(TSErrors.AccessorCannotBeOptional, {
  9174. at: node
  9175. });
  9176. }
  9177. return super.parseClassAccessorProperty(node);
  9178. }
  9179. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9180. const typeParameters = this.tsTryParseTypeParameters();
  9181. if (typeParameters && isConstructor) {
  9182. this.raise(TSErrors.ConstructorHasTypeParameters, {
  9183. at: typeParameters
  9184. });
  9185. }
  9186. const {
  9187. declare = false,
  9188. kind
  9189. } = method;
  9190. if (declare && (kind === "get" || kind === "set")) {
  9191. this.raise(TSErrors.DeclareAccessor, {
  9192. at: method,
  9193. kind
  9194. });
  9195. }
  9196. if (typeParameters) method.typeParameters = typeParameters;
  9197. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  9198. }
  9199. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9200. const typeParameters = this.tsTryParseTypeParameters();
  9201. if (typeParameters) method.typeParameters = typeParameters;
  9202. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  9203. }
  9204. declareClassPrivateMethodInScope(node, kind) {
  9205. if (node.type === "TSDeclareMethod") return;
  9206. if (node.type === "MethodDefinition" && !node.value.body) return;
  9207. super.declareClassPrivateMethodInScope(node, kind);
  9208. }
  9209. parseClassSuper(node) {
  9210. super.parseClassSuper(node);
  9211. if (node.superClass && (this.match(47) || this.match(51))) {
  9212. node.superTypeParameters = this.tsParseTypeArgumentsInExpression();
  9213. }
  9214. if (this.eatContextual(111)) {
  9215. node.implements = this.tsParseHeritageClause("implements");
  9216. }
  9217. }
  9218. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9219. const typeParameters = this.tsTryParseTypeParameters();
  9220. if (typeParameters) prop.typeParameters = typeParameters;
  9221. return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  9222. }
  9223. parseFunctionParams(node, allowModifiers) {
  9224. const typeParameters = this.tsTryParseTypeParameters();
  9225. if (typeParameters) node.typeParameters = typeParameters;
  9226. super.parseFunctionParams(node, allowModifiers);
  9227. }
  9228. parseVarId(decl, kind) {
  9229. super.parseVarId(decl, kind);
  9230. if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
  9231. decl.definite = true;
  9232. }
  9233. const type = this.tsTryParseTypeAnnotation();
  9234. if (type) {
  9235. decl.id.typeAnnotation = type;
  9236. this.resetEndLocation(decl.id);
  9237. }
  9238. }
  9239. parseAsyncArrowFromCallExpression(node, call) {
  9240. if (this.match(14)) {
  9241. node.returnType = this.tsParseTypeAnnotation();
  9242. }
  9243. return super.parseAsyncArrowFromCallExpression(node, call);
  9244. }
  9245. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  9246. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  9247. let state;
  9248. let jsx;
  9249. let typeCast;
  9250. if (this.hasPlugin("jsx") && (this.match(140) || this.match(47))) {
  9251. state = this.state.clone();
  9252. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9253. if (!jsx.error) return jsx.node;
  9254. const {
  9255. context
  9256. } = this.state;
  9257. const currentContext = context[context.length - 1];
  9258. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  9259. context.pop();
  9260. }
  9261. }
  9262. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) {
  9263. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9264. }
  9265. if (!state || state === this.state) state = this.state.clone();
  9266. let typeParameters;
  9267. const arrow = this.tryParse(abort => {
  9268. var _expr$extra, _typeParameters;
  9269. typeParameters = this.tsParseTypeParameters();
  9270. const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9271. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  9272. abort();
  9273. }
  9274. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  9275. this.resetStartLocationFromNode(expr, typeParameters);
  9276. }
  9277. expr.typeParameters = typeParameters;
  9278. return expr;
  9279. }, state);
  9280. if (!arrow.error && !arrow.aborted) {
  9281. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9282. return arrow.node;
  9283. }
  9284. if (!jsx) {
  9285. assert(!this.hasPlugin("jsx"));
  9286. typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9287. if (!typeCast.error) return typeCast.node;
  9288. }
  9289. if ((_jsx2 = jsx) != null && _jsx2.node) {
  9290. this.state = jsx.failState;
  9291. return jsx.node;
  9292. }
  9293. if (arrow.node) {
  9294. this.state = arrow.failState;
  9295. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9296. return arrow.node;
  9297. }
  9298. if ((_typeCast = typeCast) != null && _typeCast.node) {
  9299. this.state = typeCast.failState;
  9300. return typeCast.node;
  9301. }
  9302. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  9303. if (arrow.thrown) throw arrow.error;
  9304. if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error;
  9305. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  9306. }
  9307. reportReservedArrowTypeParam(node) {
  9308. var _node$extra;
  9309. if (node.params.length === 1 && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  9310. this.raise(TSErrors.ReservedArrowTypeParam, {
  9311. at: node
  9312. });
  9313. }
  9314. }
  9315. parseMaybeUnary(refExpressionErrors, sawUnary) {
  9316. if (!this.hasPlugin("jsx") && this.match(47)) {
  9317. return this.tsParseTypeAssertion();
  9318. } else {
  9319. return super.parseMaybeUnary(refExpressionErrors, sawUnary);
  9320. }
  9321. }
  9322. parseArrow(node) {
  9323. if (this.match(14)) {
  9324. const result = this.tryParse(abort => {
  9325. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9326. if (this.canInsertSemicolon() || !this.match(19)) abort();
  9327. return returnType;
  9328. });
  9329. if (result.aborted) return;
  9330. if (!result.thrown) {
  9331. if (result.error) this.state = result.failState;
  9332. node.returnType = result.node;
  9333. }
  9334. }
  9335. return super.parseArrow(node);
  9336. }
  9337. parseAssignableListItemTypes(param) {
  9338. if (this.eat(17)) {
  9339. if (param.type !== "Identifier" && !this.state.isAmbientContext && !this.state.inType) {
  9340. this.raise(TSErrors.PatternIsOptional, {
  9341. at: param
  9342. });
  9343. }
  9344. param.optional = true;
  9345. }
  9346. const type = this.tsTryParseTypeAnnotation();
  9347. if (type) param.typeAnnotation = type;
  9348. this.resetEndLocation(param);
  9349. return param;
  9350. }
  9351. isAssignable(node, isBinding) {
  9352. switch (node.type) {
  9353. case "TSTypeCastExpression":
  9354. return this.isAssignable(node.expression, isBinding);
  9355. case "TSParameterProperty":
  9356. return true;
  9357. default:
  9358. return super.isAssignable(node, isBinding);
  9359. }
  9360. }
  9361. toAssignable(node, isLHS = false) {
  9362. switch (node.type) {
  9363. case "ParenthesizedExpression":
  9364. this.toAssignableParenthesizedExpression(node, isLHS);
  9365. break;
  9366. case "TSAsExpression":
  9367. case "TSSatisfiesExpression":
  9368. case "TSNonNullExpression":
  9369. case "TSTypeAssertion":
  9370. if (isLHS) {
  9371. this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, {
  9372. at: node
  9373. });
  9374. } else {
  9375. this.raise(TSErrors.UnexpectedTypeCastInParameter, {
  9376. at: node
  9377. });
  9378. }
  9379. this.toAssignable(node.expression, isLHS);
  9380. break;
  9381. case "AssignmentExpression":
  9382. if (!isLHS && node.left.type === "TSTypeCastExpression") {
  9383. node.left = this.typeCastToParameter(node.left);
  9384. }
  9385. default:
  9386. super.toAssignable(node, isLHS);
  9387. }
  9388. }
  9389. toAssignableParenthesizedExpression(node, isLHS) {
  9390. switch (node.expression.type) {
  9391. case "TSAsExpression":
  9392. case "TSSatisfiesExpression":
  9393. case "TSNonNullExpression":
  9394. case "TSTypeAssertion":
  9395. case "ParenthesizedExpression":
  9396. this.toAssignable(node.expression, isLHS);
  9397. break;
  9398. default:
  9399. super.toAssignable(node, isLHS);
  9400. }
  9401. }
  9402. checkToRestConversion(node, allowPattern) {
  9403. switch (node.type) {
  9404. case "TSAsExpression":
  9405. case "TSSatisfiesExpression":
  9406. case "TSTypeAssertion":
  9407. case "TSNonNullExpression":
  9408. this.checkToRestConversion(node.expression, false);
  9409. break;
  9410. default:
  9411. super.checkToRestConversion(node, allowPattern);
  9412. }
  9413. }
  9414. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  9415. return getOwn$1({
  9416. TSTypeCastExpression: true,
  9417. TSParameterProperty: "parameter",
  9418. TSNonNullExpression: "expression",
  9419. TSAsExpression: (binding !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
  9420. TSSatisfiesExpression: (binding !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
  9421. TSTypeAssertion: (binding !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true]
  9422. }, type) || super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  9423. }
  9424. parseBindingAtom() {
  9425. switch (this.state.type) {
  9426. case 78:
  9427. return this.parseIdentifier(true);
  9428. default:
  9429. return super.parseBindingAtom();
  9430. }
  9431. }
  9432. parseMaybeDecoratorArguments(expr) {
  9433. if (this.match(47) || this.match(51)) {
  9434. const typeArguments = this.tsParseTypeArgumentsInExpression();
  9435. if (this.match(10)) {
  9436. const call = super.parseMaybeDecoratorArguments(expr);
  9437. call.typeParameters = typeArguments;
  9438. return call;
  9439. }
  9440. this.unexpected(null, 10);
  9441. }
  9442. return super.parseMaybeDecoratorArguments(expr);
  9443. }
  9444. checkCommaAfterRest(close) {
  9445. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9446. this.next();
  9447. return false;
  9448. } else {
  9449. return super.checkCommaAfterRest(close);
  9450. }
  9451. }
  9452. isClassMethod() {
  9453. return this.match(47) || super.isClassMethod();
  9454. }
  9455. isClassProperty() {
  9456. return this.match(35) || this.match(14) || super.isClassProperty();
  9457. }
  9458. parseMaybeDefault(startLoc, left) {
  9459. const node = super.parseMaybeDefault(startLoc, left);
  9460. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9461. this.raise(TSErrors.TypeAnnotationAfterAssign, {
  9462. at: node.typeAnnotation
  9463. });
  9464. }
  9465. return node;
  9466. }
  9467. getTokenFromCode(code) {
  9468. if (this.state.inType) {
  9469. if (code === 62) {
  9470. return this.finishOp(48, 1);
  9471. }
  9472. if (code === 60) {
  9473. return this.finishOp(47, 1);
  9474. }
  9475. }
  9476. return super.getTokenFromCode(code);
  9477. }
  9478. reScan_lt_gt() {
  9479. const {
  9480. type
  9481. } = this.state;
  9482. if (type === 47) {
  9483. this.state.pos -= 1;
  9484. this.readToken_lt();
  9485. } else if (type === 48) {
  9486. this.state.pos -= 1;
  9487. this.readToken_gt();
  9488. }
  9489. }
  9490. reScan_lt() {
  9491. const {
  9492. type
  9493. } = this.state;
  9494. if (type === 51) {
  9495. this.state.pos -= 2;
  9496. this.finishOp(47, 1);
  9497. return 47;
  9498. }
  9499. return type;
  9500. }
  9501. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  9502. for (let i = 0; i < exprList.length; i++) {
  9503. const expr = exprList[i];
  9504. if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") {
  9505. exprList[i] = this.typeCastToParameter(expr);
  9506. }
  9507. }
  9508. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  9509. }
  9510. typeCastToParameter(node) {
  9511. node.expression.typeAnnotation = node.typeAnnotation;
  9512. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  9513. return node.expression;
  9514. }
  9515. shouldParseArrow(params) {
  9516. if (this.match(14)) {
  9517. return params.every(expr => this.isAssignable(expr, true));
  9518. }
  9519. return super.shouldParseArrow(params);
  9520. }
  9521. shouldParseAsyncArrow() {
  9522. return this.match(14) || super.shouldParseAsyncArrow();
  9523. }
  9524. canHaveLeadingDecorator() {
  9525. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9526. }
  9527. jsxParseOpeningElementAfterName(node) {
  9528. if (this.match(47) || this.match(51)) {
  9529. const typeArguments = this.tsTryParseAndCatch(() =>
  9530. this.tsParseTypeArgumentsInExpression());
  9531. if (typeArguments) node.typeParameters = typeArguments;
  9532. }
  9533. return super.jsxParseOpeningElementAfterName(node);
  9534. }
  9535. getGetterSetterExpectedParamCount(method) {
  9536. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9537. const params = this.getObjectOrClassMethodParams(method);
  9538. const firstParam = params[0];
  9539. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9540. return hasContextParam ? baseCount + 1 : baseCount;
  9541. }
  9542. parseCatchClauseParam() {
  9543. const param = super.parseCatchClauseParam();
  9544. const type = this.tsTryParseTypeAnnotation();
  9545. if (type) {
  9546. param.typeAnnotation = type;
  9547. this.resetEndLocation(param);
  9548. }
  9549. return param;
  9550. }
  9551. tsInAmbientContext(cb) {
  9552. const oldIsAmbientContext = this.state.isAmbientContext;
  9553. this.state.isAmbientContext = true;
  9554. try {
  9555. return cb();
  9556. } finally {
  9557. this.state.isAmbientContext = oldIsAmbientContext;
  9558. }
  9559. }
  9560. parseClass(node, isStatement, optionalId) {
  9561. const oldInAbstractClass = this.state.inAbstractClass;
  9562. this.state.inAbstractClass = !!node.abstract;
  9563. try {
  9564. return super.parseClass(node, isStatement, optionalId);
  9565. } finally {
  9566. this.state.inAbstractClass = oldInAbstractClass;
  9567. }
  9568. }
  9569. tsParseAbstractDeclaration(node, decorators) {
  9570. if (this.match(80)) {
  9571. node.abstract = true;
  9572. return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false));
  9573. } else if (this.isContextual(127)) {
  9574. if (!this.hasFollowingLineBreak()) {
  9575. node.abstract = true;
  9576. this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, {
  9577. at: node
  9578. });
  9579. return this.tsParseInterfaceDeclaration(node);
  9580. }
  9581. } else {
  9582. this.unexpected(null, 80);
  9583. }
  9584. }
  9585. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
  9586. const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  9587. if (method.abstract) {
  9588. const hasBody = this.hasPlugin("estree") ?
  9589. !!method.value.body : !!method.body;
  9590. if (hasBody) {
  9591. const {
  9592. key
  9593. } = method;
  9594. this.raise(TSErrors.AbstractMethodHasImplementation, {
  9595. at: method,
  9596. methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`
  9597. });
  9598. }
  9599. }
  9600. return method;
  9601. }
  9602. tsParseTypeParameterName() {
  9603. const typeName = this.parseIdentifier();
  9604. return typeName.name;
  9605. }
  9606. shouldParseAsAmbientContext() {
  9607. return !!this.getPluginOption("typescript", "dts");
  9608. }
  9609. parse() {
  9610. if (this.shouldParseAsAmbientContext()) {
  9611. this.state.isAmbientContext = true;
  9612. }
  9613. return super.parse();
  9614. }
  9615. getExpression() {
  9616. if (this.shouldParseAsAmbientContext()) {
  9617. this.state.isAmbientContext = true;
  9618. }
  9619. return super.getExpression();
  9620. }
  9621. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9622. if (!isString && isMaybeTypeOnly) {
  9623. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9624. return this.finishNode(node, "ExportSpecifier");
  9625. }
  9626. node.exportKind = "value";
  9627. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9628. }
  9629. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly,
  9630. bindingType) {
  9631. if (!importedIsString && isMaybeTypeOnly) {
  9632. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  9633. return this.finishNode(specifier, "ImportSpecifier");
  9634. }
  9635. specifier.importKind = "value";
  9636. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? BIND_TS_TYPE_IMPORT : BIND_FLAGS_TS_IMPORT);
  9637. }
  9638. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  9639. const leftOfAsKey = isImport ? "imported" : "local";
  9640. const rightOfAsKey = isImport ? "local" : "exported";
  9641. let leftOfAs = node[leftOfAsKey];
  9642. let rightOfAs;
  9643. let hasTypeSpecifier = false;
  9644. let canParseAsKeyword = true;
  9645. const loc = leftOfAs.loc.start;
  9646. if (this.isContextual(93)) {
  9647. const firstAs = this.parseIdentifier();
  9648. if (this.isContextual(93)) {
  9649. const secondAs = this.parseIdentifier();
  9650. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9651. hasTypeSpecifier = true;
  9652. leftOfAs = firstAs;
  9653. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9654. canParseAsKeyword = false;
  9655. } else {
  9656. rightOfAs = secondAs;
  9657. canParseAsKeyword = false;
  9658. }
  9659. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9660. canParseAsKeyword = false;
  9661. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9662. } else {
  9663. hasTypeSpecifier = true;
  9664. leftOfAs = firstAs;
  9665. }
  9666. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9667. hasTypeSpecifier = true;
  9668. if (isImport) {
  9669. leftOfAs = this.parseIdentifier(true);
  9670. if (!this.isContextual(93)) {
  9671. this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
  9672. }
  9673. } else {
  9674. leftOfAs = this.parseModuleExportName();
  9675. }
  9676. }
  9677. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  9678. this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, {
  9679. at: loc
  9680. });
  9681. }
  9682. node[leftOfAsKey] = leftOfAs;
  9683. node[rightOfAsKey] = rightOfAs;
  9684. const kindKey = isImport ? "importKind" : "exportKind";
  9685. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  9686. if (canParseAsKeyword && this.eatContextual(93)) {
  9687. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9688. }
  9689. if (!node[rightOfAsKey]) {
  9690. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  9691. }
  9692. if (isImport) {
  9693. this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? BIND_TS_TYPE_IMPORT : BIND_FLAGS_TS_IMPORT);
  9694. }
  9695. }
  9696. });
  9697. function isPossiblyLiteralEnum(expression) {
  9698. if (expression.type !== "MemberExpression") return false;
  9699. const {
  9700. computed,
  9701. property
  9702. } = expression;
  9703. if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
  9704. return false;
  9705. }
  9706. return isUncomputedMemberExpressionChain(expression.object);
  9707. }
  9708. function isUncomputedMemberExpressionChain(expression) {
  9709. if (expression.type === "Identifier") return true;
  9710. if (expression.type !== "MemberExpression") return false;
  9711. if (expression.computed) return false;
  9712. return isUncomputedMemberExpressionChain(expression.object);
  9713. }
  9714. const PlaceholderErrors = ParseErrorEnum`placeholders`({
  9715. ClassNameIsRequired: "A class name is required.",
  9716. UnexpectedSpace: "Unexpected space in placeholder."
  9717. });
  9718. var placeholders = (superClass => class PlaceholdersParserMixin extends superClass {
  9719. parsePlaceholder(expectedNode) {
  9720. if (this.match(142)) {
  9721. const node = this.startNode();
  9722. this.next();
  9723. this.assertNoSpace();
  9724. node.name = super.parseIdentifier(true);
  9725. this.assertNoSpace();
  9726. this.expect(142);
  9727. return this.finishPlaceholder(node, expectedNode);
  9728. }
  9729. }
  9730. finishPlaceholder(node, expectedNode) {
  9731. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  9732. node.expectedNode = expectedNode;
  9733. return isFinished ? node : this.finishNode(node, "Placeholder");
  9734. }
  9735. getTokenFromCode(code) {
  9736. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  9737. return this.finishOp(142, 2);
  9738. }
  9739. return super.getTokenFromCode(code);
  9740. }
  9741. parseExprAtom(refExpressionErrors) {
  9742. return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  9743. }
  9744. parseIdentifier(liberal) {
  9745. return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  9746. }
  9747. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9748. if (word !== undefined) {
  9749. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  9750. }
  9751. }
  9752. parseBindingAtom() {
  9753. return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  9754. }
  9755. isValidLVal(type, isParenthesized, binding) {
  9756. return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding);
  9757. }
  9758. toAssignable(node, isLHS) {
  9759. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  9760. node.expectedNode = "Pattern";
  9761. } else {
  9762. super.toAssignable(node, isLHS);
  9763. }
  9764. }
  9765. chStartsBindingIdentifier(ch, pos) {
  9766. if (super.chStartsBindingIdentifier(ch, pos)) {
  9767. return true;
  9768. }
  9769. const nextToken = this.lookahead();
  9770. if (nextToken.type === 142) {
  9771. return true;
  9772. }
  9773. return false;
  9774. }
  9775. verifyBreakContinue(node, isBreak) {
  9776. if (node.label && node.label.type === "Placeholder") return;
  9777. super.verifyBreakContinue(node, isBreak);
  9778. }
  9779. parseExpressionStatement(node, expr) {
  9780. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  9781. return super.parseExpressionStatement(node, expr);
  9782. }
  9783. if (this.match(14)) {
  9784. const stmt = node;
  9785. stmt.label = this.finishPlaceholder(expr, "Identifier");
  9786. this.next();
  9787. stmt.body = super.parseStatementOrFunctionDeclaration(false);
  9788. return this.finishNode(stmt, "LabeledStatement");
  9789. }
  9790. this.semicolon();
  9791. node.name = expr.name;
  9792. return this.finishPlaceholder(node, "Statement");
  9793. }
  9794. parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
  9795. return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  9796. }
  9797. parseFunctionId(requireId) {
  9798. return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  9799. }
  9800. parseClass(node, isStatement, optionalId) {
  9801. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  9802. this.next();
  9803. const oldStrict = this.state.strict;
  9804. const placeholder = this.parsePlaceholder("Identifier");
  9805. if (placeholder) {
  9806. if (this.match(81) || this.match(142) || this.match(5)) {
  9807. node.id = placeholder;
  9808. } else if (optionalId || !isStatement) {
  9809. node.id = null;
  9810. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  9811. return this.finishNode(node, type);
  9812. } else {
  9813. throw this.raise(PlaceholderErrors.ClassNameIsRequired, {
  9814. at: this.state.startLoc
  9815. });
  9816. }
  9817. } else {
  9818. this.parseClassId(node, isStatement, optionalId);
  9819. }
  9820. super.parseClassSuper(node);
  9821. node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict);
  9822. return this.finishNode(node, type);
  9823. }
  9824. parseExport(node, decorators) {
  9825. const placeholder = this.parsePlaceholder("Identifier");
  9826. if (!placeholder) return super.parseExport(node, decorators);
  9827. if (!this.isContextual(97) && !this.match(12)) {
  9828. node.specifiers = [];
  9829. node.source = null;
  9830. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  9831. return this.finishNode(node, "ExportNamedDeclaration");
  9832. }
  9833. this.expectPlugin("exportDefaultFrom");
  9834. const specifier = this.startNode();
  9835. specifier.exported = placeholder;
  9836. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9837. return super.parseExport(node, decorators);
  9838. }
  9839. isExportDefaultSpecifier() {
  9840. if (this.match(65)) {
  9841. const next = this.nextTokenStart();
  9842. if (this.isUnparsedContextual(next, "from")) {
  9843. if (this.input.startsWith(tokenLabelName(142), this.nextTokenStartSince(next + 4))) {
  9844. return true;
  9845. }
  9846. }
  9847. }
  9848. return super.isExportDefaultSpecifier();
  9849. }
  9850. maybeParseExportDefaultSpecifier(node) {
  9851. if (node.specifiers && node.specifiers.length > 0) {
  9852. return true;
  9853. }
  9854. return super.maybeParseExportDefaultSpecifier(node);
  9855. }
  9856. checkExport(node) {
  9857. const {
  9858. specifiers
  9859. } = node;
  9860. if (specifiers != null && specifiers.length) {
  9861. node.specifiers = specifiers.filter(
  9862. node => node.exported.type === "Placeholder");
  9863. }
  9864. super.checkExport(node);
  9865. node.specifiers = specifiers;
  9866. }
  9867. parseImport(node) {
  9868. const placeholder = this.parsePlaceholder("Identifier");
  9869. if (!placeholder) return super.parseImport(node);
  9870. node.specifiers = [];
  9871. if (!this.isContextual(97) && !this.match(12)) {
  9872. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  9873. this.semicolon();
  9874. return this.finishNode(node, "ImportDeclaration");
  9875. }
  9876. const specifier = this.startNodeAtNode(placeholder);
  9877. specifier.local = placeholder;
  9878. node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
  9879. if (this.eat(12)) {
  9880. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  9881. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  9882. }
  9883. this.expectContextual(97);
  9884. node.source = this.parseImportSource();
  9885. this.semicolon();
  9886. return this.finishNode(node, "ImportDeclaration");
  9887. }
  9888. parseImportSource() {
  9889. return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  9890. }
  9891. assertNoSpace() {
  9892. if (this.state.start > this.state.lastTokEndLoc.index) {
  9893. this.raise(PlaceholderErrors.UnexpectedSpace, {
  9894. at: this.state.lastTokEndLoc
  9895. });
  9896. }
  9897. }
  9898. });
  9899. var v8intrinsic = (superClass => class V8IntrinsicMixin extends superClass {
  9900. parseV8Intrinsic() {
  9901. if (this.match(54)) {
  9902. const v8IntrinsicStartLoc = this.state.startLoc;
  9903. const node = this.startNode();
  9904. this.next();
  9905. if (tokenIsIdentifier(this.state.type)) {
  9906. const name = this.parseIdentifierName();
  9907. const identifier = this.createIdentifier(node, name);
  9908. identifier.type = "V8IntrinsicIdentifier";
  9909. if (this.match(10)) {
  9910. return identifier;
  9911. }
  9912. }
  9913. this.unexpected(v8IntrinsicStartLoc);
  9914. }
  9915. }
  9916. parseExprAtom(refExpressionErrors) {
  9917. return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  9918. }
  9919. });
  9920. function hasPlugin(plugins, expectedConfig) {
  9921. const [expectedName, expectedOptions] = typeof expectedConfig === "string" ? [expectedConfig, {}] : expectedConfig;
  9922. const expectedKeys = Object.keys(expectedOptions);
  9923. const expectedOptionsIsEmpty = expectedKeys.length === 0;
  9924. return plugins.some(p => {
  9925. if (typeof p === "string") {
  9926. return expectedOptionsIsEmpty && p === expectedName;
  9927. } else {
  9928. const [pluginName, pluginOptions] = p;
  9929. if (pluginName !== expectedName) {
  9930. return false;
  9931. }
  9932. for (const key of expectedKeys) {
  9933. if (pluginOptions[key] !== expectedOptions[key]) {
  9934. return false;
  9935. }
  9936. }
  9937. return true;
  9938. }
  9939. });
  9940. }
  9941. function getPluginOption(plugins, name, option) {
  9942. const plugin = plugins.find(plugin => {
  9943. if (Array.isArray(plugin)) {
  9944. return plugin[0] === name;
  9945. } else {
  9946. return plugin === name;
  9947. }
  9948. });
  9949. if (plugin && Array.isArray(plugin) && plugin.length > 1) {
  9950. return plugin[1][option];
  9951. }
  9952. return null;
  9953. }
  9954. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  9955. const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
  9956. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  9957. function validatePlugins(plugins) {
  9958. if (hasPlugin(plugins, "decorators")) {
  9959. if (hasPlugin(plugins, "decorators-legacy")) {
  9960. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  9961. }
  9962. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  9963. if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
  9964. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  9965. }
  9966. const allowCallParenthesized = getPluginOption(plugins, "decorators", "allowCallParenthesized");
  9967. if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
  9968. throw new Error("'allowCallParenthesized' must be a boolean.");
  9969. }
  9970. }
  9971. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  9972. throw new Error("Cannot combine flow and typescript plugins.");
  9973. }
  9974. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  9975. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  9976. }
  9977. if (hasPlugin(plugins, "pipelineOperator")) {
  9978. const proposal = getPluginOption(plugins, "pipelineOperator", "proposal");
  9979. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  9980. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  9981. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  9982. }
  9983. const tupleSyntaxIsHash = hasPlugin(plugins, ["recordAndTuple", {
  9984. syntaxType: "hash"
  9985. }]);
  9986. if (proposal === "hack") {
  9987. if (hasPlugin(plugins, "placeholders")) {
  9988. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  9989. }
  9990. if (hasPlugin(plugins, "v8intrinsic")) {
  9991. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  9992. }
  9993. const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken");
  9994. if (!TOPIC_TOKENS.includes(topicToken)) {
  9995. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  9996. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  9997. }
  9998. if (topicToken === "#" && tupleSyntaxIsHash) {
  9999. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  10000. }
  10001. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  10002. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  10003. }
  10004. }
  10005. if (hasPlugin(plugins, "moduleAttributes")) {
  10006. {
  10007. if (hasPlugin(plugins, "importAssertions")) {
  10008. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  10009. }
  10010. const moduleAttributesVersionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  10011. if (moduleAttributesVersionPluginOption !== "may-2020") {
  10012. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  10013. }
  10014. }
  10015. }
  10016. if (hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") != null && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  10017. throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  10018. }
  10019. if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) {
  10020. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  10021. error.missingPlugins = "doExpressions";
  10022. throw error;
  10023. }
  10024. }
  10025. const mixinPlugins = {
  10026. estree,
  10027. jsx,
  10028. flow,
  10029. typescript,
  10030. v8intrinsic,
  10031. placeholders
  10032. };
  10033. const mixinPluginNames = Object.keys(mixinPlugins);
  10034. const defaultOptions = {
  10035. sourceType: "script",
  10036. sourceFilename: undefined,
  10037. startColumn: 0,
  10038. startLine: 1,
  10039. allowAwaitOutsideFunction: false,
  10040. allowReturnOutsideFunction: false,
  10041. allowImportExportEverywhere: false,
  10042. allowSuperOutsideMethod: false,
  10043. allowUndeclaredExports: false,
  10044. plugins: [],
  10045. strictMode: null,
  10046. ranges: false,
  10047. tokens: false,
  10048. createParenthesizedExpressions: false,
  10049. errorRecovery: false,
  10050. attachComment: true
  10051. };
  10052. function getOptions(opts) {
  10053. const options = {};
  10054. for (const key of Object.keys(defaultOptions)) {
  10055. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  10056. }
  10057. return options;
  10058. }
  10059. const getOwn = (object, key) => Object.hasOwnProperty.call(object, key) && object[key];
  10060. const unwrapParenthesizedExpression = node => {
  10061. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  10062. };
  10063. class LValParser extends NodeUtils {
  10064. toAssignable(node, isLHS = false) {
  10065. var _node$extra, _node$extra3;
  10066. let parenthesized = undefined;
  10067. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  10068. parenthesized = unwrapParenthesizedExpression(node);
  10069. if (isLHS) {
  10070. if (parenthesized.type === "Identifier") {
  10071. this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, {
  10072. at: node
  10073. });
  10074. } else if (parenthesized.type !== "MemberExpression") {
  10075. this.raise(Errors.InvalidParenthesizedAssignment, {
  10076. at: node
  10077. });
  10078. }
  10079. } else {
  10080. this.raise(Errors.InvalidParenthesizedAssignment, {
  10081. at: node
  10082. });
  10083. }
  10084. }
  10085. switch (node.type) {
  10086. case "Identifier":
  10087. case "ObjectPattern":
  10088. case "ArrayPattern":
  10089. case "AssignmentPattern":
  10090. case "RestElement":
  10091. break;
  10092. case "ObjectExpression":
  10093. node.type = "ObjectPattern";
  10094. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  10095. var _node$extra2;
  10096. const prop = node.properties[i];
  10097. const isLast = i === last;
  10098. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  10099. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) {
  10100. this.raise(Errors.RestTrailingComma, {
  10101. at: node.extra.trailingCommaLoc
  10102. });
  10103. }
  10104. }
  10105. break;
  10106. case "ObjectProperty":
  10107. {
  10108. const {
  10109. key,
  10110. value
  10111. } = node;
  10112. if (this.isPrivateName(key)) {
  10113. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  10114. }
  10115. this.toAssignable(value, isLHS);
  10116. break;
  10117. }
  10118. case "SpreadElement":
  10119. {
  10120. throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller.");
  10121. }
  10122. case "ArrayExpression":
  10123. node.type = "ArrayPattern";
  10124. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
  10125. break;
  10126. case "AssignmentExpression":
  10127. if (node.operator !== "=") {
  10128. this.raise(Errors.MissingEqInAssignment, {
  10129. at: node.left.loc.end
  10130. });
  10131. }
  10132. node.type = "AssignmentPattern";
  10133. delete node.operator;
  10134. this.toAssignable(node.left, isLHS);
  10135. break;
  10136. case "ParenthesizedExpression":
  10137. this.toAssignable(parenthesized, isLHS);
  10138. break;
  10139. }
  10140. }
  10141. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  10142. if (prop.type === "ObjectMethod") {
  10143. this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, {
  10144. at: prop.key
  10145. });
  10146. } else if (prop.type === "SpreadElement") {
  10147. prop.type = "RestElement";
  10148. const arg = prop.argument;
  10149. this.checkToRestConversion(arg, false);
  10150. this.toAssignable(arg, isLHS);
  10151. if (!isLast) {
  10152. this.raise(Errors.RestTrailingComma, {
  10153. at: prop
  10154. });
  10155. }
  10156. } else {
  10157. this.toAssignable(prop, isLHS);
  10158. }
  10159. }
  10160. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  10161. const end = exprList.length - 1;
  10162. for (let i = 0; i <= end; i++) {
  10163. const elt = exprList[i];
  10164. if (!elt) continue;
  10165. if (elt.type === "SpreadElement") {
  10166. elt.type = "RestElement";
  10167. const arg = elt.argument;
  10168. this.checkToRestConversion(arg, true);
  10169. this.toAssignable(arg, isLHS);
  10170. } else {
  10171. this.toAssignable(elt, isLHS);
  10172. }
  10173. if (elt.type === "RestElement") {
  10174. if (i < end) {
  10175. this.raise(Errors.RestTrailingComma, {
  10176. at: elt
  10177. });
  10178. } else if (trailingCommaLoc) {
  10179. this.raise(Errors.RestTrailingComma, {
  10180. at: trailingCommaLoc
  10181. });
  10182. }
  10183. }
  10184. }
  10185. }
  10186. isAssignable(node, isBinding) {
  10187. switch (node.type) {
  10188. case "Identifier":
  10189. case "ObjectPattern":
  10190. case "ArrayPattern":
  10191. case "AssignmentPattern":
  10192. case "RestElement":
  10193. return true;
  10194. case "ObjectExpression":
  10195. {
  10196. const last = node.properties.length - 1;
  10197. return node.properties.every((prop, i) => {
  10198. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  10199. });
  10200. }
  10201. case "ObjectProperty":
  10202. return this.isAssignable(node.value);
  10203. case "SpreadElement":
  10204. return this.isAssignable(node.argument);
  10205. case "ArrayExpression":
  10206. return node.elements.every(element => element === null || this.isAssignable(element));
  10207. case "AssignmentExpression":
  10208. return node.operator === "=";
  10209. case "ParenthesizedExpression":
  10210. return this.isAssignable(node.expression);
  10211. case "MemberExpression":
  10212. case "OptionalMemberExpression":
  10213. return !isBinding;
  10214. default:
  10215. return false;
  10216. }
  10217. }
  10218. toReferencedList(exprList,
  10219. isParenthesizedExpr) {
  10220. return exprList;
  10221. }
  10222. toReferencedListDeep(exprList, isParenthesizedExpr) {
  10223. this.toReferencedList(exprList, isParenthesizedExpr);
  10224. for (const expr of exprList) {
  10225. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  10226. this.toReferencedListDeep(expr.elements);
  10227. }
  10228. }
  10229. }
  10230. parseSpread(refExpressionErrors) {
  10231. const node = this.startNode();
  10232. this.next();
  10233. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined);
  10234. return this.finishNode(node, "SpreadElement");
  10235. }
  10236. parseRestBinding() {
  10237. const node = this.startNode();
  10238. this.next();
  10239. node.argument = this.parseBindingAtom();
  10240. return this.finishNode(node, "RestElement");
  10241. }
  10242. parseBindingAtom() {
  10243. switch (this.state.type) {
  10244. case 0:
  10245. {
  10246. const node = this.startNode();
  10247. this.next();
  10248. node.elements = this.parseBindingList(3, 93, true);
  10249. return this.finishNode(node, "ArrayPattern");
  10250. }
  10251. case 5:
  10252. return this.parseObjectLike(8, true);
  10253. }
  10254. return this.parseIdentifier();
  10255. }
  10256. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  10257. const elts = [];
  10258. let first = true;
  10259. while (!this.eat(close)) {
  10260. if (first) {
  10261. first = false;
  10262. } else {
  10263. this.expect(12);
  10264. }
  10265. if (allowEmpty && this.match(12)) {
  10266. elts.push(null);
  10267. } else if (this.eat(close)) {
  10268. break;
  10269. } else if (this.match(21)) {
  10270. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  10271. if (!this.checkCommaAfterRest(closeCharCode)) {
  10272. this.expect(close);
  10273. break;
  10274. }
  10275. } else {
  10276. const decorators = [];
  10277. if (this.match(26) && this.hasPlugin("decorators")) {
  10278. this.raise(Errors.UnsupportedParameterDecorator, {
  10279. at: this.state.startLoc
  10280. });
  10281. }
  10282. while (this.match(26)) {
  10283. decorators.push(this.parseDecorator());
  10284. }
  10285. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  10286. }
  10287. }
  10288. return elts;
  10289. }
  10290. parseBindingRestProperty(prop) {
  10291. this.next();
  10292. prop.argument = this.parseIdentifier();
  10293. this.checkCommaAfterRest(125);
  10294. return this.finishNode(prop, "RestElement");
  10295. }
  10296. parseBindingProperty() {
  10297. const prop = this.startNode();
  10298. const {
  10299. type,
  10300. startLoc
  10301. } = this.state;
  10302. if (type === 21) {
  10303. return this.parseBindingRestProperty(prop);
  10304. } else if (type === 136) {
  10305. this.expectPlugin("destructuringPrivate", startLoc);
  10306. this.classScope.usePrivateName(this.state.value, startLoc);
  10307. prop.key = this.parsePrivateName();
  10308. } else {
  10309. this.parsePropertyName(prop);
  10310. }
  10311. prop.method = false;
  10312. return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  10313. }
  10314. parseAssignableListItem(allowModifiers, decorators) {
  10315. const left = this.parseMaybeDefault();
  10316. this.parseAssignableListItemTypes(left);
  10317. const elt = this.parseMaybeDefault(left.loc.start, left);
  10318. if (decorators.length) {
  10319. left.decorators = decorators;
  10320. }
  10321. return elt;
  10322. }
  10323. parseAssignableListItemTypes(param) {
  10324. return param;
  10325. }
  10326. parseMaybeDefault(startLoc, left) {
  10327. var _startLoc, _left;
  10328. (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
  10329. left = (_left = left) != null ? _left : this.parseBindingAtom();
  10330. if (!this.eat(29)) return left;
  10331. const node = this.startNodeAt(startLoc);
  10332. node.left = left;
  10333. node.right = this.parseMaybeAssignAllowIn();
  10334. return this.finishNode(node, "AssignmentPattern");
  10335. }
  10336. isValidLVal(type,
  10337. isUnparenthesizedInAssign,
  10338. binding) {
  10339. return getOwn({
  10340. AssignmentPattern: "left",
  10341. RestElement: "argument",
  10342. ObjectProperty: "value",
  10343. ParenthesizedExpression: "expression",
  10344. ArrayPattern: "elements",
  10345. ObjectPattern: "properties"
  10346. },
  10347. type);
  10348. }
  10349. checkLVal(expression, {
  10350. in: ancestor,
  10351. binding = BIND_NONE,
  10352. checkClashes = false,
  10353. strictModeChanged = false,
  10354. allowingSloppyLetBinding = !(binding & BIND_SCOPE_LEXICAL),
  10355. hasParenthesizedAncestor = false
  10356. }) {
  10357. var _expression$extra;
  10358. const type = expression.type;
  10359. if (this.isObjectMethod(expression)) return;
  10360. if (type === "MemberExpression") {
  10361. if (binding !== BIND_NONE) {
  10362. this.raise(Errors.InvalidPropertyBindingPattern, {
  10363. at: expression
  10364. });
  10365. }
  10366. return;
  10367. }
  10368. if (expression.type === "Identifier") {
  10369. this.checkIdentifier(expression, binding, strictModeChanged, allowingSloppyLetBinding);
  10370. const {
  10371. name
  10372. } = expression;
  10373. if (checkClashes) {
  10374. if (checkClashes.has(name)) {
  10375. this.raise(Errors.ParamDupe, {
  10376. at: expression
  10377. });
  10378. } else {
  10379. checkClashes.add(name);
  10380. }
  10381. }
  10382. return;
  10383. }
  10384. const validity = this.isValidLVal(expression.type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
  10385. if (validity === true) return;
  10386. if (validity === false) {
  10387. const ParseErrorClass = binding === BIND_NONE ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
  10388. this.raise(ParseErrorClass, {
  10389. at: expression,
  10390. ancestor: ancestor.type === "UpdateExpression" ? {
  10391. type: "UpdateExpression",
  10392. prefix: ancestor.prefix
  10393. } : {
  10394. type: ancestor.type
  10395. }
  10396. });
  10397. return;
  10398. }
  10399. const [key, isParenthesizedExpression] = Array.isArray(validity) ? validity : [validity, type === "ParenthesizedExpression"];
  10400. const nextAncestor = expression.type === "ArrayPattern" || expression.type === "ObjectPattern" || expression.type === "ParenthesizedExpression" ? expression : ancestor;
  10401. for (const child of [].concat(expression[key])) {
  10402. if (child) {
  10403. this.checkLVal(child, {
  10404. in: nextAncestor,
  10405. binding,
  10406. checkClashes,
  10407. allowingSloppyLetBinding,
  10408. strictModeChanged,
  10409. hasParenthesizedAncestor: isParenthesizedExpression
  10410. });
  10411. }
  10412. }
  10413. }
  10414. checkIdentifier(at, bindingType, strictModeChanged = false, allowLetBinding = !(bindingType & BIND_SCOPE_LEXICAL)) {
  10415. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
  10416. if (bindingType === BIND_NONE) {
  10417. this.raise(Errors.StrictEvalArguments, {
  10418. at,
  10419. referenceName: at.name
  10420. });
  10421. } else {
  10422. this.raise(Errors.StrictEvalArgumentsBinding, {
  10423. at,
  10424. bindingName: at.name
  10425. });
  10426. }
  10427. }
  10428. if (!allowLetBinding && at.name === "let") {
  10429. this.raise(Errors.LetInLexicalBinding, {
  10430. at
  10431. });
  10432. }
  10433. if (!(bindingType & BIND_NONE)) {
  10434. this.declareNameFromIdentifier(at, bindingType);
  10435. }
  10436. }
  10437. declareNameFromIdentifier(identifier, binding) {
  10438. this.scope.declareName(identifier.name, binding, identifier.loc.start);
  10439. }
  10440. checkToRestConversion(node, allowPattern) {
  10441. switch (node.type) {
  10442. case "ParenthesizedExpression":
  10443. this.checkToRestConversion(node.expression, allowPattern);
  10444. break;
  10445. case "Identifier":
  10446. case "MemberExpression":
  10447. break;
  10448. case "ArrayExpression":
  10449. case "ObjectExpression":
  10450. if (allowPattern) break;
  10451. default:
  10452. this.raise(Errors.InvalidRestAssignmentPattern, {
  10453. at: node
  10454. });
  10455. }
  10456. }
  10457. checkCommaAfterRest(close) {
  10458. if (!this.match(12)) {
  10459. return false;
  10460. }
  10461. this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, {
  10462. at: this.state.startLoc
  10463. });
  10464. return true;
  10465. }
  10466. }
  10467. class ExpressionParser extends LValParser {
  10468. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  10469. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed ||
  10470. prop.shorthand) {
  10471. return;
  10472. }
  10473. const key = prop.key;
  10474. const name = key.type === "Identifier" ? key.name : key.value;
  10475. if (name === "__proto__") {
  10476. if (isRecord) {
  10477. this.raise(Errors.RecordNoProto, {
  10478. at: key
  10479. });
  10480. return;
  10481. }
  10482. if (protoRef.used) {
  10483. if (refExpressionErrors) {
  10484. if (refExpressionErrors.doubleProtoLoc === null) {
  10485. refExpressionErrors.doubleProtoLoc = key.loc.start;
  10486. }
  10487. } else {
  10488. this.raise(Errors.DuplicateProto, {
  10489. at: key
  10490. });
  10491. }
  10492. }
  10493. protoRef.used = true;
  10494. }
  10495. }
  10496. shouldExitDescending(expr, potentialArrowAt) {
  10497. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  10498. }
  10499. getExpression() {
  10500. this.enterInitialScopes();
  10501. this.nextToken();
  10502. const expr = this.parseExpression();
  10503. if (!this.match(137)) {
  10504. this.unexpected();
  10505. }
  10506. this.finalizeRemainingComments();
  10507. expr.comments = this.state.comments;
  10508. expr.errors = this.state.errors;
  10509. if (this.options.tokens) {
  10510. expr.tokens = this.tokens;
  10511. }
  10512. return expr;
  10513. }
  10514. parseExpression(disallowIn, refExpressionErrors) {
  10515. if (disallowIn) {
  10516. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10517. }
  10518. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10519. }
  10520. parseExpressionBase(refExpressionErrors) {
  10521. const startLoc = this.state.startLoc;
  10522. const expr = this.parseMaybeAssign(refExpressionErrors);
  10523. if (this.match(12)) {
  10524. const node = this.startNodeAt(startLoc);
  10525. node.expressions = [expr];
  10526. while (this.eat(12)) {
  10527. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10528. }
  10529. this.toReferencedList(node.expressions);
  10530. return this.finishNode(node, "SequenceExpression");
  10531. }
  10532. return expr;
  10533. }
  10534. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10535. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10536. }
  10537. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10538. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10539. }
  10540. setOptionalParametersError(refExpressionErrors, resultError) {
  10541. var _resultError$loc;
  10542. refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc;
  10543. }
  10544. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10545. const startLoc = this.state.startLoc;
  10546. if (this.isContextual(106)) {
  10547. if (this.prodParam.hasYield) {
  10548. let left = this.parseYield();
  10549. if (afterLeftParse) {
  10550. left = afterLeftParse.call(this, left, startLoc);
  10551. }
  10552. return left;
  10553. }
  10554. }
  10555. let ownExpressionErrors;
  10556. if (refExpressionErrors) {
  10557. ownExpressionErrors = false;
  10558. } else {
  10559. refExpressionErrors = new ExpressionErrors();
  10560. ownExpressionErrors = true;
  10561. }
  10562. const {
  10563. type
  10564. } = this.state;
  10565. if (type === 10 || tokenIsIdentifier(type)) {
  10566. this.state.potentialArrowAt = this.state.start;
  10567. }
  10568. let left = this.parseMaybeConditional(refExpressionErrors);
  10569. if (afterLeftParse) {
  10570. left = afterLeftParse.call(this, left, startLoc);
  10571. }
  10572. if (tokenIsAssignment(this.state.type)) {
  10573. const node = this.startNodeAt(startLoc);
  10574. const operator = this.state.value;
  10575. node.operator = operator;
  10576. if (this.match(29)) {
  10577. this.toAssignable(left, true);
  10578. node.left = left;
  10579. const startIndex = startLoc.index;
  10580. if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
  10581. refExpressionErrors.doubleProtoLoc = null;
  10582. }
  10583. if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
  10584. refExpressionErrors.shorthandAssignLoc = null;
  10585. }
  10586. if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
  10587. this.checkDestructuringPrivate(refExpressionErrors);
  10588. refExpressionErrors.privateKeyLoc = null;
  10589. }
  10590. } else {
  10591. node.left = left;
  10592. }
  10593. this.next();
  10594. node.right = this.parseMaybeAssign();
  10595. this.checkLVal(left, {
  10596. in: this.finishNode(node, "AssignmentExpression")
  10597. });
  10598. return node;
  10599. } else if (ownExpressionErrors) {
  10600. this.checkExpressionErrors(refExpressionErrors, true);
  10601. }
  10602. return left;
  10603. }
  10604. parseMaybeConditional(refExpressionErrors) {
  10605. const startLoc = this.state.startLoc;
  10606. const potentialArrowAt = this.state.potentialArrowAt;
  10607. const expr = this.parseExprOps(refExpressionErrors);
  10608. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10609. return expr;
  10610. }
  10611. return this.parseConditional(expr, startLoc, refExpressionErrors);
  10612. }
  10613. parseConditional(expr, startLoc,
  10614. refExpressionErrors) {
  10615. if (this.eat(17)) {
  10616. const node = this.startNodeAt(startLoc);
  10617. node.test = expr;
  10618. node.consequent = this.parseMaybeAssignAllowIn();
  10619. this.expect(14);
  10620. node.alternate = this.parseMaybeAssign();
  10621. return this.finishNode(node, "ConditionalExpression");
  10622. }
  10623. return expr;
  10624. }
  10625. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10626. return this.match(136) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10627. }
  10628. parseExprOps(refExpressionErrors) {
  10629. const startLoc = this.state.startLoc;
  10630. const potentialArrowAt = this.state.potentialArrowAt;
  10631. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10632. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10633. return expr;
  10634. }
  10635. return this.parseExprOp(expr, startLoc, -1);
  10636. }
  10637. parseExprOp(left, leftStartLoc, minPrec) {
  10638. if (this.isPrivateName(left)) {
  10639. const value = this.getPrivateNameSV(left);
  10640. if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
  10641. this.raise(Errors.PrivateInExpectedIn, {
  10642. at: left,
  10643. identifierName: value
  10644. });
  10645. }
  10646. this.classScope.usePrivateName(value, left.loc.start);
  10647. }
  10648. const op = this.state.type;
  10649. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
  10650. let prec = tokenOperatorPrecedence(op);
  10651. if (prec > minPrec) {
  10652. if (op === 39) {
  10653. this.expectPlugin("pipelineOperator");
  10654. if (this.state.inFSharpPipelineDirectBody) {
  10655. return left;
  10656. }
  10657. this.checkPipelineAtInfixOperator(left, leftStartLoc);
  10658. }
  10659. const node = this.startNodeAt(leftStartLoc);
  10660. node.left = left;
  10661. node.operator = this.state.value;
  10662. const logical = op === 41 || op === 42;
  10663. const coalesce = op === 40;
  10664. if (coalesce) {
  10665. prec = tokenOperatorPrecedence(42);
  10666. }
  10667. this.next();
  10668. if (op === 39 && this.hasPlugin(["pipelineOperator", {
  10669. proposal: "minimal"
  10670. }])) {
  10671. if (this.state.type === 96 && this.prodParam.hasAwait) {
  10672. throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, {
  10673. at: this.state.startLoc
  10674. });
  10675. }
  10676. }
  10677. node.right = this.parseExprOpRightExpr(op, prec);
  10678. const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10679. const nextOp = this.state.type;
  10680. if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
  10681. throw this.raise(Errors.MixingCoalesceWithLogical, {
  10682. at: this.state.startLoc
  10683. });
  10684. }
  10685. return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
  10686. }
  10687. }
  10688. return left;
  10689. }
  10690. parseExprOpRightExpr(op, prec) {
  10691. const startLoc = this.state.startLoc;
  10692. switch (op) {
  10693. case 39:
  10694. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10695. case "hack":
  10696. return this.withTopicBindingContext(() => {
  10697. return this.parseHackPipeBody();
  10698. });
  10699. case "smart":
  10700. return this.withTopicBindingContext(() => {
  10701. if (this.prodParam.hasYield && this.isContextual(106)) {
  10702. throw this.raise(Errors.PipeBodyIsTighter, {
  10703. at: this.state.startLoc
  10704. });
  10705. }
  10706. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
  10707. });
  10708. case "fsharp":
  10709. return this.withSoloAwaitPermittingContext(() => {
  10710. return this.parseFSharpPipelineBody(prec);
  10711. });
  10712. }
  10713. default:
  10714. return this.parseExprOpBaseRightExpr(op, prec);
  10715. }
  10716. }
  10717. parseExprOpBaseRightExpr(op, prec) {
  10718. const startLoc = this.state.startLoc;
  10719. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10720. }
  10721. parseHackPipeBody() {
  10722. var _body$extra;
  10723. const {
  10724. startLoc
  10725. } = this.state;
  10726. const body = this.parseMaybeAssign();
  10727. const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(
  10728. body.type);
  10729. if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10730. this.raise(Errors.PipeUnparenthesizedBody, {
  10731. at: startLoc,
  10732. type: body.type
  10733. });
  10734. }
  10735. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10736. this.raise(Errors.PipeTopicUnused, {
  10737. at: startLoc
  10738. });
  10739. }
  10740. return body;
  10741. }
  10742. checkExponentialAfterUnary(node) {
  10743. if (this.match(57)) {
  10744. this.raise(Errors.UnexpectedTokenUnaryExponentiation, {
  10745. at: node.argument
  10746. });
  10747. }
  10748. }
  10749. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10750. const startLoc = this.state.startLoc;
  10751. const isAwait = this.isContextual(96);
  10752. if (isAwait && this.isAwaitAllowed()) {
  10753. this.next();
  10754. const expr = this.parseAwait(startLoc);
  10755. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10756. return expr;
  10757. }
  10758. const update = this.match(34);
  10759. const node = this.startNode();
  10760. if (tokenIsPrefix(this.state.type)) {
  10761. node.operator = this.state.value;
  10762. node.prefix = true;
  10763. if (this.match(72)) {
  10764. this.expectPlugin("throwExpressions");
  10765. }
  10766. const isDelete = this.match(89);
  10767. this.next();
  10768. node.argument = this.parseMaybeUnary(null, true);
  10769. this.checkExpressionErrors(refExpressionErrors, true);
  10770. if (this.state.strict && isDelete) {
  10771. const arg = node.argument;
  10772. if (arg.type === "Identifier") {
  10773. this.raise(Errors.StrictDelete, {
  10774. at: node
  10775. });
  10776. } else if (this.hasPropertyAsPrivateName(arg)) {
  10777. this.raise(Errors.DeletePrivateField, {
  10778. at: node
  10779. });
  10780. }
  10781. }
  10782. if (!update) {
  10783. if (!sawUnary) {
  10784. this.checkExponentialAfterUnary(node);
  10785. }
  10786. return this.finishNode(node, "UnaryExpression");
  10787. }
  10788. }
  10789. const expr = this.parseUpdate(
  10790. node, update, refExpressionErrors);
  10791. if (isAwait) {
  10792. const {
  10793. type
  10794. } = this.state;
  10795. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  10796. if (startsExpr && !this.isAmbiguousAwait()) {
  10797. this.raiseOverwrite(Errors.AwaitNotInAsyncContext, {
  10798. at: startLoc
  10799. });
  10800. return this.parseAwait(startLoc);
  10801. }
  10802. }
  10803. return expr;
  10804. }
  10805. parseUpdate(node, update, refExpressionErrors) {
  10806. if (update) {
  10807. const updateExpressionNode = node;
  10808. this.checkLVal(updateExpressionNode.argument, {
  10809. in: this.finishNode(updateExpressionNode, "UpdateExpression")
  10810. });
  10811. return node;
  10812. }
  10813. const startLoc = this.state.startLoc;
  10814. let expr = this.parseExprSubscripts(refExpressionErrors);
  10815. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10816. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10817. const node = this.startNodeAt(startLoc);
  10818. node.operator = this.state.value;
  10819. node.prefix = false;
  10820. node.argument = expr;
  10821. this.next();
  10822. this.checkLVal(expr, {
  10823. in: expr = this.finishNode(node, "UpdateExpression")
  10824. });
  10825. }
  10826. return expr;
  10827. }
  10828. parseExprSubscripts(refExpressionErrors) {
  10829. const startLoc = this.state.startLoc;
  10830. const potentialArrowAt = this.state.potentialArrowAt;
  10831. const expr = this.parseExprAtom(refExpressionErrors);
  10832. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10833. return expr;
  10834. }
  10835. return this.parseSubscripts(expr, startLoc);
  10836. }
  10837. parseSubscripts(base, startLoc, noCalls) {
  10838. const state = {
  10839. optionalChainMember: false,
  10840. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10841. stop: false
  10842. };
  10843. do {
  10844. base = this.parseSubscript(base, startLoc, noCalls, state);
  10845. state.maybeAsyncArrow = false;
  10846. } while (!state.stop);
  10847. return base;
  10848. }
  10849. parseSubscript(base, startLoc, noCalls, state) {
  10850. const {
  10851. type
  10852. } = this.state;
  10853. if (!noCalls && type === 15) {
  10854. return this.parseBind(base, startLoc, noCalls, state);
  10855. } else if (tokenIsTemplate(type)) {
  10856. return this.parseTaggedTemplateExpression(base, startLoc, state);
  10857. }
  10858. let optional = false;
  10859. if (type === 18) {
  10860. if (noCalls && this.lookaheadCharCode() === 40) {
  10861. state.stop = true;
  10862. return base;
  10863. }
  10864. state.optionalChainMember = optional = true;
  10865. this.next();
  10866. }
  10867. if (!noCalls && this.match(10)) {
  10868. return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional);
  10869. } else {
  10870. const computed = this.eat(0);
  10871. if (computed || optional || this.eat(16)) {
  10872. return this.parseMember(base, startLoc, state, computed, optional);
  10873. } else {
  10874. state.stop = true;
  10875. return base;
  10876. }
  10877. }
  10878. }
  10879. parseMember(base, startLoc, state, computed, optional) {
  10880. const node = this.startNodeAt(startLoc);
  10881. node.object = base;
  10882. node.computed = computed;
  10883. if (computed) {
  10884. node.property = this.parseExpression();
  10885. this.expect(3);
  10886. } else if (this.match(136)) {
  10887. if (base.type === "Super") {
  10888. this.raise(Errors.SuperPrivateField, {
  10889. at: startLoc
  10890. });
  10891. }
  10892. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  10893. node.property = this.parsePrivateName();
  10894. } else {
  10895. node.property = this.parseIdentifier(true);
  10896. }
  10897. if (state.optionalChainMember) {
  10898. node.optional = optional;
  10899. return this.finishNode(node, "OptionalMemberExpression");
  10900. } else {
  10901. return this.finishNode(node, "MemberExpression");
  10902. }
  10903. }
  10904. parseBind(base, startLoc, noCalls, state) {
  10905. const node = this.startNodeAt(startLoc);
  10906. node.object = base;
  10907. this.next();
  10908. node.callee = this.parseNoCallExpr();
  10909. state.stop = true;
  10910. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls);
  10911. }
  10912. parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) {
  10913. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10914. let refExpressionErrors = null;
  10915. this.state.maybeInArrowParameters = true;
  10916. this.next();
  10917. const node = this.startNodeAt(startLoc);
  10918. node.callee = base;
  10919. const {
  10920. maybeAsyncArrow,
  10921. optionalChainMember
  10922. } = state;
  10923. if (maybeAsyncArrow) {
  10924. this.expressionScope.enter(newAsyncArrowScope());
  10925. refExpressionErrors = new ExpressionErrors();
  10926. }
  10927. if (optionalChainMember) {
  10928. node.optional = optional;
  10929. }
  10930. if (optional) {
  10931. node.arguments = this.parseCallExpressionArguments(11);
  10932. } else {
  10933. node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super",
  10934. node, refExpressionErrors);
  10935. }
  10936. let finishedNode = this.finishCallExpression(node, optionalChainMember);
  10937. if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10938. state.stop = true;
  10939. this.checkDestructuringPrivate(refExpressionErrors);
  10940. this.expressionScope.validateAsPattern();
  10941. this.expressionScope.exit();
  10942. finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
  10943. } else {
  10944. if (maybeAsyncArrow) {
  10945. this.checkExpressionErrors(refExpressionErrors, true);
  10946. this.expressionScope.exit();
  10947. }
  10948. this.toReferencedArguments(finishedNode);
  10949. }
  10950. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10951. return finishedNode;
  10952. }
  10953. toReferencedArguments(node, isParenthesizedExpr) {
  10954. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10955. }
  10956. parseTaggedTemplateExpression(base, startLoc, state) {
  10957. const node = this.startNodeAt(startLoc);
  10958. node.tag = base;
  10959. node.quasi = this.parseTemplate(true);
  10960. if (state.optionalChainMember) {
  10961. this.raise(Errors.OptionalChainingNoTemplate, {
  10962. at: startLoc
  10963. });
  10964. }
  10965. return this.finishNode(node, "TaggedTemplateExpression");
  10966. }
  10967. atPossibleAsyncArrow(base) {
  10968. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() &&
  10969. base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  10970. }
  10971. finishCallExpression(node, optional) {
  10972. if (node.callee.type === "Import") {
  10973. if (node.arguments.length === 2) {
  10974. {
  10975. if (!this.hasPlugin("moduleAttributes")) {
  10976. this.expectPlugin("importAssertions");
  10977. }
  10978. }
  10979. }
  10980. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10981. this.raise(Errors.ImportCallArity, {
  10982. at: node,
  10983. maxArgumentCount: this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? 2 : 1
  10984. });
  10985. } else {
  10986. for (const arg of node.arguments) {
  10987. if (arg.type === "SpreadElement") {
  10988. this.raise(Errors.ImportCallSpreadArgument, {
  10989. at: arg
  10990. });
  10991. }
  10992. }
  10993. }
  10994. }
  10995. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10996. }
  10997. parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10998. const elts = [];
  10999. let first = true;
  11000. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11001. this.state.inFSharpPipelineDirectBody = false;
  11002. while (!this.eat(close)) {
  11003. if (first) {
  11004. first = false;
  11005. } else {
  11006. this.expect(12);
  11007. if (this.match(close)) {
  11008. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  11009. this.raise(Errors.ImportCallArgumentTrailingComma, {
  11010. at: this.state.lastTokStartLoc
  11011. });
  11012. }
  11013. if (nodeForExtra) {
  11014. this.addTrailingCommaExtraToNode(nodeForExtra);
  11015. }
  11016. this.next();
  11017. break;
  11018. }
  11019. }
  11020. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  11021. }
  11022. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11023. return elts;
  11024. }
  11025. shouldParseAsyncArrow() {
  11026. return this.match(19) && !this.canInsertSemicolon();
  11027. }
  11028. parseAsyncArrowFromCallExpression(node, call) {
  11029. var _call$extra;
  11030. this.resetPreviousNodeTrailingComments(call);
  11031. this.expect(19);
  11032. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
  11033. if (call.innerComments) {
  11034. setInnerComments(node, call.innerComments);
  11035. }
  11036. if (call.callee.trailingComments) {
  11037. setInnerComments(node, call.callee.trailingComments);
  11038. }
  11039. return node;
  11040. }
  11041. parseNoCallExpr() {
  11042. const startLoc = this.state.startLoc;
  11043. return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  11044. }
  11045. parseExprAtom(refExpressionErrors) {
  11046. let node;
  11047. let decorators = null;
  11048. const {
  11049. type
  11050. } = this.state;
  11051. switch (type) {
  11052. case 79:
  11053. return this.parseSuper();
  11054. case 83:
  11055. node = this.startNode();
  11056. this.next();
  11057. if (this.match(16)) {
  11058. return this.parseImportMetaProperty(node);
  11059. }
  11060. if (!this.match(10)) {
  11061. this.raise(Errors.UnsupportedImport, {
  11062. at: this.state.lastTokStartLoc
  11063. });
  11064. }
  11065. return this.finishNode(node, "Import");
  11066. case 78:
  11067. node = this.startNode();
  11068. this.next();
  11069. return this.finishNode(node, "ThisExpression");
  11070. case 90:
  11071. {
  11072. return this.parseDo(this.startNode(), false);
  11073. }
  11074. case 56:
  11075. case 31:
  11076. {
  11077. this.readRegexp();
  11078. return this.parseRegExpLiteral(this.state.value);
  11079. }
  11080. case 132:
  11081. return this.parseNumericLiteral(this.state.value);
  11082. case 133:
  11083. return this.parseBigIntLiteral(this.state.value);
  11084. case 134:
  11085. return this.parseDecimalLiteral(this.state.value);
  11086. case 131:
  11087. return this.parseStringLiteral(this.state.value);
  11088. case 84:
  11089. return this.parseNullLiteral();
  11090. case 85:
  11091. return this.parseBooleanLiteral(true);
  11092. case 86:
  11093. return this.parseBooleanLiteral(false);
  11094. case 10:
  11095. {
  11096. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  11097. return this.parseParenAndDistinguishExpression(canBeArrow);
  11098. }
  11099. case 2:
  11100. case 1:
  11101. {
  11102. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  11103. }
  11104. case 0:
  11105. {
  11106. return this.parseArrayLike(3, true, false, refExpressionErrors);
  11107. }
  11108. case 6:
  11109. case 7:
  11110. {
  11111. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  11112. }
  11113. case 5:
  11114. {
  11115. return this.parseObjectLike(8, false, false, refExpressionErrors);
  11116. }
  11117. case 68:
  11118. return this.parseFunctionOrFunctionSent();
  11119. case 26:
  11120. decorators = this.parseDecorators();
  11121. case 80:
  11122. return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
  11123. case 77:
  11124. return this.parseNewOrNewTarget();
  11125. case 25:
  11126. case 24:
  11127. return this.parseTemplate(false);
  11128. case 15:
  11129. {
  11130. node = this.startNode();
  11131. this.next();
  11132. node.object = null;
  11133. const callee = node.callee = this.parseNoCallExpr();
  11134. if (callee.type === "MemberExpression") {
  11135. return this.finishNode(node, "BindExpression");
  11136. } else {
  11137. throw this.raise(Errors.UnsupportedBind, {
  11138. at: callee
  11139. });
  11140. }
  11141. }
  11142. case 136:
  11143. {
  11144. this.raise(Errors.PrivateInExpectedIn, {
  11145. at: this.state.startLoc,
  11146. identifierName: this.state.value
  11147. });
  11148. return this.parsePrivateName();
  11149. }
  11150. case 33:
  11151. {
  11152. return this.parseTopicReferenceThenEqualsSign(54, "%");
  11153. }
  11154. case 32:
  11155. {
  11156. return this.parseTopicReferenceThenEqualsSign(44, "^");
  11157. }
  11158. case 37:
  11159. case 38:
  11160. {
  11161. return this.parseTopicReference("hack");
  11162. }
  11163. case 44:
  11164. case 54:
  11165. case 27:
  11166. {
  11167. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  11168. if (pipeProposal) {
  11169. return this.parseTopicReference(pipeProposal);
  11170. } else {
  11171. throw this.unexpected();
  11172. }
  11173. }
  11174. case 47:
  11175. {
  11176. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  11177. if (isIdentifierStart(lookaheadCh) ||
  11178. lookaheadCh === 62) {
  11179. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  11180. break;
  11181. } else {
  11182. throw this.unexpected();
  11183. }
  11184. }
  11185. default:
  11186. if (tokenIsIdentifier(type)) {
  11187. if (this.isContextual(125) && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
  11188. return this.parseModuleExpression();
  11189. }
  11190. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  11191. const containsEsc = this.state.containsEsc;
  11192. const id = this.parseIdentifier();
  11193. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  11194. const {
  11195. type
  11196. } = this.state;
  11197. if (type === 68) {
  11198. this.resetPreviousNodeTrailingComments(id);
  11199. this.next();
  11200. return this.parseAsyncFunctionExpression(this.startNodeAtNode(id));
  11201. } else if (tokenIsIdentifier(type)) {
  11202. if (this.lookaheadCharCode() === 61) {
  11203. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  11204. } else {
  11205. return id;
  11206. }
  11207. } else if (type === 90) {
  11208. this.resetPreviousNodeTrailingComments(id);
  11209. return this.parseDo(this.startNodeAtNode(id), true);
  11210. }
  11211. }
  11212. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  11213. this.next();
  11214. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  11215. }
  11216. return id;
  11217. } else {
  11218. throw this.unexpected();
  11219. }
  11220. }
  11221. }
  11222. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  11223. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  11224. if (pipeProposal) {
  11225. this.state.type = topicTokenType;
  11226. this.state.value = topicTokenValue;
  11227. this.state.pos--;
  11228. this.state.end--;
  11229. this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
  11230. return this.parseTopicReference(pipeProposal);
  11231. } else {
  11232. throw this.unexpected();
  11233. }
  11234. }
  11235. parseTopicReference(pipeProposal) {
  11236. const node = this.startNode();
  11237. const startLoc = this.state.startLoc;
  11238. const tokenType = this.state.type;
  11239. this.next();
  11240. return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);
  11241. }
  11242. finishTopicReference(node, startLoc, pipeProposal, tokenType) {
  11243. if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
  11244. const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" :
  11245. "TopicReference";
  11246. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  11247. this.raise(
  11248. pipeProposal === "smart" ? Errors.PrimaryTopicNotAllowed :
  11249. Errors.PipeTopicUnbound, {
  11250. at: startLoc
  11251. });
  11252. }
  11253. this.registerTopicReference();
  11254. return this.finishNode(node, nodeType);
  11255. } else {
  11256. throw this.raise(Errors.PipeTopicUnconfiguredToken, {
  11257. at: startLoc,
  11258. token: tokenLabelName(tokenType)
  11259. });
  11260. }
  11261. }
  11262. testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
  11263. switch (pipeProposal) {
  11264. case "hack":
  11265. {
  11266. return this.hasPlugin(["pipelineOperator", {
  11267. topicToken: tokenLabelName(tokenType)
  11268. }]);
  11269. }
  11270. case "smart":
  11271. return tokenType === 27;
  11272. default:
  11273. throw this.raise(Errors.PipeTopicRequiresHackPipes, {
  11274. at: startLoc
  11275. });
  11276. }
  11277. }
  11278. parseAsyncArrowUnaryFunction(node) {
  11279. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  11280. const params = [this.parseIdentifier()];
  11281. this.prodParam.exit();
  11282. if (this.hasPrecedingLineBreak()) {
  11283. this.raise(Errors.LineTerminatorBeforeArrow, {
  11284. at: this.state.curPosition()
  11285. });
  11286. }
  11287. this.expect(19);
  11288. return this.parseArrowExpression(node, params, true);
  11289. }
  11290. parseDo(node, isAsync) {
  11291. this.expectPlugin("doExpressions");
  11292. if (isAsync) {
  11293. this.expectPlugin("asyncDoExpressions");
  11294. }
  11295. node.async = isAsync;
  11296. this.next();
  11297. const oldLabels = this.state.labels;
  11298. this.state.labels = [];
  11299. if (isAsync) {
  11300. this.prodParam.enter(PARAM_AWAIT);
  11301. node.body = this.parseBlock();
  11302. this.prodParam.exit();
  11303. } else {
  11304. node.body = this.parseBlock();
  11305. }
  11306. this.state.labels = oldLabels;
  11307. return this.finishNode(node, "DoExpression");
  11308. }
  11309. parseSuper() {
  11310. const node = this.startNode();
  11311. this.next();
  11312. if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  11313. this.raise(Errors.SuperNotAllowed, {
  11314. at: node
  11315. });
  11316. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  11317. this.raise(Errors.UnexpectedSuper, {
  11318. at: node
  11319. });
  11320. }
  11321. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  11322. this.raise(Errors.UnsupportedSuper, {
  11323. at: node
  11324. });
  11325. }
  11326. return this.finishNode(node, "Super");
  11327. }
  11328. parsePrivateName() {
  11329. const node = this.startNode();
  11330. const id = this.startNodeAt(
  11331. createPositionWithColumnOffset(this.state.startLoc, 1));
  11332. const name = this.state.value;
  11333. this.next();
  11334. node.id = this.createIdentifier(id, name);
  11335. return this.finishNode(node, "PrivateName");
  11336. }
  11337. parseFunctionOrFunctionSent() {
  11338. const node = this.startNode();
  11339. this.next();
  11340. if (this.prodParam.hasYield && this.match(16)) {
  11341. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  11342. this.next();
  11343. if (this.match(102)) {
  11344. this.expectPlugin("functionSent");
  11345. } else if (!this.hasPlugin("functionSent")) {
  11346. this.unexpected();
  11347. }
  11348. return this.parseMetaProperty(node, meta, "sent");
  11349. }
  11350. return this.parseFunction(node);
  11351. }
  11352. parseMetaProperty(node, meta, propertyName) {
  11353. node.meta = meta;
  11354. const containsEsc = this.state.containsEsc;
  11355. node.property = this.parseIdentifier(true);
  11356. if (node.property.name !== propertyName || containsEsc) {
  11357. this.raise(Errors.UnsupportedMetaProperty, {
  11358. at: node.property,
  11359. target: meta.name,
  11360. onlyValidPropertyName: propertyName
  11361. });
  11362. }
  11363. return this.finishNode(node, "MetaProperty");
  11364. }
  11365. parseImportMetaProperty(node) {
  11366. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  11367. this.next();
  11368. if (this.isContextual(100)) {
  11369. if (!this.inModule) {
  11370. this.raise(Errors.ImportMetaOutsideModule, {
  11371. at: id
  11372. });
  11373. }
  11374. this.sawUnambiguousESM = true;
  11375. }
  11376. return this.parseMetaProperty(node, id, "meta");
  11377. }
  11378. parseLiteralAtNode(value, type, node) {
  11379. this.addExtra(node, "rawValue", value);
  11380. this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
  11381. node.value = value;
  11382. this.next();
  11383. return this.finishNode(node, type);
  11384. }
  11385. parseLiteral(value, type) {
  11386. const node = this.startNode();
  11387. return this.parseLiteralAtNode(value, type, node);
  11388. }
  11389. parseStringLiteral(value) {
  11390. return this.parseLiteral(value, "StringLiteral");
  11391. }
  11392. parseNumericLiteral(value) {
  11393. return this.parseLiteral(value, "NumericLiteral");
  11394. }
  11395. parseBigIntLiteral(value) {
  11396. return this.parseLiteral(value, "BigIntLiteral");
  11397. }
  11398. parseDecimalLiteral(value) {
  11399. return this.parseLiteral(value, "DecimalLiteral");
  11400. }
  11401. parseRegExpLiteral(value) {
  11402. const node = this.parseLiteral(value.value, "RegExpLiteral");
  11403. node.pattern = value.pattern;
  11404. node.flags = value.flags;
  11405. return node;
  11406. }
  11407. parseBooleanLiteral(value) {
  11408. const node = this.startNode();
  11409. node.value = value;
  11410. this.next();
  11411. return this.finishNode(node, "BooleanLiteral");
  11412. }
  11413. parseNullLiteral() {
  11414. const node = this.startNode();
  11415. this.next();
  11416. return this.finishNode(node, "NullLiteral");
  11417. }
  11418. parseParenAndDistinguishExpression(canBeArrow) {
  11419. const startLoc = this.state.startLoc;
  11420. let val;
  11421. this.next();
  11422. this.expressionScope.enter(newArrowHeadScope());
  11423. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11424. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11425. this.state.maybeInArrowParameters = true;
  11426. this.state.inFSharpPipelineDirectBody = false;
  11427. const innerStartLoc = this.state.startLoc;
  11428. const exprList = [];
  11429. const refExpressionErrors = new ExpressionErrors();
  11430. let first = true;
  11431. let spreadStartLoc;
  11432. let optionalCommaStartLoc;
  11433. while (!this.match(11)) {
  11434. if (first) {
  11435. first = false;
  11436. } else {
  11437. this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
  11438. if (this.match(11)) {
  11439. optionalCommaStartLoc = this.state.startLoc;
  11440. break;
  11441. }
  11442. }
  11443. if (this.match(21)) {
  11444. const spreadNodeStartLoc = this.state.startLoc;
  11445. spreadStartLoc = this.state.startLoc;
  11446. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
  11447. if (!this.checkCommaAfterRest(41)) {
  11448. break;
  11449. }
  11450. } else {
  11451. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  11452. }
  11453. }
  11454. const innerEndLoc = this.state.lastTokEndLoc;
  11455. this.expect(11);
  11456. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11457. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11458. let arrowNode = this.startNodeAt(startLoc);
  11459. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  11460. this.checkDestructuringPrivate(refExpressionErrors);
  11461. this.expressionScope.validateAsPattern();
  11462. this.expressionScope.exit();
  11463. this.parseArrowExpression(arrowNode, exprList, false);
  11464. return arrowNode;
  11465. }
  11466. this.expressionScope.exit();
  11467. if (!exprList.length) {
  11468. this.unexpected(this.state.lastTokStartLoc);
  11469. }
  11470. if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);
  11471. if (spreadStartLoc) this.unexpected(spreadStartLoc);
  11472. this.checkExpressionErrors(refExpressionErrors, true);
  11473. this.toReferencedListDeep(exprList, true);
  11474. if (exprList.length > 1) {
  11475. val = this.startNodeAt(innerStartLoc);
  11476. val.expressions = exprList;
  11477. this.finishNode(val, "SequenceExpression");
  11478. this.resetEndLocation(val, innerEndLoc);
  11479. } else {
  11480. val = exprList[0];
  11481. }
  11482. return this.wrapParenthesis(startLoc,
  11483. val);
  11484. }
  11485. wrapParenthesis(startLoc, expression) {
  11486. if (!this.options.createParenthesizedExpressions) {
  11487. this.addExtra(expression, "parenthesized", true);
  11488. this.addExtra(expression, "parenStart", startLoc.index);
  11489. this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
  11490. return expression;
  11491. }
  11492. const parenExpression = this.startNodeAt(startLoc);
  11493. parenExpression.expression = expression;
  11494. return this.finishNode(parenExpression, "ParenthesizedExpression");
  11495. }
  11496. shouldParseArrow(params) {
  11497. return !this.canInsertSemicolon();
  11498. }
  11499. parseArrow(node) {
  11500. if (this.eat(19)) {
  11501. return node;
  11502. }
  11503. }
  11504. parseParenItem(node,
  11505. startLoc) {
  11506. return node;
  11507. }
  11508. parseNewOrNewTarget() {
  11509. const node = this.startNode();
  11510. this.next();
  11511. if (this.match(16)) {
  11512. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  11513. this.next();
  11514. const metaProp = this.parseMetaProperty(node, meta, "target");
  11515. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  11516. this.raise(Errors.UnexpectedNewTarget, {
  11517. at: metaProp
  11518. });
  11519. }
  11520. return metaProp;
  11521. }
  11522. return this.parseNew(node);
  11523. }
  11524. parseNew(node) {
  11525. this.parseNewCallee(node);
  11526. if (this.eat(10)) {
  11527. const args = this.parseExprList(11);
  11528. this.toReferencedList(args);
  11529. node.arguments = args;
  11530. } else {
  11531. node.arguments = [];
  11532. }
  11533. return this.finishNode(node, "NewExpression");
  11534. }
  11535. parseNewCallee(node) {
  11536. node.callee = this.parseNoCallExpr();
  11537. if (node.callee.type === "Import") {
  11538. this.raise(Errors.ImportCallNotNewExpression, {
  11539. at: node.callee
  11540. });
  11541. } else if (this.isOptionalChain(node.callee)) {
  11542. this.raise(Errors.OptionalChainingNoNew, {
  11543. at: this.state.lastTokEndLoc
  11544. });
  11545. } else if (this.eat(18)) {
  11546. this.raise(Errors.OptionalChainingNoNew, {
  11547. at: this.state.startLoc
  11548. });
  11549. }
  11550. }
  11551. parseTemplateElement(isTagged) {
  11552. const {
  11553. start,
  11554. startLoc,
  11555. end,
  11556. value
  11557. } = this.state;
  11558. const elemStart = start + 1;
  11559. const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
  11560. if (value === null) {
  11561. if (!isTagged) {
  11562. this.raise(Errors.InvalidEscapeSequenceTemplate, {
  11563. at: createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1)
  11564. });
  11565. }
  11566. }
  11567. const isTail = this.match(24);
  11568. const endOffset = isTail ? -1 : -2;
  11569. const elemEnd = end + endOffset;
  11570. elem.value = {
  11571. raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
  11572. cooked: value === null ? null : value.slice(1, endOffset)
  11573. };
  11574. elem.tail = isTail;
  11575. this.next();
  11576. const finishedNode = this.finishNode(elem, "TemplateElement");
  11577. this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
  11578. return finishedNode;
  11579. }
  11580. parseTemplate(isTagged) {
  11581. const node = this.startNode();
  11582. node.expressions = [];
  11583. let curElt = this.parseTemplateElement(isTagged);
  11584. node.quasis = [curElt];
  11585. while (!curElt.tail) {
  11586. node.expressions.push(this.parseTemplateSubstitution());
  11587. this.readTemplateContinuation();
  11588. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  11589. }
  11590. return this.finishNode(node, "TemplateLiteral");
  11591. }
  11592. parseTemplateSubstitution() {
  11593. return this.parseExpression();
  11594. }
  11595. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11596. if (isRecord) {
  11597. this.expectPlugin("recordAndTuple");
  11598. }
  11599. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11600. this.state.inFSharpPipelineDirectBody = false;
  11601. const propHash = Object.create(null);
  11602. let first = true;
  11603. const node = this.startNode();
  11604. node.properties = [];
  11605. this.next();
  11606. while (!this.match(close)) {
  11607. if (first) {
  11608. first = false;
  11609. } else {
  11610. this.expect(12);
  11611. if (this.match(close)) {
  11612. this.addTrailingCommaExtraToNode(
  11613. node);
  11614. break;
  11615. }
  11616. }
  11617. let prop;
  11618. if (isPattern) {
  11619. prop = this.parseBindingProperty();
  11620. } else {
  11621. prop = this.parsePropertyDefinition(refExpressionErrors);
  11622. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  11623. }
  11624. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11625. this.raise(Errors.InvalidRecordProperty, {
  11626. at: prop
  11627. });
  11628. }
  11629. if (prop.shorthand) {
  11630. this.addExtra(prop, "shorthand", true);
  11631. }
  11632. node.properties.push(prop);
  11633. }
  11634. this.next();
  11635. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11636. let type = "ObjectExpression";
  11637. if (isPattern) {
  11638. type = "ObjectPattern";
  11639. } else if (isRecord) {
  11640. type = "RecordExpression";
  11641. }
  11642. return this.finishNode(node, type);
  11643. }
  11644. addTrailingCommaExtraToNode(node) {
  11645. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  11646. this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  11647. }
  11648. maybeAsyncOrAccessorProp(prop) {
  11649. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  11650. }
  11651. parsePropertyDefinition(refExpressionErrors) {
  11652. let decorators = [];
  11653. if (this.match(26)) {
  11654. if (this.hasPlugin("decorators")) {
  11655. this.raise(Errors.UnsupportedPropertyDecorator, {
  11656. at: this.state.startLoc
  11657. });
  11658. }
  11659. while (this.match(26)) {
  11660. decorators.push(this.parseDecorator());
  11661. }
  11662. }
  11663. const prop = this.startNode();
  11664. let isAsync = false;
  11665. let isAccessor = false;
  11666. let startLoc;
  11667. if (this.match(21)) {
  11668. if (decorators.length) this.unexpected();
  11669. return this.parseSpread();
  11670. }
  11671. if (decorators.length) {
  11672. prop.decorators = decorators;
  11673. decorators = [];
  11674. }
  11675. prop.method = false;
  11676. if (refExpressionErrors) {
  11677. startLoc = this.state.startLoc;
  11678. }
  11679. let isGenerator = this.eat(55);
  11680. this.parsePropertyNamePrefixOperator(prop);
  11681. const containsEsc = this.state.containsEsc;
  11682. const key = this.parsePropertyName(prop, refExpressionErrors);
  11683. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11684. const keyName = key.name;
  11685. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11686. isAsync = true;
  11687. this.resetPreviousNodeTrailingComments(key);
  11688. isGenerator = this.eat(55);
  11689. this.parsePropertyName(prop);
  11690. }
  11691. if (keyName === "get" || keyName === "set") {
  11692. isAccessor = true;
  11693. this.resetPreviousNodeTrailingComments(key);
  11694. prop.kind = keyName;
  11695. if (this.match(55)) {
  11696. isGenerator = true;
  11697. this.raise(Errors.AccessorIsGenerator, {
  11698. at: this.state.curPosition(),
  11699. kind: keyName
  11700. });
  11701. this.next();
  11702. }
  11703. this.parsePropertyName(prop);
  11704. }
  11705. }
  11706. return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11707. }
  11708. getGetterSetterExpectedParamCount(method) {
  11709. return method.kind === "get" ? 0 : 1;
  11710. }
  11711. getObjectOrClassMethodParams(method) {
  11712. return method.params;
  11713. }
  11714. checkGetterSetterParams(method) {
  11715. var _params;
  11716. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11717. const params = this.getObjectOrClassMethodParams(method);
  11718. if (params.length !== paramCount) {
  11719. this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, {
  11720. at: method
  11721. });
  11722. }
  11723. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11724. this.raise(Errors.BadSetterRestParameter, {
  11725. at: method
  11726. });
  11727. }
  11728. }
  11729. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11730. if (isAccessor) {
  11731. const finishedProp = this.parseMethod(prop,
  11732. isGenerator, false, false, false, "ObjectMethod");
  11733. this.checkGetterSetterParams(finishedProp);
  11734. return finishedProp;
  11735. }
  11736. if (isAsync || isGenerator || this.match(10)) {
  11737. if (isPattern) this.unexpected();
  11738. prop.kind = "method";
  11739. prop.method = true;
  11740. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11741. }
  11742. }
  11743. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  11744. prop.shorthand = false;
  11745. if (this.eat(14)) {
  11746. prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11747. return this.finishNode(prop, "ObjectProperty");
  11748. }
  11749. if (!prop.computed && prop.key.type === "Identifier") {
  11750. this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
  11751. if (isPattern) {
  11752. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11753. } else if (this.match(29)) {
  11754. const shorthandAssignLoc = this.state.startLoc;
  11755. if (refExpressionErrors != null) {
  11756. if (refExpressionErrors.shorthandAssignLoc === null) {
  11757. refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
  11758. }
  11759. } else {
  11760. this.raise(Errors.InvalidCoverInitializedName, {
  11761. at: shorthandAssignLoc
  11762. });
  11763. }
  11764. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11765. } else {
  11766. prop.value = cloneIdentifier(prop.key);
  11767. }
  11768. prop.shorthand = true;
  11769. return this.finishNode(prop, "ObjectProperty");
  11770. }
  11771. }
  11772. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11773. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  11774. if (!node) this.unexpected();
  11775. return node;
  11776. }
  11777. parsePropertyName(prop, refExpressionErrors) {
  11778. if (this.eat(0)) {
  11779. prop.computed = true;
  11780. prop.key = this.parseMaybeAssignAllowIn();
  11781. this.expect(3);
  11782. } else {
  11783. const {
  11784. type,
  11785. value
  11786. } = this.state;
  11787. let key;
  11788. if (tokenIsKeywordOrIdentifier(type)) {
  11789. key = this.parseIdentifier(true);
  11790. } else {
  11791. switch (type) {
  11792. case 132:
  11793. key = this.parseNumericLiteral(value);
  11794. break;
  11795. case 131:
  11796. key = this.parseStringLiteral(value);
  11797. break;
  11798. case 133:
  11799. key = this.parseBigIntLiteral(value);
  11800. break;
  11801. case 134:
  11802. key = this.parseDecimalLiteral(value);
  11803. break;
  11804. case 136:
  11805. {
  11806. const privateKeyLoc = this.state.startLoc;
  11807. if (refExpressionErrors != null) {
  11808. if (refExpressionErrors.privateKeyLoc === null) {
  11809. refExpressionErrors.privateKeyLoc = privateKeyLoc;
  11810. }
  11811. } else {
  11812. this.raise(Errors.UnexpectedPrivateField, {
  11813. at: privateKeyLoc
  11814. });
  11815. }
  11816. key = this.parsePrivateName();
  11817. break;
  11818. }
  11819. default:
  11820. throw this.unexpected();
  11821. }
  11822. }
  11823. prop.key = key;
  11824. if (type !== 136) {
  11825. prop.computed = false;
  11826. }
  11827. }
  11828. return prop.key;
  11829. }
  11830. initFunction(node, isAsync) {
  11831. node.id = null;
  11832. node.generator = false;
  11833. node.async = isAsync;
  11834. }
  11835. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11836. this.initFunction(node, isAsync);
  11837. node.generator = isGenerator;
  11838. const allowModifiers = isConstructor;
  11839. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  11840. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11841. this.parseFunctionParams(node, allowModifiers);
  11842. const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
  11843. this.prodParam.exit();
  11844. this.scope.exit();
  11845. return finishedNode;
  11846. }
  11847. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11848. if (isTuple) {
  11849. this.expectPlugin("recordAndTuple");
  11850. }
  11851. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11852. this.state.inFSharpPipelineDirectBody = false;
  11853. const node = this.startNode();
  11854. this.next();
  11855. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors,
  11856. node);
  11857. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11858. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11859. }
  11860. parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
  11861. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  11862. let flags = functionFlags(isAsync, false);
  11863. if (!this.match(5) && this.prodParam.hasIn) {
  11864. flags |= PARAM_IN;
  11865. }
  11866. this.prodParam.enter(flags);
  11867. this.initFunction(node, isAsync);
  11868. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11869. if (params) {
  11870. this.state.maybeInArrowParameters = true;
  11871. this.setArrowFunctionParameters(node, params, trailingCommaLoc);
  11872. }
  11873. this.state.maybeInArrowParameters = false;
  11874. this.parseFunctionBody(node, true);
  11875. this.prodParam.exit();
  11876. this.scope.exit();
  11877. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11878. return this.finishNode(node, "ArrowFunctionExpression");
  11879. }
  11880. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  11881. this.toAssignableList(params, trailingCommaLoc, false);
  11882. node.params = params;
  11883. }
  11884. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11885. this.parseFunctionBody(node, false, isMethod);
  11886. return this.finishNode(node, type);
  11887. }
  11888. parseFunctionBody(node, allowExpression, isMethod = false) {
  11889. const isExpression = allowExpression && !this.match(5);
  11890. this.expressionScope.enter(newExpressionScope());
  11891. if (isExpression) {
  11892. node.body = this.parseMaybeAssign();
  11893. this.checkParams(node, false, allowExpression, false);
  11894. } else {
  11895. const oldStrict = this.state.strict;
  11896. const oldLabels = this.state.labels;
  11897. this.state.labels = [];
  11898. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  11899. node.body = this.parseBlock(true, false,
  11900. hasStrictModeDirective => {
  11901. const nonSimple = !this.isSimpleParamList(node.params);
  11902. if (hasStrictModeDirective && nonSimple) {
  11903. this.raise(Errors.IllegalLanguageModeDirective, {
  11904. at:
  11905. (node.kind === "method" || node.kind === "constructor") &&
  11906. !!node.key ?
  11907. node.key.loc.end : node
  11908. });
  11909. }
  11910. const strictModeChanged = !oldStrict && this.state.strict;
  11911. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11912. if (this.state.strict && node.id) {
  11913. this.checkIdentifier(node.id, BIND_OUTSIDE, strictModeChanged);
  11914. }
  11915. });
  11916. this.prodParam.exit();
  11917. this.state.labels = oldLabels;
  11918. }
  11919. this.expressionScope.exit();
  11920. }
  11921. isSimpleParameter(node) {
  11922. return node.type === "Identifier";
  11923. }
  11924. isSimpleParamList(params) {
  11925. for (let i = 0, len = params.length; i < len; i++) {
  11926. if (!this.isSimpleParameter(params[i])) return false;
  11927. }
  11928. return true;
  11929. }
  11930. checkParams(node, allowDuplicates,
  11931. isArrowFunction, strictModeChanged = true) {
  11932. const checkClashes = !allowDuplicates && new Set();
  11933. const formalParameters = {
  11934. type: "FormalParameters"
  11935. };
  11936. for (const param of node.params) {
  11937. this.checkLVal(param, {
  11938. in: formalParameters,
  11939. binding: BIND_VAR,
  11940. checkClashes,
  11941. strictModeChanged
  11942. });
  11943. }
  11944. }
  11945. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11946. const elts = [];
  11947. let first = true;
  11948. while (!this.eat(close)) {
  11949. if (first) {
  11950. first = false;
  11951. } else {
  11952. this.expect(12);
  11953. if (this.match(close)) {
  11954. if (nodeForExtra) {
  11955. this.addTrailingCommaExtraToNode(nodeForExtra);
  11956. }
  11957. this.next();
  11958. break;
  11959. }
  11960. }
  11961. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11962. }
  11963. return elts;
  11964. }
  11965. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11966. let elt;
  11967. if (this.match(12)) {
  11968. if (!allowEmpty) {
  11969. this.raise(Errors.UnexpectedToken, {
  11970. at: this.state.curPosition(),
  11971. unexpected: ","
  11972. });
  11973. }
  11974. elt = null;
  11975. } else if (this.match(21)) {
  11976. const spreadNodeStartLoc = this.state.startLoc;
  11977. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
  11978. } else if (this.match(17)) {
  11979. this.expectPlugin("partialApplication");
  11980. if (!allowPlaceholder) {
  11981. this.raise(Errors.UnexpectedArgumentPlaceholder, {
  11982. at: this.state.startLoc
  11983. });
  11984. }
  11985. const node = this.startNode();
  11986. this.next();
  11987. elt = this.finishNode(node, "ArgumentPlaceholder");
  11988. } else {
  11989. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11990. }
  11991. return elt;
  11992. }
  11993. parseIdentifier(liberal) {
  11994. const node = this.startNode();
  11995. const name = this.parseIdentifierName(liberal);
  11996. return this.createIdentifier(node, name);
  11997. }
  11998. createIdentifier(node, name) {
  11999. node.name = name;
  12000. node.loc.identifierName = name;
  12001. return this.finishNode(node, "Identifier");
  12002. }
  12003. parseIdentifierName(liberal) {
  12004. let name;
  12005. const {
  12006. startLoc,
  12007. type
  12008. } = this.state;
  12009. if (tokenIsKeywordOrIdentifier(type)) {
  12010. name = this.state.value;
  12011. } else {
  12012. throw this.unexpected();
  12013. }
  12014. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  12015. if (liberal) {
  12016. if (tokenIsKeyword) {
  12017. this.replaceToken(130);
  12018. }
  12019. } else {
  12020. this.checkReservedWord(name, startLoc, tokenIsKeyword, false);
  12021. }
  12022. this.next();
  12023. return name;
  12024. }
  12025. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  12026. if (word.length > 10) {
  12027. return;
  12028. }
  12029. if (!canBeReservedWord(word)) {
  12030. return;
  12031. }
  12032. if (word === "yield") {
  12033. if (this.prodParam.hasYield) {
  12034. this.raise(Errors.YieldBindingIdentifier, {
  12035. at: startLoc
  12036. });
  12037. return;
  12038. }
  12039. } else if (word === "await") {
  12040. if (this.prodParam.hasAwait) {
  12041. this.raise(Errors.AwaitBindingIdentifier, {
  12042. at: startLoc
  12043. });
  12044. return;
  12045. }
  12046. if (this.scope.inStaticBlock) {
  12047. this.raise(Errors.AwaitBindingIdentifierInStaticBlock, {
  12048. at: startLoc
  12049. });
  12050. return;
  12051. }
  12052. this.expressionScope.recordAsyncArrowParametersError({
  12053. at: startLoc
  12054. });
  12055. } else if (word === "arguments") {
  12056. if (this.scope.inClassAndNotInNonArrowFunction) {
  12057. this.raise(Errors.ArgumentsInClass, {
  12058. at: startLoc
  12059. });
  12060. return;
  12061. }
  12062. }
  12063. if (checkKeywords && isKeyword(word)) {
  12064. this.raise(Errors.UnexpectedKeyword, {
  12065. at: startLoc,
  12066. keyword: word
  12067. });
  12068. return;
  12069. }
  12070. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  12071. if (reservedTest(word, this.inModule)) {
  12072. this.raise(Errors.UnexpectedReservedWord, {
  12073. at: startLoc,
  12074. reservedWord: word
  12075. });
  12076. }
  12077. }
  12078. isAwaitAllowed() {
  12079. if (this.prodParam.hasAwait) return true;
  12080. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  12081. return true;
  12082. }
  12083. return false;
  12084. }
  12085. parseAwait(startLoc) {
  12086. const node = this.startNodeAt(startLoc);
  12087. this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, {
  12088. at: node
  12089. });
  12090. if (this.eat(55)) {
  12091. this.raise(Errors.ObsoleteAwaitStar, {
  12092. at: node
  12093. });
  12094. }
  12095. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  12096. if (this.isAmbiguousAwait()) {
  12097. this.ambiguousScriptDifferentAst = true;
  12098. } else {
  12099. this.sawUnambiguousESM = true;
  12100. }
  12101. }
  12102. if (!this.state.soloAwait) {
  12103. node.argument = this.parseMaybeUnary(null, true);
  12104. }
  12105. return this.finishNode(node, "AwaitExpression");
  12106. }
  12107. isAmbiguousAwait() {
  12108. if (this.hasPrecedingLineBreak()) return true;
  12109. const {
  12110. type
  12111. } = this.state;
  12112. return (
  12113. type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 101 && !this.state.containsEsc ||
  12114. type === 135 || type === 56 ||
  12115. this.hasPlugin("v8intrinsic") && type === 54
  12116. );
  12117. }
  12118. parseYield() {
  12119. const node = this.startNode();
  12120. this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, {
  12121. at: node
  12122. });
  12123. this.next();
  12124. let delegating = false;
  12125. let argument = null;
  12126. if (!this.hasPrecedingLineBreak()) {
  12127. delegating = this.eat(55);
  12128. switch (this.state.type) {
  12129. case 13:
  12130. case 137:
  12131. case 8:
  12132. case 11:
  12133. case 3:
  12134. case 9:
  12135. case 14:
  12136. case 12:
  12137. if (!delegating) break;
  12138. default:
  12139. argument = this.parseMaybeAssign();
  12140. }
  12141. }
  12142. node.delegate = delegating;
  12143. node.argument = argument;
  12144. return this.finishNode(node, "YieldExpression");
  12145. }
  12146. checkPipelineAtInfixOperator(left, leftStartLoc) {
  12147. if (this.hasPlugin(["pipelineOperator", {
  12148. proposal: "smart"
  12149. }])) {
  12150. if (left.type === "SequenceExpression") {
  12151. this.raise(Errors.PipelineHeadSequenceExpression, {
  12152. at: leftStartLoc
  12153. });
  12154. }
  12155. }
  12156. }
  12157. parseSmartPipelineBodyInStyle(childExpr, startLoc) {
  12158. if (this.isSimpleReference(childExpr)) {
  12159. const bodyNode = this.startNodeAt(startLoc);
  12160. bodyNode.callee = childExpr;
  12161. return this.finishNode(bodyNode, "PipelineBareFunction");
  12162. } else {
  12163. const bodyNode = this.startNodeAt(startLoc);
  12164. this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
  12165. bodyNode.expression = childExpr;
  12166. return this.finishNode(bodyNode, "PipelineTopicExpression");
  12167. }
  12168. }
  12169. isSimpleReference(expression) {
  12170. switch (expression.type) {
  12171. case "MemberExpression":
  12172. return !expression.computed && this.isSimpleReference(expression.object);
  12173. case "Identifier":
  12174. return true;
  12175. default:
  12176. return false;
  12177. }
  12178. }
  12179. checkSmartPipeTopicBodyEarlyErrors(startLoc) {
  12180. if (this.match(19)) {
  12181. throw this.raise(Errors.PipelineBodyNoArrow, {
  12182. at: this.state.startLoc
  12183. });
  12184. }
  12185. if (!this.topicReferenceWasUsedInCurrentContext()) {
  12186. this.raise(Errors.PipelineTopicUnused, {
  12187. at: startLoc
  12188. });
  12189. }
  12190. }
  12191. withTopicBindingContext(callback) {
  12192. const outerContextTopicState = this.state.topicContext;
  12193. this.state.topicContext = {
  12194. maxNumOfResolvableTopics: 1,
  12195. maxTopicIndex: null
  12196. };
  12197. try {
  12198. return callback();
  12199. } finally {
  12200. this.state.topicContext = outerContextTopicState;
  12201. }
  12202. }
  12203. withSmartMixTopicForbiddingContext(callback) {
  12204. if (this.hasPlugin(["pipelineOperator", {
  12205. proposal: "smart"
  12206. }])) {
  12207. const outerContextTopicState = this.state.topicContext;
  12208. this.state.topicContext = {
  12209. maxNumOfResolvableTopics: 0,
  12210. maxTopicIndex: null
  12211. };
  12212. try {
  12213. return callback();
  12214. } finally {
  12215. this.state.topicContext = outerContextTopicState;
  12216. }
  12217. } else {
  12218. return callback();
  12219. }
  12220. }
  12221. withSoloAwaitPermittingContext(callback) {
  12222. const outerContextSoloAwaitState = this.state.soloAwait;
  12223. this.state.soloAwait = true;
  12224. try {
  12225. return callback();
  12226. } finally {
  12227. this.state.soloAwait = outerContextSoloAwaitState;
  12228. }
  12229. }
  12230. allowInAnd(callback) {
  12231. const flags = this.prodParam.currentFlags();
  12232. const prodParamToSet = PARAM_IN & ~flags;
  12233. if (prodParamToSet) {
  12234. this.prodParam.enter(flags | PARAM_IN);
  12235. try {
  12236. return callback();
  12237. } finally {
  12238. this.prodParam.exit();
  12239. }
  12240. }
  12241. return callback();
  12242. }
  12243. disallowInAnd(callback) {
  12244. const flags = this.prodParam.currentFlags();
  12245. const prodParamToClear = PARAM_IN & flags;
  12246. if (prodParamToClear) {
  12247. this.prodParam.enter(flags & ~PARAM_IN);
  12248. try {
  12249. return callback();
  12250. } finally {
  12251. this.prodParam.exit();
  12252. }
  12253. }
  12254. return callback();
  12255. }
  12256. registerTopicReference() {
  12257. this.state.topicContext.maxTopicIndex = 0;
  12258. }
  12259. topicReferenceIsAllowedInCurrentContext() {
  12260. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  12261. }
  12262. topicReferenceWasUsedInCurrentContext() {
  12263. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  12264. }
  12265. parseFSharpPipelineBody(prec) {
  12266. const startLoc = this.state.startLoc;
  12267. this.state.potentialArrowAt = this.state.start;
  12268. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  12269. this.state.inFSharpPipelineDirectBody = true;
  12270. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
  12271. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  12272. return ret;
  12273. }
  12274. parseModuleExpression() {
  12275. this.expectPlugin("moduleBlocks");
  12276. const node = this.startNode();
  12277. this.next();
  12278. if (!this.match(5)) {
  12279. this.unexpected(null, 5);
  12280. }
  12281. const program = this.startNodeAt(this.state.endLoc);
  12282. this.next();
  12283. const revertScopes = this.initializeScopes(true);
  12284. this.enterInitialScopes();
  12285. try {
  12286. node.body = this.parseProgram(program, 8, "module");
  12287. } finally {
  12288. revertScopes();
  12289. }
  12290. return this.finishNode(node, "ModuleExpression");
  12291. }
  12292. parsePropertyNamePrefixOperator(
  12293. prop) {}
  12294. }
  12295. const loopLabel = {
  12296. kind: "loop"
  12297. },
  12298. switchLabel = {
  12299. kind: "switch"
  12300. };
  12301. var ParseFunctionFlag = {
  12302. Expression: 0,
  12303. Declaration: 1,
  12304. HangingDeclaration: 2,
  12305. NullableId: 4,
  12306. Async: 8
  12307. };
  12308. var ParseStatementFlag = {
  12309. StatementOnly: 0,
  12310. AllowImportExport: 1,
  12311. AllowDeclaration: 2,
  12312. AllowFunctionDeclaration: 4,
  12313. AllowLabeledFunction: 8
  12314. };
  12315. const loneSurrogate = /[\uD800-\uDFFF]/u;
  12316. const keywordRelationalOperator = /in(?:stanceof)?/y;
  12317. function babel7CompatTokens(tokens, input) {
  12318. for (let i = 0; i < tokens.length; i++) {
  12319. const token = tokens[i];
  12320. const {
  12321. type
  12322. } = token;
  12323. if (typeof type === "number") {
  12324. {
  12325. if (type === 136) {
  12326. const {
  12327. loc,
  12328. start,
  12329. value,
  12330. end
  12331. } = token;
  12332. const hashEndPos = start + 1;
  12333. const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
  12334. tokens.splice(i, 1, new Token({
  12335. type: getExportedToken(27),
  12336. value: "#",
  12337. start: start,
  12338. end: hashEndPos,
  12339. startLoc: loc.start,
  12340. endLoc: hashEndLoc
  12341. }), new Token({
  12342. type: getExportedToken(130),
  12343. value: value,
  12344. start: hashEndPos,
  12345. end: end,
  12346. startLoc: hashEndLoc,
  12347. endLoc: loc.end
  12348. }));
  12349. i++;
  12350. continue;
  12351. }
  12352. if (tokenIsTemplate(type)) {
  12353. const {
  12354. loc,
  12355. start,
  12356. value,
  12357. end
  12358. } = token;
  12359. const backquoteEnd = start + 1;
  12360. const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
  12361. let startToken;
  12362. if (input.charCodeAt(start) === 96) {
  12363. startToken = new Token({
  12364. type: getExportedToken(22),
  12365. value: "`",
  12366. start: start,
  12367. end: backquoteEnd,
  12368. startLoc: loc.start,
  12369. endLoc: backquoteEndLoc
  12370. });
  12371. } else {
  12372. startToken = new Token({
  12373. type: getExportedToken(8),
  12374. value: "}",
  12375. start: start,
  12376. end: backquoteEnd,
  12377. startLoc: loc.start,
  12378. endLoc: backquoteEndLoc
  12379. });
  12380. }
  12381. let templateValue, templateElementEnd, templateElementEndLoc, endToken;
  12382. if (type === 24) {
  12383. templateElementEnd = end - 1;
  12384. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
  12385. templateValue = value === null ? null : value.slice(1, -1);
  12386. endToken = new Token({
  12387. type: getExportedToken(22),
  12388. value: "`",
  12389. start: templateElementEnd,
  12390. end: end,
  12391. startLoc: templateElementEndLoc,
  12392. endLoc: loc.end
  12393. });
  12394. } else {
  12395. templateElementEnd = end - 2;
  12396. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
  12397. templateValue = value === null ? null : value.slice(1, -2);
  12398. endToken = new Token({
  12399. type: getExportedToken(23),
  12400. value: "${",
  12401. start: templateElementEnd,
  12402. end: end,
  12403. startLoc: templateElementEndLoc,
  12404. endLoc: loc.end
  12405. });
  12406. }
  12407. tokens.splice(i, 1, startToken, new Token({
  12408. type: getExportedToken(20),
  12409. value: templateValue,
  12410. start: backquoteEnd,
  12411. end: templateElementEnd,
  12412. startLoc: backquoteEndLoc,
  12413. endLoc: templateElementEndLoc
  12414. }), endToken);
  12415. i += 2;
  12416. continue;
  12417. }
  12418. }
  12419. token.type = getExportedToken(type);
  12420. }
  12421. }
  12422. return tokens;
  12423. }
  12424. class StatementParser extends ExpressionParser {
  12425. parseTopLevel(file, program) {
  12426. file.program = this.parseProgram(program);
  12427. file.comments = this.state.comments;
  12428. if (this.options.tokens) {
  12429. file.tokens = babel7CompatTokens(this.tokens, this.input);
  12430. }
  12431. return this.finishNode(file, "File");
  12432. }
  12433. parseProgram(program, end = 137, sourceType = this.options.sourceType) {
  12434. program.sourceType = sourceType;
  12435. program.interpreter = this.parseInterpreterDirective();
  12436. this.parseBlockBody(program, true, true, end);
  12437. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  12438. for (const [localName, at] of Array.from(this.scope.undefinedExports)) {
  12439. this.raise(Errors.ModuleExportUndefined, {
  12440. at,
  12441. localName
  12442. });
  12443. }
  12444. }
  12445. let finishedProgram;
  12446. if (end === 137) {
  12447. finishedProgram = this.finishNode(program, "Program");
  12448. } else {
  12449. finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
  12450. }
  12451. return finishedProgram;
  12452. }
  12453. stmtToDirective(stmt) {
  12454. const directive = stmt;
  12455. directive.type = "Directive";
  12456. directive.value = directive.expression;
  12457. delete directive.expression;
  12458. const directiveLiteral = directive.value;
  12459. const expressionValue = directiveLiteral.value;
  12460. const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
  12461. const val = directiveLiteral.value = raw.slice(1, -1);
  12462. this.addExtra(directiveLiteral, "raw", raw);
  12463. this.addExtra(directiveLiteral, "rawValue", val);
  12464. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  12465. directiveLiteral.type = "DirectiveLiteral";
  12466. return directive;
  12467. }
  12468. parseInterpreterDirective() {
  12469. if (!this.match(28)) {
  12470. return null;
  12471. }
  12472. const node = this.startNode();
  12473. node.value = this.state.value;
  12474. this.next();
  12475. return this.finishNode(node, "InterpreterDirective");
  12476. }
  12477. isLet() {
  12478. if (!this.isContextual(99)) {
  12479. return false;
  12480. }
  12481. return this.hasFollowingBindingAtom();
  12482. }
  12483. chStartsBindingIdentifier(ch, pos) {
  12484. if (isIdentifierStart(ch)) {
  12485. keywordRelationalOperator.lastIndex = pos;
  12486. if (keywordRelationalOperator.test(this.input)) {
  12487. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  12488. if (!isIdentifierChar(endCh) && endCh !== 92) {
  12489. return false;
  12490. }
  12491. }
  12492. return true;
  12493. } else if (ch === 92) {
  12494. return true;
  12495. } else {
  12496. return false;
  12497. }
  12498. }
  12499. chStartsBindingPattern(ch) {
  12500. return ch === 91 || ch === 123;
  12501. }
  12502. hasFollowingBindingAtom() {
  12503. const next = this.nextTokenStart();
  12504. const nextCh = this.codePointAtPos(next);
  12505. return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  12506. }
  12507. hasFollowingBindingIdentifier() {
  12508. const next = this.nextTokenStart();
  12509. const nextCh = this.codePointAtPos(next);
  12510. return this.chStartsBindingIdentifier(nextCh, next);
  12511. }
  12512. startsUsingForOf() {
  12513. const lookahead = this.lookahead();
  12514. if (lookahead.type === 101 && !lookahead.containsEsc) {
  12515. return false;
  12516. } else {
  12517. this.expectPlugin("explicitResourceManagement");
  12518. return true;
  12519. }
  12520. }
  12521. parseModuleItem() {
  12522. return this.parseStatementLike(ParseStatementFlag.AllowImportExport | ParseStatementFlag.AllowDeclaration | ParseStatementFlag.AllowFunctionDeclaration | ParseStatementFlag.AllowLabeledFunction);
  12523. }
  12524. parseStatementListItem() {
  12525. return this.parseStatementLike(ParseStatementFlag.AllowDeclaration | ParseStatementFlag.AllowFunctionDeclaration | ParseStatementFlag.AllowLabeledFunction);
  12526. }
  12527. parseStatementOrFunctionDeclaration(disallowLabeledFunction) {
  12528. return this.parseStatementLike(ParseStatementFlag.AllowFunctionDeclaration | (disallowLabeledFunction ? 0 : ParseStatementFlag.AllowLabeledFunction));
  12529. }
  12530. parseStatement() {
  12531. return this.parseStatementLike(ParseStatementFlag.StatementOnly);
  12532. }
  12533. parseStatementLike(flags) {
  12534. let decorators = null;
  12535. if (this.match(26)) {
  12536. decorators = this.parseDecorators(true);
  12537. }
  12538. return this.parseStatementContent(flags, decorators);
  12539. }
  12540. parseStatementContent(flags, decorators) {
  12541. const starttype = this.state.type;
  12542. const node = this.startNode();
  12543. const allowDeclaration = !!(flags & ParseStatementFlag.AllowDeclaration);
  12544. const allowFunctionDeclaration = !!(flags & ParseStatementFlag.AllowFunctionDeclaration);
  12545. const topLevel = flags & ParseStatementFlag.AllowImportExport;
  12546. switch (starttype) {
  12547. case 60:
  12548. return this.parseBreakContinueStatement(node, true);
  12549. case 63:
  12550. return this.parseBreakContinueStatement(node, false);
  12551. case 64:
  12552. return this.parseDebuggerStatement(node);
  12553. case 90:
  12554. return this.parseDoWhileStatement(node);
  12555. case 91:
  12556. return this.parseForStatement(node);
  12557. case 68:
  12558. if (this.lookaheadCharCode() === 46) break;
  12559. if (!allowDeclaration) {
  12560. if (this.state.strict) {
  12561. this.raise(Errors.StrictFunction, {
  12562. at: this.state.startLoc
  12563. });
  12564. } else if (!allowFunctionDeclaration) {
  12565. this.raise(Errors.SloppyFunction, {
  12566. at: this.state.startLoc
  12567. });
  12568. }
  12569. }
  12570. return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration);
  12571. case 80:
  12572. if (!allowDeclaration) this.unexpected();
  12573. return this.parseClass(this.maybeTakeDecorators(decorators, node), true);
  12574. case 69:
  12575. return this.parseIfStatement(node);
  12576. case 70:
  12577. return this.parseReturnStatement(node);
  12578. case 71:
  12579. return this.parseSwitchStatement(node);
  12580. case 72:
  12581. return this.parseThrowStatement(node);
  12582. case 73:
  12583. return this.parseTryStatement(node);
  12584. case 105:
  12585. if (this.hasFollowingLineBreak() || this.state.containsEsc || !this.hasFollowingBindingIdentifier()) {
  12586. break;
  12587. }
  12588. this.expectPlugin("explicitResourceManagement");
  12589. if (!this.scope.inModule && this.scope.inTopLevel) {
  12590. this.raise(Errors.UnexpectedUsingDeclaration, {
  12591. at: this.state.startLoc
  12592. });
  12593. } else if (!allowDeclaration) {
  12594. this.raise(Errors.UnexpectedLexicalDeclaration, {
  12595. at: this.state.startLoc
  12596. });
  12597. }
  12598. return this.parseVarStatement(node, "using");
  12599. case 99:
  12600. {
  12601. if (this.state.containsEsc) {
  12602. break;
  12603. }
  12604. const next = this.nextTokenStart();
  12605. const nextCh = this.codePointAtPos(next);
  12606. if (nextCh !== 91) {
  12607. if (!allowDeclaration && this.hasFollowingLineBreak()) break;
  12608. if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
  12609. break;
  12610. }
  12611. }
  12612. }
  12613. case 75:
  12614. {
  12615. if (!allowDeclaration) {
  12616. this.raise(Errors.UnexpectedLexicalDeclaration, {
  12617. at: this.state.startLoc
  12618. });
  12619. }
  12620. }
  12621. case 74:
  12622. {
  12623. const kind = this.state.value;
  12624. return this.parseVarStatement(node, kind);
  12625. }
  12626. case 92:
  12627. return this.parseWhileStatement(node);
  12628. case 76:
  12629. return this.parseWithStatement(node);
  12630. case 5:
  12631. return this.parseBlock();
  12632. case 13:
  12633. return this.parseEmptyStatement(node);
  12634. case 83:
  12635. {
  12636. const nextTokenCharCode = this.lookaheadCharCode();
  12637. if (nextTokenCharCode === 40 ||
  12638. nextTokenCharCode === 46) {
  12639. break;
  12640. }
  12641. }
  12642. case 82:
  12643. {
  12644. if (!this.options.allowImportExportEverywhere && !topLevel) {
  12645. this.raise(Errors.UnexpectedImportExport, {
  12646. at: this.state.startLoc
  12647. });
  12648. }
  12649. this.next();
  12650. let result;
  12651. if (starttype === 83) {
  12652. result = this.parseImport(node);
  12653. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  12654. this.sawUnambiguousESM = true;
  12655. }
  12656. } else {
  12657. result = this.parseExport(node, decorators);
  12658. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  12659. this.sawUnambiguousESM = true;
  12660. }
  12661. }
  12662. this.assertModuleNodeAllowed(result);
  12663. return result;
  12664. }
  12665. default:
  12666. {
  12667. if (this.isAsyncFunction()) {
  12668. if (!allowDeclaration) {
  12669. this.raise(Errors.AsyncFunctionInSingleStatementContext, {
  12670. at: this.state.startLoc
  12671. });
  12672. }
  12673. this.next();
  12674. return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration);
  12675. }
  12676. }
  12677. }
  12678. const maybeName = this.state.value;
  12679. const expr = this.parseExpression();
  12680. if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) {
  12681. return this.parseLabeledStatement(node, maybeName,
  12682. expr, flags);
  12683. } else {
  12684. return this.parseExpressionStatement(node, expr, decorators);
  12685. }
  12686. }
  12687. assertModuleNodeAllowed(node) {
  12688. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  12689. this.raise(Errors.ImportOutsideModule, {
  12690. at: node
  12691. });
  12692. }
  12693. }
  12694. decoratorsEnabledBeforeExport() {
  12695. if (this.hasPlugin("decorators-legacy")) return true;
  12696. return this.hasPlugin("decorators") && !!this.getPluginOption("decorators", "decoratorsBeforeExport");
  12697. }
  12698. maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
  12699. if (maybeDecorators) {
  12700. classNode.decorators = maybeDecorators;
  12701. this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
  12702. if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);
  12703. }
  12704. return classNode;
  12705. }
  12706. canHaveLeadingDecorator() {
  12707. return this.match(80);
  12708. }
  12709. parseDecorators(allowExport) {
  12710. const decorators = [];
  12711. do {
  12712. decorators.push(this.parseDecorator());
  12713. } while (this.match(26));
  12714. if (this.match(82)) {
  12715. if (!allowExport) {
  12716. this.unexpected();
  12717. }
  12718. if (!this.decoratorsEnabledBeforeExport()) {
  12719. this.raise(Errors.DecoratorExportClass, {
  12720. at: this.state.startLoc
  12721. });
  12722. }
  12723. } else if (!this.canHaveLeadingDecorator()) {
  12724. throw this.raise(Errors.UnexpectedLeadingDecorator, {
  12725. at: this.state.startLoc
  12726. });
  12727. }
  12728. return decorators;
  12729. }
  12730. parseDecorator() {
  12731. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12732. const node = this.startNode();
  12733. this.next();
  12734. if (this.hasPlugin("decorators")) {
  12735. const startLoc = this.state.startLoc;
  12736. let expr;
  12737. if (this.match(10)) {
  12738. const startLoc = this.state.startLoc;
  12739. this.next();
  12740. expr = this.parseExpression();
  12741. this.expect(11);
  12742. expr = this.wrapParenthesis(startLoc, expr);
  12743. const paramsStartLoc = this.state.startLoc;
  12744. node.expression = this.parseMaybeDecoratorArguments(expr);
  12745. if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) {
  12746. this.raise(Errors.DecoratorArgumentsOutsideParentheses, {
  12747. at: paramsStartLoc
  12748. });
  12749. }
  12750. } else {
  12751. expr = this.parseIdentifier(false);
  12752. while (this.eat(16)) {
  12753. const node = this.startNodeAt(startLoc);
  12754. node.object = expr;
  12755. if (this.match(136)) {
  12756. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  12757. node.property = this.parsePrivateName();
  12758. } else {
  12759. node.property = this.parseIdentifier(true);
  12760. }
  12761. node.computed = false;
  12762. expr = this.finishNode(node, "MemberExpression");
  12763. }
  12764. node.expression = this.parseMaybeDecoratorArguments(expr);
  12765. }
  12766. } else {
  12767. node.expression = this.parseExprSubscripts();
  12768. }
  12769. return this.finishNode(node, "Decorator");
  12770. }
  12771. parseMaybeDecoratorArguments(expr) {
  12772. if (this.eat(10)) {
  12773. const node = this.startNodeAtNode(expr);
  12774. node.callee = expr;
  12775. node.arguments = this.parseCallExpressionArguments(11, false);
  12776. this.toReferencedList(node.arguments);
  12777. return this.finishNode(node, "CallExpression");
  12778. }
  12779. return expr;
  12780. }
  12781. parseBreakContinueStatement(node, isBreak) {
  12782. this.next();
  12783. if (this.isLineTerminator()) {
  12784. node.label = null;
  12785. } else {
  12786. node.label = this.parseIdentifier();
  12787. this.semicolon();
  12788. }
  12789. this.verifyBreakContinue(node, isBreak);
  12790. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  12791. }
  12792. verifyBreakContinue(node, isBreak) {
  12793. let i;
  12794. for (i = 0; i < this.state.labels.length; ++i) {
  12795. const lab = this.state.labels[i];
  12796. if (node.label == null || lab.name === node.label.name) {
  12797. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  12798. if (node.label && isBreak) break;
  12799. }
  12800. }
  12801. if (i === this.state.labels.length) {
  12802. const type = isBreak ? "BreakStatement" : "ContinueStatement";
  12803. this.raise(Errors.IllegalBreakContinue, {
  12804. at: node,
  12805. type
  12806. });
  12807. }
  12808. }
  12809. parseDebuggerStatement(node) {
  12810. this.next();
  12811. this.semicolon();
  12812. return this.finishNode(node, "DebuggerStatement");
  12813. }
  12814. parseHeaderExpression() {
  12815. this.expect(10);
  12816. const val = this.parseExpression();
  12817. this.expect(11);
  12818. return val;
  12819. }
  12820. parseDoWhileStatement(node) {
  12821. this.next();
  12822. this.state.labels.push(loopLabel);
  12823. node.body =
  12824. this.withSmartMixTopicForbiddingContext(() =>
  12825. this.parseStatement());
  12826. this.state.labels.pop();
  12827. this.expect(92);
  12828. node.test = this.parseHeaderExpression();
  12829. this.eat(13);
  12830. return this.finishNode(node, "DoWhileStatement");
  12831. }
  12832. parseForStatement(node) {
  12833. this.next();
  12834. this.state.labels.push(loopLabel);
  12835. let awaitAt = null;
  12836. if (this.isAwaitAllowed() && this.eatContextual(96)) {
  12837. awaitAt = this.state.lastTokStartLoc;
  12838. }
  12839. this.scope.enter(SCOPE_OTHER);
  12840. this.expect(10);
  12841. if (this.match(13)) {
  12842. if (awaitAt !== null) {
  12843. this.unexpected(awaitAt);
  12844. }
  12845. return this.parseFor(node, null);
  12846. }
  12847. const startsWithLet = this.isContextual(99);
  12848. const startsWithUsing = this.isContextual(105) && !this.hasFollowingLineBreak();
  12849. const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || startsWithUsing && this.hasFollowingBindingIdentifier() && this.startsUsingForOf();
  12850. if (this.match(74) || this.match(75) || isLetOrUsing) {
  12851. const initNode = this.startNode();
  12852. const kind = this.state.value;
  12853. this.next();
  12854. this.parseVar(initNode, true, kind);
  12855. const init = this.finishNode(initNode, "VariableDeclaration");
  12856. const isForIn = this.match(58);
  12857. if (isForIn && startsWithUsing) {
  12858. this.raise(Errors.ForInUsing, {
  12859. at: init
  12860. });
  12861. }
  12862. if ((isForIn || this.isContextual(101)) && init.declarations.length === 1) {
  12863. return this.parseForIn(node, init, awaitAt);
  12864. }
  12865. if (awaitAt !== null) {
  12866. this.unexpected(awaitAt);
  12867. }
  12868. return this.parseFor(node, init);
  12869. }
  12870. const startsWithAsync = this.isContextual(95);
  12871. const refExpressionErrors = new ExpressionErrors();
  12872. const init = this.parseExpression(true, refExpressionErrors);
  12873. const isForOf = this.isContextual(101);
  12874. if (isForOf) {
  12875. if (startsWithLet) {
  12876. this.raise(Errors.ForOfLet, {
  12877. at: init
  12878. });
  12879. }
  12880. if (
  12881. awaitAt === null && startsWithAsync && init.type === "Identifier") {
  12882. this.raise(Errors.ForOfAsync, {
  12883. at: init
  12884. });
  12885. }
  12886. }
  12887. if (isForOf || this.match(58)) {
  12888. this.checkDestructuringPrivate(refExpressionErrors);
  12889. this.toAssignable(init, true);
  12890. const type = isForOf ? "ForOfStatement" : "ForInStatement";
  12891. this.checkLVal(init, {
  12892. in: {
  12893. type
  12894. }
  12895. });
  12896. return this.parseForIn(node,
  12897. init, awaitAt);
  12898. } else {
  12899. this.checkExpressionErrors(refExpressionErrors, true);
  12900. }
  12901. if (awaitAt !== null) {
  12902. this.unexpected(awaitAt);
  12903. }
  12904. return this.parseFor(node, init);
  12905. }
  12906. parseFunctionStatement(node, isAsync, isHangingDeclaration) {
  12907. this.next();
  12908. return this.parseFunction(node, ParseFunctionFlag.Declaration | (isHangingDeclaration ? ParseFunctionFlag.HangingDeclaration : 0) | (isAsync ? ParseFunctionFlag.Async : 0));
  12909. }
  12910. parseIfStatement(node) {
  12911. this.next();
  12912. node.test = this.parseHeaderExpression();
  12913. node.consequent = this.parseStatementOrFunctionDeclaration(
  12914. true);
  12915. node.alternate = this.eat(66) ? this.parseStatementOrFunctionDeclaration(true) : null;
  12916. return this.finishNode(node, "IfStatement");
  12917. }
  12918. parseReturnStatement(node) {
  12919. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  12920. this.raise(Errors.IllegalReturn, {
  12921. at: this.state.startLoc
  12922. });
  12923. }
  12924. this.next();
  12925. if (this.isLineTerminator()) {
  12926. node.argument = null;
  12927. } else {
  12928. node.argument = this.parseExpression();
  12929. this.semicolon();
  12930. }
  12931. return this.finishNode(node, "ReturnStatement");
  12932. }
  12933. parseSwitchStatement(node) {
  12934. this.next();
  12935. node.discriminant = this.parseHeaderExpression();
  12936. const cases = node.cases = [];
  12937. this.expect(5);
  12938. this.state.labels.push(switchLabel);
  12939. this.scope.enter(SCOPE_OTHER);
  12940. let cur;
  12941. for (let sawDefault; !this.match(8);) {
  12942. if (this.match(61) || this.match(65)) {
  12943. const isCase = this.match(61);
  12944. if (cur) this.finishNode(cur, "SwitchCase");
  12945. cases.push(cur = this.startNode());
  12946. cur.consequent = [];
  12947. this.next();
  12948. if (isCase) {
  12949. cur.test = this.parseExpression();
  12950. } else {
  12951. if (sawDefault) {
  12952. this.raise(Errors.MultipleDefaultsInSwitch, {
  12953. at: this.state.lastTokStartLoc
  12954. });
  12955. }
  12956. sawDefault = true;
  12957. cur.test = null;
  12958. }
  12959. this.expect(14);
  12960. } else {
  12961. if (cur) {
  12962. cur.consequent.push(this.parseStatementListItem());
  12963. } else {
  12964. this.unexpected();
  12965. }
  12966. }
  12967. }
  12968. this.scope.exit();
  12969. if (cur) this.finishNode(cur, "SwitchCase");
  12970. this.next();
  12971. this.state.labels.pop();
  12972. return this.finishNode(node, "SwitchStatement");
  12973. }
  12974. parseThrowStatement(node) {
  12975. this.next();
  12976. if (this.hasPrecedingLineBreak()) {
  12977. this.raise(Errors.NewlineAfterThrow, {
  12978. at: this.state.lastTokEndLoc
  12979. });
  12980. }
  12981. node.argument = this.parseExpression();
  12982. this.semicolon();
  12983. return this.finishNode(node, "ThrowStatement");
  12984. }
  12985. parseCatchClauseParam() {
  12986. const param = this.parseBindingAtom();
  12987. const simple = param.type === "Identifier";
  12988. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  12989. this.checkLVal(param, {
  12990. in: {
  12991. type: "CatchClause"
  12992. },
  12993. binding: BIND_LEXICAL,
  12994. allowingSloppyLetBinding: true
  12995. });
  12996. return param;
  12997. }
  12998. parseTryStatement(node) {
  12999. this.next();
  13000. node.block = this.parseBlock();
  13001. node.handler = null;
  13002. if (this.match(62)) {
  13003. const clause = this.startNode();
  13004. this.next();
  13005. if (this.match(10)) {
  13006. this.expect(10);
  13007. clause.param = this.parseCatchClauseParam();
  13008. this.expect(11);
  13009. } else {
  13010. clause.param = null;
  13011. this.scope.enter(SCOPE_OTHER);
  13012. }
  13013. clause.body =
  13014. this.withSmartMixTopicForbiddingContext(() =>
  13015. this.parseBlock(false, false));
  13016. this.scope.exit();
  13017. node.handler = this.finishNode(clause, "CatchClause");
  13018. }
  13019. node.finalizer = this.eat(67) ? this.parseBlock() : null;
  13020. if (!node.handler && !node.finalizer) {
  13021. this.raise(Errors.NoCatchOrFinally, {
  13022. at: node
  13023. });
  13024. }
  13025. return this.finishNode(node, "TryStatement");
  13026. }
  13027. parseVarStatement(node, kind, allowMissingInitializer = false) {
  13028. this.next();
  13029. this.parseVar(node, false, kind, allowMissingInitializer);
  13030. this.semicolon();
  13031. return this.finishNode(node, "VariableDeclaration");
  13032. }
  13033. parseWhileStatement(node) {
  13034. this.next();
  13035. node.test = this.parseHeaderExpression();
  13036. this.state.labels.push(loopLabel);
  13037. node.body =
  13038. this.withSmartMixTopicForbiddingContext(() =>
  13039. this.parseStatement());
  13040. this.state.labels.pop();
  13041. return this.finishNode(node, "WhileStatement");
  13042. }
  13043. parseWithStatement(node) {
  13044. if (this.state.strict) {
  13045. this.raise(Errors.StrictWith, {
  13046. at: this.state.startLoc
  13047. });
  13048. }
  13049. this.next();
  13050. node.object = this.parseHeaderExpression();
  13051. node.body =
  13052. this.withSmartMixTopicForbiddingContext(() =>
  13053. this.parseStatement());
  13054. return this.finishNode(node, "WithStatement");
  13055. }
  13056. parseEmptyStatement(node) {
  13057. this.next();
  13058. return this.finishNode(node, "EmptyStatement");
  13059. }
  13060. parseLabeledStatement(node, maybeName, expr, flags) {
  13061. for (const label of this.state.labels) {
  13062. if (label.name === maybeName) {
  13063. this.raise(Errors.LabelRedeclaration, {
  13064. at: expr,
  13065. labelName: maybeName
  13066. });
  13067. }
  13068. }
  13069. const kind = tokenIsLoop(this.state.type) ? "loop" : this.match(71) ? "switch" : null;
  13070. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  13071. const label = this.state.labels[i];
  13072. if (label.statementStart === node.start) {
  13073. label.statementStart = this.state.start;
  13074. label.kind = kind;
  13075. } else {
  13076. break;
  13077. }
  13078. }
  13079. this.state.labels.push({
  13080. name: maybeName,
  13081. kind: kind,
  13082. statementStart: this.state.start
  13083. });
  13084. node.body = flags & ParseStatementFlag.AllowLabeledFunction ? this.parseStatementOrFunctionDeclaration(false) : this.parseStatement();
  13085. this.state.labels.pop();
  13086. node.label = expr;
  13087. return this.finishNode(node, "LabeledStatement");
  13088. }
  13089. parseExpressionStatement(node, expr,
  13090. decorators) {
  13091. node.expression = expr;
  13092. this.semicolon();
  13093. return this.finishNode(node, "ExpressionStatement");
  13094. }
  13095. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  13096. const node = this.startNode();
  13097. if (allowDirectives) {
  13098. this.state.strictErrors.clear();
  13099. }
  13100. this.expect(5);
  13101. if (createNewLexicalScope) {
  13102. this.scope.enter(SCOPE_OTHER);
  13103. }
  13104. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  13105. if (createNewLexicalScope) {
  13106. this.scope.exit();
  13107. }
  13108. return this.finishNode(node, "BlockStatement");
  13109. }
  13110. isValidDirective(stmt) {
  13111. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  13112. }
  13113. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  13114. const body = node.body = [];
  13115. const directives = node.directives = [];
  13116. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  13117. }
  13118. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  13119. const oldStrict = this.state.strict;
  13120. let hasStrictModeDirective = false;
  13121. let parsedNonDirective = false;
  13122. while (!this.match(end)) {
  13123. const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
  13124. if (directives && !parsedNonDirective) {
  13125. if (this.isValidDirective(stmt)) {
  13126. const directive = this.stmtToDirective(stmt);
  13127. directives.push(directive);
  13128. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  13129. hasStrictModeDirective = true;
  13130. this.setStrict(true);
  13131. }
  13132. continue;
  13133. }
  13134. parsedNonDirective = true;
  13135. this.state.strictErrors.clear();
  13136. }
  13137. body.push(stmt);
  13138. }
  13139. if (afterBlockParse) {
  13140. afterBlockParse.call(this, hasStrictModeDirective);
  13141. }
  13142. if (!oldStrict) {
  13143. this.setStrict(false);
  13144. }
  13145. this.next();
  13146. }
  13147. parseFor(node, init) {
  13148. node.init = init;
  13149. this.semicolon(false);
  13150. node.test = this.match(13) ? null : this.parseExpression();
  13151. this.semicolon(false);
  13152. node.update = this.match(11) ? null : this.parseExpression();
  13153. this.expect(11);
  13154. node.body =
  13155. this.withSmartMixTopicForbiddingContext(() =>
  13156. this.parseStatement());
  13157. this.scope.exit();
  13158. this.state.labels.pop();
  13159. return this.finishNode(node, "ForStatement");
  13160. }
  13161. parseForIn(node, init, awaitAt) {
  13162. const isForIn = this.match(58);
  13163. this.next();
  13164. if (isForIn) {
  13165. if (awaitAt !== null) this.unexpected(awaitAt);
  13166. } else {
  13167. node.await = awaitAt !== null;
  13168. }
  13169. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  13170. this.raise(Errors.ForInOfLoopInitializer, {
  13171. at: init,
  13172. type: isForIn ? "ForInStatement" : "ForOfStatement"
  13173. });
  13174. }
  13175. if (init.type === "AssignmentPattern") {
  13176. this.raise(Errors.InvalidLhs, {
  13177. at: init,
  13178. ancestor: {
  13179. type: "ForStatement"
  13180. }
  13181. });
  13182. }
  13183. node.left = init;
  13184. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  13185. this.expect(11);
  13186. node.body =
  13187. this.withSmartMixTopicForbiddingContext(() =>
  13188. this.parseStatement());
  13189. this.scope.exit();
  13190. this.state.labels.pop();
  13191. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  13192. }
  13193. parseVar(node, isFor, kind, allowMissingInitializer = false) {
  13194. const declarations = node.declarations = [];
  13195. node.kind = kind;
  13196. for (;;) {
  13197. const decl = this.startNode();
  13198. this.parseVarId(decl, kind);
  13199. decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  13200. if (decl.init === null && !allowMissingInitializer) {
  13201. if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(101)))) {
  13202. this.raise(Errors.DeclarationMissingInitializer, {
  13203. at: this.state.lastTokEndLoc,
  13204. kind: "destructuring"
  13205. });
  13206. } else if (kind === "const" && !(this.match(58) || this.isContextual(101))) {
  13207. this.raise(Errors.DeclarationMissingInitializer, {
  13208. at: this.state.lastTokEndLoc,
  13209. kind: "const"
  13210. });
  13211. }
  13212. }
  13213. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  13214. if (!this.eat(12)) break;
  13215. }
  13216. return node;
  13217. }
  13218. parseVarId(decl, kind) {
  13219. const id = this.parseBindingAtom();
  13220. this.checkLVal(id, {
  13221. in: {
  13222. type: "VariableDeclarator"
  13223. },
  13224. binding: kind === "var" ? BIND_VAR : BIND_LEXICAL
  13225. });
  13226. decl.id = id;
  13227. }
  13228. parseAsyncFunctionExpression(node) {
  13229. return this.parseFunction(node, ParseFunctionFlag.Async);
  13230. }
  13231. parseFunction(node, flags = ParseFunctionFlag.Expression) {
  13232. const hangingDeclaration = flags & ParseFunctionFlag.HangingDeclaration;
  13233. const isDeclaration = !!(flags & ParseFunctionFlag.Declaration);
  13234. const requireId = isDeclaration && !(flags & ParseFunctionFlag.NullableId);
  13235. const isAsync = !!(flags & ParseFunctionFlag.Async);
  13236. this.initFunction(node, isAsync);
  13237. if (this.match(55)) {
  13238. if (hangingDeclaration) {
  13239. this.raise(Errors.GeneratorInSingleStatementContext, {
  13240. at: this.state.startLoc
  13241. });
  13242. }
  13243. this.next();
  13244. node.generator = true;
  13245. }
  13246. if (isDeclaration) {
  13247. node.id = this.parseFunctionId(requireId);
  13248. }
  13249. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  13250. this.state.maybeInArrowParameters = false;
  13251. this.scope.enter(SCOPE_FUNCTION);
  13252. this.prodParam.enter(functionFlags(isAsync, node.generator));
  13253. if (!isDeclaration) {
  13254. node.id = this.parseFunctionId();
  13255. }
  13256. this.parseFunctionParams(node, false);
  13257. this.withSmartMixTopicForbiddingContext(() => {
  13258. this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
  13259. });
  13260. this.prodParam.exit();
  13261. this.scope.exit();
  13262. if (isDeclaration && !hangingDeclaration) {
  13263. this.registerFunctionStatementId(node);
  13264. }
  13265. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  13266. return node;
  13267. }
  13268. parseFunctionId(requireId) {
  13269. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  13270. }
  13271. parseFunctionParams(node, allowModifiers) {
  13272. this.expect(10);
  13273. this.expressionScope.enter(newParameterDeclarationScope());
  13274. node.params = this.parseBindingList(11, 41, false, allowModifiers);
  13275. this.expressionScope.exit();
  13276. }
  13277. registerFunctionStatementId(node) {
  13278. if (!node.id) return;
  13279. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.loc.start);
  13280. }
  13281. parseClass(node, isStatement, optionalId) {
  13282. this.next();
  13283. const oldStrict = this.state.strict;
  13284. this.state.strict = true;
  13285. this.parseClassId(node, isStatement, optionalId);
  13286. this.parseClassSuper(node);
  13287. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  13288. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  13289. }
  13290. isClassProperty() {
  13291. return this.match(29) || this.match(13) || this.match(8);
  13292. }
  13293. isClassMethod() {
  13294. return this.match(10);
  13295. }
  13296. isNonstaticConstructor(method) {
  13297. return !method.computed && !method.static && (method.key.name === "constructor" ||
  13298. method.key.value === "constructor");
  13299. }
  13300. parseClassBody(hadSuperClass, oldStrict) {
  13301. this.classScope.enter();
  13302. const state = {
  13303. hadConstructor: false,
  13304. hadSuperClass
  13305. };
  13306. let decorators = [];
  13307. const classBody = this.startNode();
  13308. classBody.body = [];
  13309. this.expect(5);
  13310. this.withSmartMixTopicForbiddingContext(() => {
  13311. while (!this.match(8)) {
  13312. if (this.eat(13)) {
  13313. if (decorators.length > 0) {
  13314. throw this.raise(Errors.DecoratorSemicolon, {
  13315. at: this.state.lastTokEndLoc
  13316. });
  13317. }
  13318. continue;
  13319. }
  13320. if (this.match(26)) {
  13321. decorators.push(this.parseDecorator());
  13322. continue;
  13323. }
  13324. const member = this.startNode();
  13325. if (decorators.length) {
  13326. member.decorators = decorators;
  13327. this.resetStartLocationFromNode(member, decorators[0]);
  13328. decorators = [];
  13329. }
  13330. this.parseClassMember(classBody, member, state);
  13331. if (
  13332. member.kind === "constructor" &&
  13333. member.decorators &&
  13334. member.decorators.length > 0) {
  13335. this.raise(Errors.DecoratorConstructor, {
  13336. at: member
  13337. });
  13338. }
  13339. }
  13340. });
  13341. this.state.strict = oldStrict;
  13342. this.next();
  13343. if (decorators.length) {
  13344. throw this.raise(Errors.TrailingDecorator, {
  13345. at: this.state.startLoc
  13346. });
  13347. }
  13348. this.classScope.exit();
  13349. return this.finishNode(classBody, "ClassBody");
  13350. }
  13351. parseClassMemberFromModifier(classBody, member) {
  13352. const key = this.parseIdentifier(true);
  13353. if (this.isClassMethod()) {
  13354. const method = member;
  13355. method.kind = "method";
  13356. method.computed = false;
  13357. method.key = key;
  13358. method.static = false;
  13359. this.pushClassMethod(classBody, method, false, false, false, false);
  13360. return true;
  13361. } else if (this.isClassProperty()) {
  13362. const prop = member;
  13363. prop.computed = false;
  13364. prop.key = key;
  13365. prop.static = false;
  13366. classBody.body.push(this.parseClassProperty(prop));
  13367. return true;
  13368. }
  13369. this.resetPreviousNodeTrailingComments(key);
  13370. return false;
  13371. }
  13372. parseClassMember(classBody, member, state) {
  13373. const isStatic = this.isContextual(104);
  13374. if (isStatic) {
  13375. if (this.parseClassMemberFromModifier(classBody, member)) {
  13376. return;
  13377. }
  13378. if (this.eat(5)) {
  13379. this.parseClassStaticBlock(classBody, member);
  13380. return;
  13381. }
  13382. }
  13383. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  13384. }
  13385. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  13386. const publicMethod = member;
  13387. const privateMethod = member;
  13388. const publicProp = member;
  13389. const privateProp = member;
  13390. const accessorProp = member;
  13391. const method = publicMethod;
  13392. const publicMember = publicMethod;
  13393. member.static = isStatic;
  13394. this.parsePropertyNamePrefixOperator(member);
  13395. if (this.eat(55)) {
  13396. method.kind = "method";
  13397. const isPrivateName = this.match(136);
  13398. this.parseClassElementName(method);
  13399. if (isPrivateName) {
  13400. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  13401. return;
  13402. }
  13403. if (this.isNonstaticConstructor(publicMethod)) {
  13404. this.raise(Errors.ConstructorIsGenerator, {
  13405. at: publicMethod.key
  13406. });
  13407. }
  13408. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  13409. return;
  13410. }
  13411. const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc;
  13412. const isPrivate = this.match(136);
  13413. const key = this.parseClassElementName(member);
  13414. const maybeQuestionTokenStartLoc = this.state.startLoc;
  13415. this.parsePostMemberNameModifiers(publicMember);
  13416. if (this.isClassMethod()) {
  13417. method.kind = "method";
  13418. if (isPrivate) {
  13419. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13420. return;
  13421. }
  13422. const isConstructor = this.isNonstaticConstructor(publicMethod);
  13423. let allowsDirectSuper = false;
  13424. if (isConstructor) {
  13425. publicMethod.kind = "constructor";
  13426. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  13427. this.raise(Errors.DuplicateConstructor, {
  13428. at: key
  13429. });
  13430. }
  13431. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  13432. this.raise(Errors.OverrideOnConstructor, {
  13433. at: key
  13434. });
  13435. }
  13436. state.hadConstructor = true;
  13437. allowsDirectSuper = state.hadSuperClass;
  13438. }
  13439. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  13440. } else if (this.isClassProperty()) {
  13441. if (isPrivate) {
  13442. this.pushClassPrivateProperty(classBody, privateProp);
  13443. } else {
  13444. this.pushClassProperty(classBody, publicProp);
  13445. }
  13446. } else if (isContextual && key.name === "async" && !this.isLineTerminator()) {
  13447. this.resetPreviousNodeTrailingComments(key);
  13448. const isGenerator = this.eat(55);
  13449. if (publicMember.optional) {
  13450. this.unexpected(maybeQuestionTokenStartLoc);
  13451. }
  13452. method.kind = "method";
  13453. const isPrivate = this.match(136);
  13454. this.parseClassElementName(method);
  13455. this.parsePostMemberNameModifiers(publicMember);
  13456. if (isPrivate) {
  13457. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  13458. } else {
  13459. if (this.isNonstaticConstructor(publicMethod)) {
  13460. this.raise(Errors.ConstructorIsAsync, {
  13461. at: publicMethod.key
  13462. });
  13463. }
  13464. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  13465. }
  13466. } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(55) && this.isLineTerminator())) {
  13467. this.resetPreviousNodeTrailingComments(key);
  13468. method.kind = key.name;
  13469. const isPrivate = this.match(136);
  13470. this.parseClassElementName(publicMethod);
  13471. if (isPrivate) {
  13472. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13473. } else {
  13474. if (this.isNonstaticConstructor(publicMethod)) {
  13475. this.raise(Errors.ConstructorIsAccessor, {
  13476. at: publicMethod.key
  13477. });
  13478. }
  13479. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  13480. }
  13481. this.checkGetterSetterParams(publicMethod);
  13482. } else if (isContextual && key.name === "accessor" && !this.isLineTerminator()) {
  13483. this.expectPlugin("decoratorAutoAccessors");
  13484. this.resetPreviousNodeTrailingComments(key);
  13485. const isPrivate = this.match(136);
  13486. this.parseClassElementName(publicProp);
  13487. this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);
  13488. } else if (this.isLineTerminator()) {
  13489. if (isPrivate) {
  13490. this.pushClassPrivateProperty(classBody, privateProp);
  13491. } else {
  13492. this.pushClassProperty(classBody, publicProp);
  13493. }
  13494. } else {
  13495. this.unexpected();
  13496. }
  13497. }
  13498. parseClassElementName(member) {
  13499. const {
  13500. type,
  13501. value
  13502. } = this.state;
  13503. if ((type === 130 || type === 131) && member.static && value === "prototype") {
  13504. this.raise(Errors.StaticPrototype, {
  13505. at: this.state.startLoc
  13506. });
  13507. }
  13508. if (type === 136) {
  13509. if (value === "constructor") {
  13510. this.raise(Errors.ConstructorClassPrivateField, {
  13511. at: this.state.startLoc
  13512. });
  13513. }
  13514. const key = this.parsePrivateName();
  13515. member.key = key;
  13516. return key;
  13517. }
  13518. return this.parsePropertyName(member);
  13519. }
  13520. parseClassStaticBlock(classBody, member) {
  13521. var _member$decorators;
  13522. this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
  13523. const oldLabels = this.state.labels;
  13524. this.state.labels = [];
  13525. this.prodParam.enter(PARAM);
  13526. const body = member.body = [];
  13527. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  13528. this.prodParam.exit();
  13529. this.scope.exit();
  13530. this.state.labels = oldLabels;
  13531. classBody.body.push(this.finishNode(member, "StaticBlock"));
  13532. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  13533. this.raise(Errors.DecoratorStaticBlock, {
  13534. at: member
  13535. });
  13536. }
  13537. }
  13538. pushClassProperty(classBody, prop) {
  13539. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  13540. this.raise(Errors.ConstructorClassField, {
  13541. at: prop.key
  13542. });
  13543. }
  13544. classBody.body.push(this.parseClassProperty(prop));
  13545. }
  13546. pushClassPrivateProperty(classBody, prop) {
  13547. const node = this.parseClassPrivateProperty(prop);
  13548. classBody.body.push(node);
  13549. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.loc.start);
  13550. }
  13551. pushClassAccessorProperty(classBody, prop, isPrivate) {
  13552. if (!isPrivate && !prop.computed) {
  13553. const key = prop.key;
  13554. if (key.name === "constructor" || key.value === "constructor") {
  13555. this.raise(Errors.ConstructorClassField, {
  13556. at: key
  13557. });
  13558. }
  13559. }
  13560. const node = this.parseClassAccessorProperty(prop);
  13561. classBody.body.push(node);
  13562. if (isPrivate) {
  13563. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.loc.start);
  13564. }
  13565. }
  13566. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  13567. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  13568. }
  13569. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  13570. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  13571. classBody.body.push(node);
  13572. 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;
  13573. this.declareClassPrivateMethodInScope(node, kind);
  13574. }
  13575. declareClassPrivateMethodInScope(node, kind) {
  13576. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start);
  13577. }
  13578. parsePostMemberNameModifiers(
  13579. methodOrProp) {}
  13580. parseClassPrivateProperty(node) {
  13581. this.parseInitializer(node);
  13582. this.semicolon();
  13583. return this.finishNode(node, "ClassPrivateProperty");
  13584. }
  13585. parseClassProperty(node) {
  13586. this.parseInitializer(node);
  13587. this.semicolon();
  13588. return this.finishNode(node, "ClassProperty");
  13589. }
  13590. parseClassAccessorProperty(node) {
  13591. this.parseInitializer(node);
  13592. this.semicolon();
  13593. return this.finishNode(node, "ClassAccessorProperty");
  13594. }
  13595. parseInitializer(node) {
  13596. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  13597. this.expressionScope.enter(newExpressionScope());
  13598. this.prodParam.enter(PARAM);
  13599. node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
  13600. this.expressionScope.exit();
  13601. this.prodParam.exit();
  13602. this.scope.exit();
  13603. }
  13604. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  13605. if (tokenIsIdentifier(this.state.type)) {
  13606. node.id = this.parseIdentifier();
  13607. if (isStatement) {
  13608. this.declareNameFromIdentifier(node.id, bindingType);
  13609. }
  13610. } else {
  13611. if (optionalId || !isStatement) {
  13612. node.id = null;
  13613. } else {
  13614. throw this.raise(Errors.MissingClassName, {
  13615. at: this.state.startLoc
  13616. });
  13617. }
  13618. }
  13619. }
  13620. parseClassSuper(node) {
  13621. node.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  13622. }
  13623. parseExport(node, decorators) {
  13624. const hasDefault = this.maybeParseExportDefaultSpecifier(
  13625. node);
  13626. const parseAfterDefault = !hasDefault || this.eat(12);
  13627. const hasStar = parseAfterDefault && this.eatExportStar(
  13628. node);
  13629. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(
  13630. node);
  13631. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  13632. const isFromRequired = hasDefault || hasStar;
  13633. if (hasStar && !hasNamespace) {
  13634. if (hasDefault) this.unexpected();
  13635. if (decorators) {
  13636. throw this.raise(Errors.UnsupportedDecoratorExport, {
  13637. at: node
  13638. });
  13639. }
  13640. this.parseExportFrom(node, true);
  13641. return this.finishNode(node, "ExportAllDeclaration");
  13642. }
  13643. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(
  13644. node);
  13645. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  13646. throw this.unexpected(null, 5);
  13647. }
  13648. let hasDeclaration;
  13649. if (isFromRequired || hasSpecifiers) {
  13650. hasDeclaration = false;
  13651. if (decorators) {
  13652. throw this.raise(Errors.UnsupportedDecoratorExport, {
  13653. at: node
  13654. });
  13655. }
  13656. this.parseExportFrom(node, isFromRequired);
  13657. } else {
  13658. hasDeclaration = this.maybeParseExportDeclaration(node);
  13659. }
  13660. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  13661. var _node2$declaration;
  13662. const node2 = node;
  13663. this.checkExport(node2, true, false, !!node2.source);
  13664. if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
  13665. this.maybeTakeDecorators(decorators, node2.declaration, node2);
  13666. } else if (decorators) {
  13667. throw this.raise(Errors.UnsupportedDecoratorExport, {
  13668. at: node
  13669. });
  13670. }
  13671. return this.finishNode(node2, "ExportNamedDeclaration");
  13672. }
  13673. if (this.eat(65)) {
  13674. const node2 = node;
  13675. const decl = this.parseExportDefaultExpression();
  13676. node2.declaration = decl;
  13677. if (decl.type === "ClassDeclaration") {
  13678. this.maybeTakeDecorators(decorators, decl, node2);
  13679. } else if (decorators) {
  13680. throw this.raise(Errors.UnsupportedDecoratorExport, {
  13681. at: node
  13682. });
  13683. }
  13684. this.checkExport(node2, true, true);
  13685. return this.finishNode(node2, "ExportDefaultDeclaration");
  13686. }
  13687. throw this.unexpected(null, 5);
  13688. }
  13689. eatExportStar(node) {
  13690. return this.eat(55);
  13691. }
  13692. maybeParseExportDefaultSpecifier(node) {
  13693. if (this.isExportDefaultSpecifier()) {
  13694. this.expectPlugin("exportDefaultFrom");
  13695. const specifier = this.startNode();
  13696. specifier.exported = this.parseIdentifier(true);
  13697. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  13698. return true;
  13699. }
  13700. return false;
  13701. }
  13702. maybeParseExportNamespaceSpecifier(node) {
  13703. if (this.isContextual(93)) {
  13704. if (!node.specifiers) node.specifiers = [];
  13705. const specifier = this.startNodeAt(this.state.lastTokStartLoc);
  13706. this.next();
  13707. specifier.exported = this.parseModuleExportName();
  13708. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  13709. return true;
  13710. }
  13711. return false;
  13712. }
  13713. maybeParseExportNamedSpecifiers(node) {
  13714. if (this.match(5)) {
  13715. if (!node.specifiers) node.specifiers = [];
  13716. const isTypeExport = node.exportKind === "type";
  13717. node.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  13718. node.source = null;
  13719. node.declaration = null;
  13720. if (this.hasPlugin("importAssertions")) {
  13721. node.assertions = [];
  13722. }
  13723. return true;
  13724. }
  13725. return false;
  13726. }
  13727. maybeParseExportDeclaration(node) {
  13728. if (this.shouldParseExportDeclaration()) {
  13729. node.specifiers = [];
  13730. node.source = null;
  13731. if (this.hasPlugin("importAssertions")) {
  13732. node.assertions = [];
  13733. }
  13734. node.declaration = this.parseExportDeclaration(node);
  13735. return true;
  13736. }
  13737. return false;
  13738. }
  13739. isAsyncFunction() {
  13740. if (!this.isContextual(95)) return false;
  13741. const next = this.nextTokenStart();
  13742. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  13743. }
  13744. parseExportDefaultExpression() {
  13745. const expr = this.startNode();
  13746. if (this.match(68)) {
  13747. this.next();
  13748. return this.parseFunction(expr, ParseFunctionFlag.Declaration | ParseFunctionFlag.NullableId);
  13749. } else if (this.isAsyncFunction()) {
  13750. this.next();
  13751. this.next();
  13752. return this.parseFunction(expr, ParseFunctionFlag.Declaration | ParseFunctionFlag.NullableId | ParseFunctionFlag.Async);
  13753. }
  13754. if (this.match(80)) {
  13755. return this.parseClass(expr, true, true);
  13756. }
  13757. if (this.match(26)) {
  13758. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  13759. this.raise(Errors.DecoratorBeforeExport, {
  13760. at: this.state.startLoc
  13761. });
  13762. }
  13763. return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
  13764. }
  13765. if (this.match(75) || this.match(74) || this.isLet()) {
  13766. throw this.raise(Errors.UnsupportedDefaultExport, {
  13767. at: this.state.startLoc
  13768. });
  13769. }
  13770. const res = this.parseMaybeAssignAllowIn();
  13771. this.semicolon();
  13772. return res;
  13773. }
  13774. parseExportDeclaration(
  13775. node) {
  13776. if (this.match(80)) {
  13777. const node = this.parseClass(this.startNode(), true, false);
  13778. return node;
  13779. }
  13780. return this.parseStatementListItem();
  13781. }
  13782. isExportDefaultSpecifier() {
  13783. const {
  13784. type
  13785. } = this.state;
  13786. if (tokenIsIdentifier(type)) {
  13787. if (type === 95 && !this.state.containsEsc || type === 99) {
  13788. return false;
  13789. }
  13790. if ((type === 128 || type === 127) && !this.state.containsEsc) {
  13791. const {
  13792. type: nextType
  13793. } = this.lookahead();
  13794. if (tokenIsIdentifier(nextType) && nextType !== 97 || nextType === 5) {
  13795. this.expectOnePlugin(["flow", "typescript"]);
  13796. return false;
  13797. }
  13798. }
  13799. } else if (!this.match(65)) {
  13800. return false;
  13801. }
  13802. const next = this.nextTokenStart();
  13803. const hasFrom = this.isUnparsedContextual(next, "from");
  13804. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  13805. return true;
  13806. }
  13807. if (this.match(65) && hasFrom) {
  13808. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  13809. return nextAfterFrom === 34 || nextAfterFrom === 39;
  13810. }
  13811. return false;
  13812. }
  13813. parseExportFrom(node, expect) {
  13814. if (this.eatContextual(97)) {
  13815. node.source = this.parseImportSource();
  13816. this.checkExport(node);
  13817. const assertions = this.maybeParseImportAssertions();
  13818. if (assertions) {
  13819. node.assertions = assertions;
  13820. this.checkJSONModuleImport(node);
  13821. }
  13822. } else if (expect) {
  13823. this.unexpected();
  13824. }
  13825. this.semicolon();
  13826. }
  13827. shouldParseExportDeclaration() {
  13828. const {
  13829. type
  13830. } = this.state;
  13831. if (type === 26) {
  13832. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  13833. if (this.hasPlugin("decorators")) {
  13834. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  13835. throw this.raise(Errors.DecoratorBeforeExport, {
  13836. at: this.state.startLoc
  13837. });
  13838. }
  13839. return true;
  13840. }
  13841. }
  13842. return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  13843. }
  13844. checkExport(node, checkNames, isDefault, isFrom) {
  13845. if (checkNames) {
  13846. if (isDefault) {
  13847. this.checkDuplicateExports(node, "default");
  13848. if (this.hasPlugin("exportDefaultFrom")) {
  13849. var _declaration$extra;
  13850. const declaration = node.declaration;
  13851. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 &&
  13852. !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  13853. this.raise(Errors.ExportDefaultFromAsIdentifier, {
  13854. at: declaration
  13855. });
  13856. }
  13857. }
  13858. } else if (node.specifiers && node.specifiers.length) {
  13859. for (const specifier of node.specifiers) {
  13860. const {
  13861. exported
  13862. } = specifier;
  13863. const exportName = exported.type === "Identifier" ? exported.name : exported.value;
  13864. this.checkDuplicateExports(specifier, exportName);
  13865. if (!isFrom && specifier.local) {
  13866. const {
  13867. local
  13868. } = specifier;
  13869. if (local.type !== "Identifier") {
  13870. this.raise(Errors.ExportBindingIsString, {
  13871. at: specifier,
  13872. localName: local.value,
  13873. exportName
  13874. });
  13875. } else {
  13876. this.checkReservedWord(local.name, local.loc.start, true, false);
  13877. this.scope.checkLocalExport(local);
  13878. }
  13879. }
  13880. }
  13881. } else if (node.declaration) {
  13882. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  13883. const id = node.declaration.id;
  13884. if (!id) throw new Error("Assertion failure");
  13885. this.checkDuplicateExports(node, id.name);
  13886. } else if (node.declaration.type === "VariableDeclaration") {
  13887. for (const declaration of node.declaration.declarations) {
  13888. this.checkDeclaration(declaration.id);
  13889. }
  13890. }
  13891. }
  13892. }
  13893. }
  13894. checkDeclaration(node) {
  13895. if (node.type === "Identifier") {
  13896. this.checkDuplicateExports(node, node.name);
  13897. } else if (node.type === "ObjectPattern") {
  13898. for (const prop of node.properties) {
  13899. this.checkDeclaration(prop);
  13900. }
  13901. } else if (node.type === "ArrayPattern") {
  13902. for (const elem of node.elements) {
  13903. if (elem) {
  13904. this.checkDeclaration(elem);
  13905. }
  13906. }
  13907. } else if (node.type === "ObjectProperty") {
  13908. this.checkDeclaration(node.value);
  13909. } else if (node.type === "RestElement") {
  13910. this.checkDeclaration(node.argument);
  13911. } else if (node.type === "AssignmentPattern") {
  13912. this.checkDeclaration(node.left);
  13913. }
  13914. }
  13915. checkDuplicateExports(node, exportName) {
  13916. if (this.exportedIdentifiers.has(exportName)) {
  13917. if (exportName === "default") {
  13918. this.raise(Errors.DuplicateDefaultExport, {
  13919. at: node
  13920. });
  13921. } else {
  13922. this.raise(Errors.DuplicateExport, {
  13923. at: node,
  13924. exportName
  13925. });
  13926. }
  13927. }
  13928. this.exportedIdentifiers.add(exportName);
  13929. }
  13930. parseExportSpecifiers(isInTypeExport) {
  13931. const nodes = [];
  13932. let first = true;
  13933. this.expect(5);
  13934. while (!this.eat(8)) {
  13935. if (first) {
  13936. first = false;
  13937. } else {
  13938. this.expect(12);
  13939. if (this.eat(8)) break;
  13940. }
  13941. const isMaybeTypeOnly = this.isContextual(128);
  13942. const isString = this.match(131);
  13943. const node = this.startNode();
  13944. node.local = this.parseModuleExportName();
  13945. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  13946. }
  13947. return nodes;
  13948. }
  13949. parseExportSpecifier(node, isString,
  13950. isInTypeExport, isMaybeTypeOnly
  13951. ) {
  13952. if (this.eatContextual(93)) {
  13953. node.exported = this.parseModuleExportName();
  13954. } else if (isString) {
  13955. node.exported = cloneStringLiteral(node.local);
  13956. } else if (!node.exported) {
  13957. node.exported = cloneIdentifier(node.local);
  13958. }
  13959. return this.finishNode(node, "ExportSpecifier");
  13960. }
  13961. parseModuleExportName() {
  13962. if (this.match(131)) {
  13963. const result = this.parseStringLiteral(this.state.value);
  13964. const surrogate = result.value.match(loneSurrogate);
  13965. if (surrogate) {
  13966. this.raise(Errors.ModuleExportNameHasLoneSurrogate, {
  13967. at: result,
  13968. surrogateCharCode: surrogate[0].charCodeAt(0)
  13969. });
  13970. }
  13971. return result;
  13972. }
  13973. return this.parseIdentifier(true);
  13974. }
  13975. isJSONModuleImport(node) {
  13976. if (node.assertions != null) {
  13977. return node.assertions.some(({
  13978. key,
  13979. value
  13980. }) => {
  13981. return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
  13982. });
  13983. }
  13984. return false;
  13985. }
  13986. checkImportReflection(node) {
  13987. if (node.module) {
  13988. var _node$assertions;
  13989. if (node.specifiers.length !== 1 || node.specifiers[0].type !== "ImportDefaultSpecifier") {
  13990. this.raise(Errors.ImportReflectionNotBinding, {
  13991. at: node.specifiers[0].loc.start
  13992. });
  13993. }
  13994. if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) {
  13995. this.raise(Errors.ImportReflectionHasAssertion, {
  13996. at: node.specifiers[0].loc.start
  13997. });
  13998. }
  13999. }
  14000. }
  14001. checkJSONModuleImport(node) {
  14002. if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") {
  14003. const {
  14004. specifiers
  14005. } = node;
  14006. if (specifiers != null) {
  14007. const nonDefaultNamedSpecifier = specifiers.find(specifier => {
  14008. let imported;
  14009. if (specifier.type === "ExportSpecifier") {
  14010. imported = specifier.local;
  14011. } else if (specifier.type === "ImportSpecifier") {
  14012. imported = specifier.imported;
  14013. }
  14014. if (imported !== undefined) {
  14015. return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
  14016. }
  14017. });
  14018. if (nonDefaultNamedSpecifier !== undefined) {
  14019. this.raise(Errors.ImportJSONBindingNotDefault, {
  14020. at: nonDefaultNamedSpecifier.loc.start
  14021. });
  14022. }
  14023. }
  14024. }
  14025. }
  14026. parseMaybeImportReflection(node) {
  14027. let isImportReflection = false;
  14028. if (this.isContextual(125)) {
  14029. const lookahead = this.lookahead();
  14030. const nextType = lookahead.type;
  14031. if (tokenIsIdentifier(nextType)) {
  14032. if (nextType !== 97) {
  14033. isImportReflection = true;
  14034. } else {
  14035. const nextNextTokenFirstChar = this.input.charCodeAt(this.nextTokenStartSince(lookahead.end));
  14036. if (nextNextTokenFirstChar === 102) {
  14037. isImportReflection = true;
  14038. }
  14039. }
  14040. } else if (nextType !== 12) {
  14041. isImportReflection = true;
  14042. }
  14043. }
  14044. if (isImportReflection) {
  14045. this.expectPlugin("importReflection");
  14046. this.next();
  14047. node.module = true;
  14048. } else if (this.hasPlugin("importReflection")) {
  14049. node.module = false;
  14050. }
  14051. }
  14052. parseImport(node) {
  14053. node.specifiers = [];
  14054. if (!this.match(131)) {
  14055. this.parseMaybeImportReflection(node);
  14056. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  14057. const parseNext = !hasDefault || this.eat(12);
  14058. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  14059. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  14060. this.expectContextual(97);
  14061. }
  14062. node.source = this.parseImportSource();
  14063. const assertions = this.maybeParseImportAssertions();
  14064. if (assertions) {
  14065. node.assertions = assertions;
  14066. } else {
  14067. const attributes = this.maybeParseModuleAttributes();
  14068. if (attributes) {
  14069. node.attributes = attributes;
  14070. }
  14071. }
  14072. this.checkImportReflection(node);
  14073. this.checkJSONModuleImport(node);
  14074. this.semicolon();
  14075. return this.finishNode(node, "ImportDeclaration");
  14076. }
  14077. parseImportSource() {
  14078. if (!this.match(131)) this.unexpected();
  14079. return this.parseExprAtom();
  14080. }
  14081. shouldParseDefaultImport(node) {
  14082. return tokenIsIdentifier(this.state.type);
  14083. }
  14084. parseImportSpecifierLocal(node, specifier, type) {
  14085. specifier.local = this.parseIdentifier();
  14086. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  14087. }
  14088. finishImportSpecifier(specifier, type, bindingType = BIND_LEXICAL) {
  14089. this.checkLVal(specifier.local, {
  14090. in: specifier,
  14091. binding: bindingType
  14092. });
  14093. return this.finishNode(specifier, type);
  14094. }
  14095. parseAssertEntries() {
  14096. const attrs = [];
  14097. const attrNames = new Set();
  14098. do {
  14099. if (this.match(8)) {
  14100. break;
  14101. }
  14102. const node = this.startNode();
  14103. const keyName = this.state.value;
  14104. if (attrNames.has(keyName)) {
  14105. this.raise(Errors.ModuleAttributesWithDuplicateKeys, {
  14106. at: this.state.startLoc,
  14107. key: keyName
  14108. });
  14109. }
  14110. attrNames.add(keyName);
  14111. if (this.match(131)) {
  14112. node.key = this.parseStringLiteral(keyName);
  14113. } else {
  14114. node.key = this.parseIdentifier(true);
  14115. }
  14116. this.expect(14);
  14117. if (!this.match(131)) {
  14118. throw this.raise(Errors.ModuleAttributeInvalidValue, {
  14119. at: this.state.startLoc
  14120. });
  14121. }
  14122. node.value = this.parseStringLiteral(this.state.value);
  14123. attrs.push(this.finishNode(node, "ImportAttribute"));
  14124. } while (this.eat(12));
  14125. return attrs;
  14126. }
  14127. maybeParseModuleAttributes() {
  14128. if (this.match(76) && !this.hasPrecedingLineBreak()) {
  14129. this.expectPlugin("moduleAttributes");
  14130. this.next();
  14131. } else {
  14132. if (this.hasPlugin("moduleAttributes")) return [];
  14133. return null;
  14134. }
  14135. const attrs = [];
  14136. const attributes = new Set();
  14137. do {
  14138. const node = this.startNode();
  14139. node.key = this.parseIdentifier(true);
  14140. if (node.key.name !== "type") {
  14141. this.raise(Errors.ModuleAttributeDifferentFromType, {
  14142. at: node.key
  14143. });
  14144. }
  14145. if (attributes.has(node.key.name)) {
  14146. this.raise(Errors.ModuleAttributesWithDuplicateKeys, {
  14147. at: node.key,
  14148. key: node.key.name
  14149. });
  14150. }
  14151. attributes.add(node.key.name);
  14152. this.expect(14);
  14153. if (!this.match(131)) {
  14154. throw this.raise(Errors.ModuleAttributeInvalidValue, {
  14155. at: this.state.startLoc
  14156. });
  14157. }
  14158. node.value = this.parseStringLiteral(this.state.value);
  14159. this.finishNode(node, "ImportAttribute");
  14160. attrs.push(node);
  14161. } while (this.eat(12));
  14162. return attrs;
  14163. }
  14164. maybeParseImportAssertions() {
  14165. if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
  14166. this.expectPlugin("importAssertions");
  14167. this.next();
  14168. } else {
  14169. if (this.hasPlugin("importAssertions")) return [];
  14170. return null;
  14171. }
  14172. this.eat(5);
  14173. const attrs = this.parseAssertEntries();
  14174. this.eat(8);
  14175. return attrs;
  14176. }
  14177. maybeParseDefaultImportSpecifier(node) {
  14178. if (this.shouldParseDefaultImport(node)) {
  14179. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier");
  14180. return true;
  14181. }
  14182. return false;
  14183. }
  14184. maybeParseStarImportSpecifier(node) {
  14185. if (this.match(55)) {
  14186. const specifier = this.startNode();
  14187. this.next();
  14188. this.expectContextual(93);
  14189. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier");
  14190. return true;
  14191. }
  14192. return false;
  14193. }
  14194. parseNamedImportSpecifiers(node) {
  14195. let first = true;
  14196. this.expect(5);
  14197. while (!this.eat(8)) {
  14198. if (first) {
  14199. first = false;
  14200. } else {
  14201. if (this.eat(14)) {
  14202. throw this.raise(Errors.DestructureNamedImport, {
  14203. at: this.state.startLoc
  14204. });
  14205. }
  14206. this.expect(12);
  14207. if (this.eat(8)) break;
  14208. }
  14209. const specifier = this.startNode();
  14210. const importedIsString = this.match(131);
  14211. const isMaybeTypeOnly = this.isContextual(128);
  14212. specifier.imported = this.parseModuleExportName();
  14213. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined);
  14214. node.specifiers.push(importSpecifier);
  14215. }
  14216. }
  14217. parseImportSpecifier(specifier, importedIsString,
  14218. isInTypeOnlyImport, isMaybeTypeOnly, bindingType
  14219. ) {
  14220. if (this.eatContextual(93)) {
  14221. specifier.local = this.parseIdentifier();
  14222. } else {
  14223. const {
  14224. imported
  14225. } = specifier;
  14226. if (importedIsString) {
  14227. throw this.raise(Errors.ImportBindingIsString, {
  14228. at: specifier,
  14229. importName: imported.value
  14230. });
  14231. }
  14232. this.checkReservedWord(imported.name, specifier.loc.start, true, true);
  14233. if (!specifier.local) {
  14234. specifier.local = cloneIdentifier(imported);
  14235. }
  14236. }
  14237. return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  14238. }
  14239. isThisParam(param) {
  14240. return param.type === "Identifier" && param.name === "this";
  14241. }
  14242. }
  14243. class Parser extends StatementParser {
  14244. constructor(options, input) {
  14245. options = getOptions(options);
  14246. super(options, input);
  14247. this.options = options;
  14248. this.initializeScopes();
  14249. this.plugins = pluginsMap(this.options.plugins);
  14250. this.filename = options.sourceFilename;
  14251. }
  14252. getScopeHandler() {
  14253. return ScopeHandler;
  14254. }
  14255. parse() {
  14256. this.enterInitialScopes();
  14257. const file = this.startNode();
  14258. const program = this.startNode();
  14259. this.nextToken();
  14260. file.errors = null;
  14261. this.parseTopLevel(file, program);
  14262. file.errors = this.state.errors;
  14263. return file;
  14264. }
  14265. }
  14266. function pluginsMap(plugins) {
  14267. const pluginMap = new Map();
  14268. for (const plugin of plugins) {
  14269. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  14270. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  14271. }
  14272. return pluginMap;
  14273. }
  14274. function parse(input, options) {
  14275. var _options;
  14276. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  14277. options = Object.assign({}, options);
  14278. try {
  14279. options.sourceType = "module";
  14280. const parser = getParser(options, input);
  14281. const ast = parser.parse();
  14282. if (parser.sawUnambiguousESM) {
  14283. return ast;
  14284. }
  14285. if (parser.ambiguousScriptDifferentAst) {
  14286. try {
  14287. options.sourceType = "script";
  14288. return getParser(options, input).parse();
  14289. } catch (_unused) {}
  14290. } else {
  14291. ast.program.sourceType = "script";
  14292. }
  14293. return ast;
  14294. } catch (moduleError) {
  14295. try {
  14296. options.sourceType = "script";
  14297. return getParser(options, input).parse();
  14298. } catch (_unused2) {}
  14299. throw moduleError;
  14300. }
  14301. } else {
  14302. return getParser(options, input).parse();
  14303. }
  14304. }
  14305. function parseExpression(input, options) {
  14306. const parser = getParser(options, input);
  14307. if (parser.options.strictMode) {
  14308. parser.state.strict = true;
  14309. }
  14310. return parser.getExpression();
  14311. }
  14312. function generateExportedTokenTypes(internalTokenTypes) {
  14313. const tokenTypes = {};
  14314. for (const typeName of Object.keys(internalTokenTypes)) {
  14315. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  14316. }
  14317. return tokenTypes;
  14318. }
  14319. const tokTypes = generateExportedTokenTypes(tt);
  14320. function getParser(options, input) {
  14321. let cls = Parser;
  14322. if (options != null && options.plugins) {
  14323. validatePlugins(options.plugins);
  14324. cls = getParserClass(options.plugins);
  14325. }
  14326. return new cls(options, input);
  14327. }
  14328. const parserClassCache = {};
  14329. function getParserClass(pluginsFromOptions) {
  14330. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  14331. const key = pluginList.join("/");
  14332. let cls = parserClassCache[key];
  14333. if (!cls) {
  14334. cls = Parser;
  14335. for (const plugin of pluginList) {
  14336. cls = mixinPlugins[plugin](cls);
  14337. }
  14338. parserClassCache[key] = cls;
  14339. }
  14340. return cls;
  14341. }
  14342. exports.parse = parse;
  14343. exports.parseExpression = parseExpression;
  14344. exports.tokTypes = tokTypes;
  14345. //# sourceMappingURL=index.js.map