index.js 414 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const beforeExpr = true;
  4. const startsExpr = true;
  5. const isLoop = true;
  6. const isAssign = true;
  7. const prefix = true;
  8. const postfix = true;
  9. class TokenType {
  10. constructor(label, conf = {}) {
  11. this.label = void 0;
  12. this.keyword = void 0;
  13. this.beforeExpr = void 0;
  14. this.startsExpr = void 0;
  15. this.rightAssociative = void 0;
  16. this.isLoop = void 0;
  17. this.isAssign = void 0;
  18. this.prefix = void 0;
  19. this.postfix = void 0;
  20. this.binop = void 0;
  21. this.updateContext = void 0;
  22. this.label = label;
  23. this.keyword = conf.keyword;
  24. this.beforeExpr = !!conf.beforeExpr;
  25. this.startsExpr = !!conf.startsExpr;
  26. this.rightAssociative = !!conf.rightAssociative;
  27. this.isLoop = !!conf.isLoop;
  28. this.isAssign = !!conf.isAssign;
  29. this.prefix = !!conf.prefix;
  30. this.postfix = !!conf.postfix;
  31. this.binop = conf.binop != null ? conf.binop : null;
  32. this.updateContext = null;
  33. }
  34. }
  35. const keywords = new Map();
  36. function createKeyword(name, options = {}) {
  37. options.keyword = name;
  38. const token = new TokenType(name, options);
  39. keywords.set(name, token);
  40. return token;
  41. }
  42. function createBinop(name, binop) {
  43. return new TokenType(name, {
  44. beforeExpr,
  45. binop
  46. });
  47. }
  48. const types = {
  49. num: new TokenType("num", {
  50. startsExpr
  51. }),
  52. bigint: new TokenType("bigint", {
  53. startsExpr
  54. }),
  55. decimal: new TokenType("decimal", {
  56. startsExpr
  57. }),
  58. regexp: new TokenType("regexp", {
  59. startsExpr
  60. }),
  61. string: new TokenType("string", {
  62. startsExpr
  63. }),
  64. name: new TokenType("name", {
  65. startsExpr
  66. }),
  67. eof: new TokenType("eof"),
  68. bracketL: new TokenType("[", {
  69. beforeExpr,
  70. startsExpr
  71. }),
  72. bracketHashL: new TokenType("#[", {
  73. beforeExpr,
  74. startsExpr
  75. }),
  76. bracketBarL: new TokenType("[|", {
  77. beforeExpr,
  78. startsExpr
  79. }),
  80. bracketR: new TokenType("]"),
  81. bracketBarR: new TokenType("|]"),
  82. braceL: new TokenType("{", {
  83. beforeExpr,
  84. startsExpr
  85. }),
  86. braceBarL: new TokenType("{|", {
  87. beforeExpr,
  88. startsExpr
  89. }),
  90. braceHashL: new TokenType("#{", {
  91. beforeExpr,
  92. startsExpr
  93. }),
  94. braceR: new TokenType("}"),
  95. braceBarR: new TokenType("|}"),
  96. parenL: new TokenType("(", {
  97. beforeExpr,
  98. startsExpr
  99. }),
  100. parenR: new TokenType(")"),
  101. comma: new TokenType(",", {
  102. beforeExpr
  103. }),
  104. semi: new TokenType(";", {
  105. beforeExpr
  106. }),
  107. colon: new TokenType(":", {
  108. beforeExpr
  109. }),
  110. doubleColon: new TokenType("::", {
  111. beforeExpr
  112. }),
  113. dot: new TokenType("."),
  114. question: new TokenType("?", {
  115. beforeExpr
  116. }),
  117. questionDot: new TokenType("?."),
  118. arrow: new TokenType("=>", {
  119. beforeExpr
  120. }),
  121. template: new TokenType("template"),
  122. ellipsis: new TokenType("...", {
  123. beforeExpr
  124. }),
  125. backQuote: new TokenType("`", {
  126. startsExpr
  127. }),
  128. dollarBraceL: new TokenType("${", {
  129. beforeExpr,
  130. startsExpr
  131. }),
  132. at: new TokenType("@"),
  133. hash: new TokenType("#", {
  134. startsExpr
  135. }),
  136. interpreterDirective: new TokenType("#!..."),
  137. eq: new TokenType("=", {
  138. beforeExpr,
  139. isAssign
  140. }),
  141. assign: new TokenType("_=", {
  142. beforeExpr,
  143. isAssign
  144. }),
  145. incDec: new TokenType("++/--", {
  146. prefix,
  147. postfix,
  148. startsExpr
  149. }),
  150. bang: new TokenType("!", {
  151. beforeExpr,
  152. prefix,
  153. startsExpr
  154. }),
  155. tilde: new TokenType("~", {
  156. beforeExpr,
  157. prefix,
  158. startsExpr
  159. }),
  160. pipeline: createBinop("|>", 0),
  161. nullishCoalescing: createBinop("??", 1),
  162. logicalOR: createBinop("||", 1),
  163. logicalAND: createBinop("&&", 2),
  164. bitwiseOR: createBinop("|", 3),
  165. bitwiseXOR: createBinop("^", 4),
  166. bitwiseAND: createBinop("&", 5),
  167. equality: createBinop("==/!=/===/!==", 6),
  168. relational: createBinop("</>/<=/>=", 7),
  169. bitShift: createBinop("<</>>/>>>", 8),
  170. plusMin: new TokenType("+/-", {
  171. beforeExpr,
  172. binop: 9,
  173. prefix,
  174. startsExpr
  175. }),
  176. modulo: new TokenType("%", {
  177. beforeExpr,
  178. binop: 10,
  179. startsExpr
  180. }),
  181. star: new TokenType("*", {
  182. binop: 10
  183. }),
  184. slash: createBinop("/", 10),
  185. exponent: new TokenType("**", {
  186. beforeExpr,
  187. binop: 11,
  188. rightAssociative: true
  189. }),
  190. _break: createKeyword("break"),
  191. _case: createKeyword("case", {
  192. beforeExpr
  193. }),
  194. _catch: createKeyword("catch"),
  195. _continue: createKeyword("continue"),
  196. _debugger: createKeyword("debugger"),
  197. _default: createKeyword("default", {
  198. beforeExpr
  199. }),
  200. _do: createKeyword("do", {
  201. isLoop,
  202. beforeExpr
  203. }),
  204. _else: createKeyword("else", {
  205. beforeExpr
  206. }),
  207. _finally: createKeyword("finally"),
  208. _for: createKeyword("for", {
  209. isLoop
  210. }),
  211. _function: createKeyword("function", {
  212. startsExpr
  213. }),
  214. _if: createKeyword("if"),
  215. _return: createKeyword("return", {
  216. beforeExpr
  217. }),
  218. _switch: createKeyword("switch"),
  219. _throw: createKeyword("throw", {
  220. beforeExpr,
  221. prefix,
  222. startsExpr
  223. }),
  224. _try: createKeyword("try"),
  225. _var: createKeyword("var"),
  226. _const: createKeyword("const"),
  227. _while: createKeyword("while", {
  228. isLoop
  229. }),
  230. _with: createKeyword("with"),
  231. _new: createKeyword("new", {
  232. beforeExpr,
  233. startsExpr
  234. }),
  235. _this: createKeyword("this", {
  236. startsExpr
  237. }),
  238. _super: createKeyword("super", {
  239. startsExpr
  240. }),
  241. _class: createKeyword("class", {
  242. startsExpr
  243. }),
  244. _extends: createKeyword("extends", {
  245. beforeExpr
  246. }),
  247. _export: createKeyword("export"),
  248. _import: createKeyword("import", {
  249. startsExpr
  250. }),
  251. _null: createKeyword("null", {
  252. startsExpr
  253. }),
  254. _true: createKeyword("true", {
  255. startsExpr
  256. }),
  257. _false: createKeyword("false", {
  258. startsExpr
  259. }),
  260. _in: createKeyword("in", {
  261. beforeExpr,
  262. binop: 7
  263. }),
  264. _instanceof: createKeyword("instanceof", {
  265. beforeExpr,
  266. binop: 7
  267. }),
  268. _typeof: createKeyword("typeof", {
  269. beforeExpr,
  270. prefix,
  271. startsExpr
  272. }),
  273. _void: createKeyword("void", {
  274. beforeExpr,
  275. prefix,
  276. startsExpr
  277. }),
  278. _delete: createKeyword("delete", {
  279. beforeExpr,
  280. prefix,
  281. startsExpr
  282. })
  283. };
  284. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  285. const lineBreakG = new RegExp(lineBreak.source, "g");
  286. function isNewLine(code) {
  287. switch (code) {
  288. case 10:
  289. case 13:
  290. case 8232:
  291. case 8233:
  292. return true;
  293. default:
  294. return false;
  295. }
  296. }
  297. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  298. function isWhitespace(code) {
  299. switch (code) {
  300. case 0x0009:
  301. case 0x000b:
  302. case 0x000c:
  303. case 32:
  304. case 160:
  305. case 5760:
  306. case 0x2000:
  307. case 0x2001:
  308. case 0x2002:
  309. case 0x2003:
  310. case 0x2004:
  311. case 0x2005:
  312. case 0x2006:
  313. case 0x2007:
  314. case 0x2008:
  315. case 0x2009:
  316. case 0x200a:
  317. case 0x202f:
  318. case 0x205f:
  319. case 0x3000:
  320. case 0xfeff:
  321. return true;
  322. default:
  323. return false;
  324. }
  325. }
  326. class Position {
  327. constructor(line, col) {
  328. this.line = void 0;
  329. this.column = void 0;
  330. this.line = line;
  331. this.column = col;
  332. }
  333. }
  334. class SourceLocation {
  335. constructor(start, end) {
  336. this.start = void 0;
  337. this.end = void 0;
  338. this.filename = void 0;
  339. this.identifierName = void 0;
  340. this.start = start;
  341. this.end = end;
  342. }
  343. }
  344. function getLineInfo(input, offset) {
  345. let line = 1;
  346. let lineStart = 0;
  347. let match;
  348. lineBreakG.lastIndex = 0;
  349. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  350. line++;
  351. lineStart = lineBreakG.lastIndex;
  352. }
  353. return new Position(line, offset - lineStart);
  354. }
  355. class BaseParser {
  356. constructor() {
  357. this.sawUnambiguousESM = false;
  358. this.ambiguousScriptDifferentAst = false;
  359. }
  360. hasPlugin(name) {
  361. return this.plugins.has(name);
  362. }
  363. getPluginOption(plugin, name) {
  364. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  365. }
  366. }
  367. function last(stack) {
  368. return stack[stack.length - 1];
  369. }
  370. class CommentsParser extends BaseParser {
  371. addComment(comment) {
  372. if (this.filename) comment.loc.filename = this.filename;
  373. this.state.trailingComments.push(comment);
  374. this.state.leadingComments.push(comment);
  375. }
  376. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  377. if (this.state.leadingComments.length === 0) {
  378. return;
  379. }
  380. let lastElement = null;
  381. let i = elements.length;
  382. while (lastElement === null && i > 0) {
  383. lastElement = elements[--i];
  384. }
  385. if (lastElement === null) {
  386. return;
  387. }
  388. for (let j = 0; j < this.state.leadingComments.length; j++) {
  389. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  390. this.state.leadingComments.splice(j, 1);
  391. j--;
  392. }
  393. }
  394. const newTrailingComments = [];
  395. for (let i = 0; i < this.state.leadingComments.length; i++) {
  396. const leadingComment = this.state.leadingComments[i];
  397. if (leadingComment.end < node.end) {
  398. newTrailingComments.push(leadingComment);
  399. if (!takeAllComments) {
  400. this.state.leadingComments.splice(i, 1);
  401. i--;
  402. }
  403. } else {
  404. if (node.trailingComments === undefined) {
  405. node.trailingComments = [];
  406. }
  407. node.trailingComments.push(leadingComment);
  408. }
  409. }
  410. if (takeAllComments) this.state.leadingComments = [];
  411. if (newTrailingComments.length > 0) {
  412. lastElement.trailingComments = newTrailingComments;
  413. } else if (lastElement.trailingComments !== undefined) {
  414. lastElement.trailingComments = [];
  415. }
  416. }
  417. processComment(node) {
  418. if (node.type === "Program" && node.body.length > 0) return;
  419. const stack = this.state.commentStack;
  420. let firstChild, lastChild, trailingComments, i, j;
  421. if (this.state.trailingComments.length > 0) {
  422. if (this.state.trailingComments[0].start >= node.end) {
  423. trailingComments = this.state.trailingComments;
  424. this.state.trailingComments = [];
  425. } else {
  426. this.state.trailingComments.length = 0;
  427. }
  428. } else if (stack.length > 0) {
  429. const lastInStack = last(stack);
  430. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  431. trailingComments = lastInStack.trailingComments;
  432. delete lastInStack.trailingComments;
  433. }
  434. }
  435. if (stack.length > 0 && last(stack).start >= node.start) {
  436. firstChild = stack.pop();
  437. }
  438. while (stack.length > 0 && last(stack).start >= node.start) {
  439. lastChild = stack.pop();
  440. }
  441. if (!lastChild && firstChild) lastChild = firstChild;
  442. if (firstChild) {
  443. switch (node.type) {
  444. case "ObjectExpression":
  445. this.adjustCommentsAfterTrailingComma(node, node.properties);
  446. break;
  447. case "ObjectPattern":
  448. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  449. break;
  450. case "CallExpression":
  451. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  452. break;
  453. case "ArrayExpression":
  454. this.adjustCommentsAfterTrailingComma(node, node.elements);
  455. break;
  456. case "ArrayPattern":
  457. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  458. break;
  459. }
  460. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  461. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  462. }
  463. if (lastChild) {
  464. if (lastChild.leadingComments) {
  465. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  466. node.leadingComments = lastChild.leadingComments;
  467. delete lastChild.leadingComments;
  468. } else {
  469. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  470. if (lastChild.leadingComments[i].end <= node.start) {
  471. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  472. break;
  473. }
  474. }
  475. }
  476. }
  477. } else if (this.state.leadingComments.length > 0) {
  478. if (last(this.state.leadingComments).end <= node.start) {
  479. if (this.state.commentPreviousNode) {
  480. for (j = 0; j < this.state.leadingComments.length; j++) {
  481. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  482. this.state.leadingComments.splice(j, 1);
  483. j--;
  484. }
  485. }
  486. }
  487. if (this.state.leadingComments.length > 0) {
  488. node.leadingComments = this.state.leadingComments;
  489. this.state.leadingComments = [];
  490. }
  491. } else {
  492. for (i = 0; i < this.state.leadingComments.length; i++) {
  493. if (this.state.leadingComments[i].end > node.start) {
  494. break;
  495. }
  496. }
  497. const leadingComments = this.state.leadingComments.slice(0, i);
  498. if (leadingComments.length) {
  499. node.leadingComments = leadingComments;
  500. }
  501. trailingComments = this.state.leadingComments.slice(i);
  502. if (trailingComments.length === 0) {
  503. trailingComments = null;
  504. }
  505. }
  506. }
  507. this.state.commentPreviousNode = node;
  508. if (trailingComments) {
  509. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  510. node.innerComments = trailingComments;
  511. } else {
  512. const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end);
  513. if (firstTrailingCommentIndex > 0) {
  514. node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex);
  515. node.trailingComments = trailingComments.slice(firstTrailingCommentIndex);
  516. } else {
  517. node.trailingComments = trailingComments;
  518. }
  519. }
  520. }
  521. stack.push(node);
  522. }
  523. }
  524. const ErrorMessages = Object.freeze({
  525. AccessorIsGenerator: "A %0ter cannot be a generator",
  526. ArgumentsInClass: "'arguments' is only allowed in functions and class methods",
  527. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  528. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  529. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block",
  530. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  531. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules",
  532. AwaitNotInAsyncFunction: "'await' is only allowed within async functions",
  533. BadGetterArity: "getter must not have any formal parameters",
  534. BadSetterArity: "setter must have exactly one formal parameter",
  535. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  536. ConstructorClassField: "Classes may not have a field named 'constructor'",
  537. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  538. ConstructorIsAccessor: "Class constructor may not be an accessor",
  539. ConstructorIsAsync: "Constructor can't be an async function",
  540. ConstructorIsGenerator: "Constructor can't be a generator",
  541. DeclarationMissingInitializer: "%0 require an initialization value",
  542. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  543. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  544. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  545. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  546. DecoratorStaticBlock: "Decorators can't be used with a static block",
  547. DeletePrivateField: "Deleting a private field is not allowed",
  548. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  549. DuplicateConstructor: "Duplicate constructor in the same class",
  550. DuplicateDefaultExport: "Only one default export allowed per module.",
  551. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  552. DuplicateProto: "Redefinition of __proto__ property",
  553. DuplicateRegExpFlags: "Duplicate regular expression flag",
  554. ElementAfterRest: "Rest element must be last element",
  555. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  556. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?",
  557. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'",
  558. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  559. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  560. IllegalBreakContinue: "Unsyntactic %0",
  561. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  562. IllegalReturn: "'return' outside of function",
  563. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  564. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  565. ImportCallArity: "import() requires exactly %0",
  566. ImportCallNotNewExpression: "Cannot use new with import(...)",
  567. ImportCallSpreadArgument: "... is not allowed in import()",
  568. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  569. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  570. InvalidBigIntLiteral: "Invalid BigIntLiteral",
  571. InvalidCodePoint: "Code point out of bounds",
  572. InvalidDecimal: "Invalid decimal",
  573. InvalidDigit: "Expected number in radix %0",
  574. InvalidEscapeSequence: "Bad character escape sequence",
  575. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  576. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  577. InvalidIdentifier: "Invalid identifier %0",
  578. InvalidLhs: "Invalid left-hand side in %0",
  579. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  580. InvalidNumber: "Invalid number",
  581. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'",
  582. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  583. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  584. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  585. InvalidPropertyBindingPattern: "Binding member expression",
  586. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions",
  587. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  588. LabelRedeclaration: "Label '%0' is already declared",
  589. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  590. LineTerminatorBeforeArrow: "No line break is allowed before '=>'",
  591. MalformedRegExpFlags: "Invalid regular expression flag",
  592. MissingClassName: "A class name is required",
  593. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  594. MissingSemicolon: "Missing semicolon",
  595. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  596. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  597. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
  598. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
  599. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
  600. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
  601. ModuleExportUndefined: "Export '%0' is not defined",
  602. MultipleDefaultsInSwitch: "Multiple default clauses",
  603. NewlineAfterThrow: "Illegal newline after throw",
  604. NoCatchOrFinally: "Missing catch or finally clause",
  605. NumberIdentifier: "Identifier directly after number",
  606. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  607. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  608. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  609. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  610. ParamDupe: "Argument name clash",
  611. PatternHasAccessor: "Object pattern can't contain getter or setter",
  612. PatternHasMethod: "Object pattern can't contain methods",
  613. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  614. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  615. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  616. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  617. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  618. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  619. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
  620. PrivateNameRedeclaration: "Duplicate private name #%0",
  621. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  622. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  623. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  624. RecordNoProto: "'__proto__' is not allowed in Record expressions",
  625. RestTrailingComma: "Unexpected trailing comma after rest element",
  626. 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",
  627. StaticPrototype: "Classes may not have static property named prototype",
  628. StrictDelete: "Deleting local variable in strict mode",
  629. StrictEvalArguments: "Assigning to '%0' in strict mode",
  630. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  631. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  632. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
  633. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  634. StrictWith: "'with' in strict mode",
  635. 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?",
  636. SuperPrivateField: "Private fields can't be accessed on super",
  637. TrailingDecorator: "Decorators must be attached to a class element",
  638. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  639. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  640. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  641. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  642. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  643. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  644. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  645. UnexpectedKeyword: "Unexpected keyword '%0'",
  646. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  647. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  648. UnexpectedNewTarget: "new.target can only be used in functions",
  649. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  650. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  651. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  652. UnexpectedSuper: "super is only allowed in object methods and classes",
  653. UnexpectedToken: "Unexpected token '%0'",
  654. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  655. UnsupportedBind: "Binding should be performed on object property.",
  656. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  657. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  658. UnsupportedImport: "import can only be used in import() or import.meta",
  659. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  660. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  661. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  662. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  663. UnterminatedComment: "Unterminated comment",
  664. UnterminatedRegExp: "Unterminated regular expression",
  665. UnterminatedString: "Unterminated string constant",
  666. UnterminatedTemplate: "Unterminated template",
  667. VarRedeclaration: "Identifier '%0' has already been declared",
  668. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  669. YieldInParameter: "Yield expression is not allowed in formal parameters",
  670. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  671. });
  672. class ParserError extends CommentsParser {
  673. getLocationForPosition(pos) {
  674. let loc;
  675. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  676. return loc;
  677. }
  678. raise(pos, errorTemplate, ...params) {
  679. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  680. }
  681. raiseOverwrite(pos, errorTemplate, ...params) {
  682. const loc = this.getLocationForPosition(pos);
  683. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  684. if (this.options.errorRecovery) {
  685. const errors = this.state.errors;
  686. for (let i = errors.length - 1; i >= 0; i--) {
  687. const error = errors[i];
  688. if (error.pos === pos) {
  689. return Object.assign(error, {
  690. message
  691. });
  692. } else if (error.pos < pos) {
  693. break;
  694. }
  695. }
  696. }
  697. return this._raise({
  698. loc,
  699. pos
  700. }, message);
  701. }
  702. raiseWithData(pos, data, errorTemplate, ...params) {
  703. const loc = this.getLocationForPosition(pos);
  704. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  705. return this._raise(Object.assign({
  706. loc,
  707. pos
  708. }, data), message);
  709. }
  710. _raise(errorContext, message) {
  711. const err = new SyntaxError(message);
  712. Object.assign(err, errorContext);
  713. if (this.options.errorRecovery) {
  714. if (!this.isLookahead) this.state.errors.push(err);
  715. return err;
  716. } else {
  717. throw err;
  718. }
  719. }
  720. }
  721. var estree = (superClass => class extends superClass {
  722. estreeParseRegExpLiteral({
  723. pattern,
  724. flags
  725. }) {
  726. let regex = null;
  727. try {
  728. regex = new RegExp(pattern, flags);
  729. } catch (e) {}
  730. const node = this.estreeParseLiteral(regex);
  731. node.regex = {
  732. pattern,
  733. flags
  734. };
  735. return node;
  736. }
  737. estreeParseBigIntLiteral(value) {
  738. let bigInt;
  739. try {
  740. bigInt = BigInt(value);
  741. } catch (_unused) {
  742. bigInt = null;
  743. }
  744. const node = this.estreeParseLiteral(bigInt);
  745. node.bigint = String(node.value || value);
  746. return node;
  747. }
  748. estreeParseDecimalLiteral(value) {
  749. const decimal = null;
  750. const node = this.estreeParseLiteral(decimal);
  751. node.decimal = String(node.value || value);
  752. return node;
  753. }
  754. estreeParseLiteral(value) {
  755. return this.parseLiteral(value, "Literal");
  756. }
  757. directiveToStmt(directive) {
  758. const directiveLiteral = directive.value;
  759. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  760. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  761. expression.value = directiveLiteral.extra.expressionValue;
  762. expression.raw = directiveLiteral.extra.raw;
  763. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  764. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  765. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  766. }
  767. initFunction(node, isAsync) {
  768. super.initFunction(node, isAsync);
  769. node.expression = false;
  770. }
  771. checkDeclaration(node) {
  772. if (node != null && this.isObjectProperty(node)) {
  773. this.checkDeclaration(node.value);
  774. } else {
  775. super.checkDeclaration(node);
  776. }
  777. }
  778. getObjectOrClassMethodParams(method) {
  779. return method.value.params;
  780. }
  781. isValidDirective(stmt) {
  782. var _stmt$expression$extr;
  783. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  784. }
  785. stmtToDirective(stmt) {
  786. const directive = super.stmtToDirective(stmt);
  787. const value = stmt.expression.value;
  788. this.addExtra(directive.value, "expressionValue", value);
  789. return directive;
  790. }
  791. parseBlockBody(node, ...args) {
  792. super.parseBlockBody(node, ...args);
  793. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  794. node.body = directiveStatements.concat(node.body);
  795. delete node.directives;
  796. }
  797. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  798. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  799. if (method.typeParameters) {
  800. method.value.typeParameters = method.typeParameters;
  801. delete method.typeParameters;
  802. }
  803. classBody.body.push(method);
  804. }
  805. parseExprAtom(refExpressionErrors) {
  806. switch (this.state.type) {
  807. case types.num:
  808. case types.string:
  809. return this.estreeParseLiteral(this.state.value);
  810. case types.regexp:
  811. return this.estreeParseRegExpLiteral(this.state.value);
  812. case types.bigint:
  813. return this.estreeParseBigIntLiteral(this.state.value);
  814. case types.decimal:
  815. return this.estreeParseDecimalLiteral(this.state.value);
  816. case types._null:
  817. return this.estreeParseLiteral(null);
  818. case types._true:
  819. return this.estreeParseLiteral(true);
  820. case types._false:
  821. return this.estreeParseLiteral(false);
  822. default:
  823. return super.parseExprAtom(refExpressionErrors);
  824. }
  825. }
  826. parseMaybePrivateName(...args) {
  827. const node = super.parseMaybePrivateName(...args);
  828. if (node.type === "PrivateName" && this.getPluginOption("estree", "classFeatures")) {
  829. return this.convertPrivateNameToPrivateIdentifier(node);
  830. }
  831. return node;
  832. }
  833. convertPrivateNameToPrivateIdentifier(node) {
  834. const name = super.getPrivateNameSV(node);
  835. node = node;
  836. delete node.id;
  837. node.name = name;
  838. node.type = "PrivateIdentifier";
  839. return node;
  840. }
  841. isPrivateName(node) {
  842. if (!this.getPluginOption("estree", "classFeatures")) {
  843. return super.isPrivateName(node);
  844. }
  845. return node.type === "PrivateIdentifier";
  846. }
  847. getPrivateNameSV(node) {
  848. if (!this.getPluginOption("estree", "classFeatures")) {
  849. return super.getPrivateNameSV(node);
  850. }
  851. return node.name;
  852. }
  853. parseLiteral(value, type, startPos, startLoc) {
  854. const node = super.parseLiteral(value, type, startPos, startLoc);
  855. node.raw = node.extra.raw;
  856. delete node.extra;
  857. return node;
  858. }
  859. parseFunctionBody(node, allowExpression, isMethod = false) {
  860. super.parseFunctionBody(node, allowExpression, isMethod);
  861. node.expression = node.body.type !== "BlockStatement";
  862. }
  863. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  864. let funcNode = this.startNode();
  865. funcNode.kind = node.kind;
  866. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  867. funcNode.type = "FunctionExpression";
  868. delete funcNode.kind;
  869. node.value = funcNode;
  870. if (type === "ClassPrivateMethod") {
  871. node.computed = false;
  872. }
  873. type = "MethodDefinition";
  874. return this.finishNode(node, type);
  875. }
  876. parseClassProperty(...args) {
  877. const propertyNode = super.parseClassProperty(...args);
  878. if (this.getPluginOption("estree", "classFeatures")) {
  879. propertyNode.type = "PropertyDefinition";
  880. }
  881. return propertyNode;
  882. }
  883. parseClassPrivateProperty(...args) {
  884. const propertyNode = super.parseClassPrivateProperty(...args);
  885. if (this.getPluginOption("estree", "classFeatures")) {
  886. propertyNode.type = "PropertyDefinition";
  887. propertyNode.computed = false;
  888. }
  889. return propertyNode;
  890. }
  891. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  892. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  893. if (node) {
  894. node.type = "Property";
  895. if (node.kind === "method") node.kind = "init";
  896. node.shorthand = false;
  897. }
  898. return node;
  899. }
  900. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  901. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  902. if (node) {
  903. node.kind = "init";
  904. node.type = "Property";
  905. }
  906. return node;
  907. }
  908. toAssignable(node, isLHS = false) {
  909. if (node != null && this.isObjectProperty(node)) {
  910. this.toAssignable(node.value, isLHS);
  911. return node;
  912. }
  913. return super.toAssignable(node, isLHS);
  914. }
  915. toAssignableObjectExpressionProp(prop, ...args) {
  916. if (prop.kind === "get" || prop.kind === "set") {
  917. this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  918. } else if (prop.method) {
  919. this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  920. } else {
  921. super.toAssignableObjectExpressionProp(prop, ...args);
  922. }
  923. }
  924. finishCallExpression(node, optional) {
  925. super.finishCallExpression(node, optional);
  926. if (node.callee.type === "Import") {
  927. node.type = "ImportExpression";
  928. node.source = node.arguments[0];
  929. delete node.arguments;
  930. delete node.callee;
  931. }
  932. return node;
  933. }
  934. toReferencedArguments(node) {
  935. if (node.type === "ImportExpression") {
  936. return;
  937. }
  938. super.toReferencedArguments(node);
  939. }
  940. parseExport(node) {
  941. super.parseExport(node);
  942. switch (node.type) {
  943. case "ExportAllDeclaration":
  944. node.exported = null;
  945. break;
  946. case "ExportNamedDeclaration":
  947. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  948. node.type = "ExportAllDeclaration";
  949. node.exported = node.specifiers[0].exported;
  950. delete node.specifiers;
  951. }
  952. break;
  953. }
  954. return node;
  955. }
  956. parseSubscript(base, startPos, startLoc, noCalls, state) {
  957. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  958. if (state.optionalChainMember) {
  959. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  960. node.type = node.type.substring(8);
  961. }
  962. if (state.stop) {
  963. const chain = this.startNodeAtNode(node);
  964. chain.expression = node;
  965. return this.finishNode(chain, "ChainExpression");
  966. }
  967. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  968. node.optional = false;
  969. }
  970. return node;
  971. }
  972. hasPropertyAsPrivateName(node) {
  973. if (node.type === "ChainExpression") {
  974. node = node.expression;
  975. }
  976. return super.hasPropertyAsPrivateName(node);
  977. }
  978. isOptionalChain(node) {
  979. return node.type === "ChainExpression";
  980. }
  981. isObjectProperty(node) {
  982. return node.type === "Property" && node.kind === "init" && !node.method;
  983. }
  984. isObjectMethod(node) {
  985. return node.method || node.kind === "get" || node.kind === "set";
  986. }
  987. });
  988. class TokContext {
  989. constructor(token, isExpr, preserveSpace, override) {
  990. this.token = void 0;
  991. this.isExpr = void 0;
  992. this.preserveSpace = void 0;
  993. this.override = void 0;
  994. this.token = token;
  995. this.isExpr = !!isExpr;
  996. this.preserveSpace = !!preserveSpace;
  997. this.override = override;
  998. }
  999. }
  1000. const types$1 = {
  1001. braceStatement: new TokContext("{", false),
  1002. braceExpression: new TokContext("{", true),
  1003. recordExpression: new TokContext("#{", true),
  1004. templateQuasi: new TokContext("${", false),
  1005. parenStatement: new TokContext("(", false),
  1006. parenExpression: new TokContext("(", true),
  1007. template: new TokContext("`", true, true, p => p.readTmplToken()),
  1008. functionExpression: new TokContext("function", true),
  1009. functionStatement: new TokContext("function", false)
  1010. };
  1011. types.parenR.updateContext = types.braceR.updateContext = function () {
  1012. if (this.state.context.length === 1) {
  1013. this.state.exprAllowed = true;
  1014. return;
  1015. }
  1016. let out = this.state.context.pop();
  1017. if (out === types$1.braceStatement && this.curContext().token === "function") {
  1018. out = this.state.context.pop();
  1019. }
  1020. this.state.exprAllowed = !out.isExpr;
  1021. };
  1022. types.name.updateContext = function (prevType) {
  1023. let allowed = false;
  1024. if (prevType !== types.dot) {
  1025. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class) {
  1026. allowed = true;
  1027. }
  1028. }
  1029. this.state.exprAllowed = allowed;
  1030. if (this.state.isIterator) {
  1031. this.state.isIterator = false;
  1032. }
  1033. };
  1034. types.braceL.updateContext = function (prevType) {
  1035. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  1036. this.state.exprAllowed = true;
  1037. };
  1038. types.dollarBraceL.updateContext = function () {
  1039. this.state.context.push(types$1.templateQuasi);
  1040. this.state.exprAllowed = true;
  1041. };
  1042. types.parenL.updateContext = function (prevType) {
  1043. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  1044. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  1045. this.state.exprAllowed = true;
  1046. };
  1047. types.incDec.updateContext = function () {};
  1048. types._function.updateContext = types._class.updateContext = function (prevType) {
  1049. if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && this.hasPrecedingLineBreak()) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
  1050. this.state.context.push(types$1.functionExpression);
  1051. } else {
  1052. this.state.context.push(types$1.functionStatement);
  1053. }
  1054. this.state.exprAllowed = false;
  1055. };
  1056. types.backQuote.updateContext = function () {
  1057. if (this.curContext() === types$1.template) {
  1058. this.state.context.pop();
  1059. } else {
  1060. this.state.context.push(types$1.template);
  1061. }
  1062. this.state.exprAllowed = false;
  1063. };
  1064. types.braceHashL.updateContext = function () {
  1065. this.state.context.push(types$1.recordExpression);
  1066. this.state.exprAllowed = true;
  1067. };
  1068. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  1069. let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  1070. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1071. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1072. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1073. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  1074. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  1075. function isInAstralSet(code, set) {
  1076. let pos = 0x10000;
  1077. for (let i = 0, length = set.length; i < length; i += 2) {
  1078. pos += set[i];
  1079. if (pos > code) return false;
  1080. pos += set[i + 1];
  1081. if (pos >= code) return true;
  1082. }
  1083. return false;
  1084. }
  1085. function isIdentifierStart(code) {
  1086. if (code < 65) return code === 36;
  1087. if (code <= 90) return true;
  1088. if (code < 97) return code === 95;
  1089. if (code <= 122) return true;
  1090. if (code <= 0xffff) {
  1091. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1092. }
  1093. return isInAstralSet(code, astralIdentifierStartCodes);
  1094. }
  1095. function isIdentifierChar(code) {
  1096. if (code < 48) return code === 36;
  1097. if (code < 58) return true;
  1098. if (code < 65) return false;
  1099. if (code <= 90) return true;
  1100. if (code < 97) return code === 95;
  1101. if (code <= 122) return true;
  1102. if (code <= 0xffff) {
  1103. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1104. }
  1105. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1106. }
  1107. const reservedWords = {
  1108. 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"],
  1109. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1110. strictBind: ["eval", "arguments"]
  1111. };
  1112. const keywords$1 = new Set(reservedWords.keyword);
  1113. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1114. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1115. function isReservedWord(word, inModule) {
  1116. return inModule && word === "await" || word === "enum";
  1117. }
  1118. function isStrictReservedWord(word, inModule) {
  1119. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1120. }
  1121. function isStrictBindOnlyReservedWord(word) {
  1122. return reservedWordsStrictBindSet.has(word);
  1123. }
  1124. function isStrictBindReservedWord(word, inModule) {
  1125. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1126. }
  1127. function isKeyword(word) {
  1128. return keywords$1.has(word);
  1129. }
  1130. const keywordRelationalOperator = /^in(stanceof)?$/;
  1131. function isIteratorStart(current, next) {
  1132. return current === 64 && next === 64;
  1133. }
  1134. const SCOPE_OTHER = 0b000000000,
  1135. SCOPE_PROGRAM = 0b000000001,
  1136. SCOPE_FUNCTION = 0b000000010,
  1137. SCOPE_ARROW = 0b000000100,
  1138. SCOPE_SIMPLE_CATCH = 0b000001000,
  1139. SCOPE_SUPER = 0b000010000,
  1140. SCOPE_DIRECT_SUPER = 0b000100000,
  1141. SCOPE_CLASS = 0b001000000,
  1142. SCOPE_STATIC_BLOCK = 0b010000000,
  1143. SCOPE_TS_MODULE = 0b100000000,
  1144. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  1145. const BIND_KIND_VALUE = 0b000000000001,
  1146. BIND_KIND_TYPE = 0b000000000010,
  1147. BIND_SCOPE_VAR = 0b000000000100,
  1148. BIND_SCOPE_LEXICAL = 0b000000001000,
  1149. BIND_SCOPE_FUNCTION = 0b000000010000,
  1150. BIND_FLAGS_NONE = 0b000001000000,
  1151. BIND_FLAGS_CLASS = 0b000010000000,
  1152. BIND_FLAGS_TS_ENUM = 0b000100000000,
  1153. BIND_FLAGS_TS_CONST_ENUM = 0b001000000000,
  1154. BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000,
  1155. BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000;
  1156. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  1157. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  1158. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  1159. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  1160. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  1161. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  1162. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  1163. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  1164. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  1165. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  1166. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  1167. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  1168. BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
  1169. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  1170. CLASS_ELEMENT_KIND_GETTER = 0b010,
  1171. CLASS_ELEMENT_KIND_SETTER = 0b001,
  1172. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  1173. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  1174. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  1175. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  1176. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  1177. CLASS_ELEMENT_OTHER = 0;
  1178. class Scope {
  1179. constructor(flags) {
  1180. this.flags = void 0;
  1181. this.var = [];
  1182. this.lexical = [];
  1183. this.functions = [];
  1184. this.flags = flags;
  1185. }
  1186. }
  1187. class ScopeHandler {
  1188. constructor(raise, inModule) {
  1189. this.scopeStack = [];
  1190. this.undefinedExports = new Map();
  1191. this.undefinedPrivateNames = new Map();
  1192. this.raise = raise;
  1193. this.inModule = inModule;
  1194. }
  1195. get inFunction() {
  1196. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  1197. }
  1198. get allowSuper() {
  1199. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  1200. }
  1201. get allowDirectSuper() {
  1202. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  1203. }
  1204. get inClass() {
  1205. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  1206. }
  1207. get inStaticBlock() {
  1208. return (this.currentThisScope().flags & SCOPE_STATIC_BLOCK) > 0;
  1209. }
  1210. get inNonArrowFunction() {
  1211. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  1212. }
  1213. get treatFunctionsAsVar() {
  1214. return this.treatFunctionsAsVarInScope(this.currentScope());
  1215. }
  1216. createScope(flags) {
  1217. return new Scope(flags);
  1218. }
  1219. enter(flags) {
  1220. this.scopeStack.push(this.createScope(flags));
  1221. }
  1222. exit() {
  1223. this.scopeStack.pop();
  1224. }
  1225. treatFunctionsAsVarInScope(scope) {
  1226. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  1227. }
  1228. declareName(name, bindingType, pos) {
  1229. let scope = this.currentScope();
  1230. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  1231. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  1232. if (bindingType & BIND_SCOPE_FUNCTION) {
  1233. scope.functions.push(name);
  1234. } else {
  1235. scope.lexical.push(name);
  1236. }
  1237. if (bindingType & BIND_SCOPE_LEXICAL) {
  1238. this.maybeExportDefined(scope, name);
  1239. }
  1240. } else if (bindingType & BIND_SCOPE_VAR) {
  1241. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  1242. scope = this.scopeStack[i];
  1243. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  1244. scope.var.push(name);
  1245. this.maybeExportDefined(scope, name);
  1246. if (scope.flags & SCOPE_VAR) break;
  1247. }
  1248. }
  1249. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  1250. this.undefinedExports.delete(name);
  1251. }
  1252. }
  1253. maybeExportDefined(scope, name) {
  1254. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  1255. this.undefinedExports.delete(name);
  1256. }
  1257. }
  1258. checkRedeclarationInScope(scope, name, bindingType, pos) {
  1259. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  1260. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  1261. }
  1262. }
  1263. isRedeclaredInScope(scope, name, bindingType) {
  1264. if (!(bindingType & BIND_KIND_VALUE)) return false;
  1265. if (bindingType & BIND_SCOPE_LEXICAL) {
  1266. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  1267. }
  1268. if (bindingType & BIND_SCOPE_FUNCTION) {
  1269. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  1270. }
  1271. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  1272. }
  1273. checkLocalExport(id) {
  1274. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) {
  1275. this.undefinedExports.set(id.name, id.start);
  1276. }
  1277. }
  1278. currentScope() {
  1279. return this.scopeStack[this.scopeStack.length - 1];
  1280. }
  1281. currentVarScope() {
  1282. for (let i = this.scopeStack.length - 1;; i--) {
  1283. const scope = this.scopeStack[i];
  1284. if (scope.flags & SCOPE_VAR) {
  1285. return scope;
  1286. }
  1287. }
  1288. }
  1289. currentThisScope() {
  1290. for (let i = this.scopeStack.length - 1;; i--) {
  1291. const scope = this.scopeStack[i];
  1292. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  1293. return scope;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. class FlowScope extends Scope {
  1299. constructor(...args) {
  1300. super(...args);
  1301. this.declareFunctions = [];
  1302. }
  1303. }
  1304. class FlowScopeHandler extends ScopeHandler {
  1305. createScope(flags) {
  1306. return new FlowScope(flags);
  1307. }
  1308. declareName(name, bindingType, pos) {
  1309. const scope = this.currentScope();
  1310. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  1311. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  1312. this.maybeExportDefined(scope, name);
  1313. scope.declareFunctions.push(name);
  1314. return;
  1315. }
  1316. super.declareName(...arguments);
  1317. }
  1318. isRedeclaredInScope(scope, name, bindingType) {
  1319. if (super.isRedeclaredInScope(...arguments)) return true;
  1320. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  1321. return !scope.declareFunctions.includes(name) && (scope.lexical.includes(name) || scope.functions.includes(name));
  1322. }
  1323. return false;
  1324. }
  1325. checkLocalExport(id) {
  1326. if (this.scopeStack[0].declareFunctions.indexOf(id.name) === -1) {
  1327. super.checkLocalExport(id);
  1328. }
  1329. }
  1330. }
  1331. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1332. const FlowErrors = Object.freeze({
  1333. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1334. 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",
  1335. AssignReservedType: "Cannot overwrite reserved type %0",
  1336. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1337. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1338. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1339. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1340. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1341. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1342. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1343. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1344. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1345. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1346. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1347. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1348. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1349. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1350. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  1351. 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",
  1352. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1353. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1354. InexactVariance: "Explicit inexact syntax cannot have variance",
  1355. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1356. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1357. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1358. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1359. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1360. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  1361. SpreadVariance: "Spread properties cannot have variance",
  1362. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  1363. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  1364. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  1365. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  1366. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  1367. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1368. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1369. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1370. UnexpectedReservedType: "Unexpected reserved type %0",
  1371. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1372. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1373. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1374. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1375. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1376. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  1377. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1378. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1379. UnterminatedFlowComment: "Unterminated flow-comment"
  1380. });
  1381. function isEsModuleType(bodyElement) {
  1382. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1383. }
  1384. function hasTypeImportKind(node) {
  1385. return node.importKind === "type" || node.importKind === "typeof";
  1386. }
  1387. function isMaybeDefaultImport(state) {
  1388. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1389. }
  1390. const exportSuggestions = {
  1391. const: "declare export var",
  1392. let: "declare export var",
  1393. type: "export type",
  1394. interface: "export interface"
  1395. };
  1396. function partition(list, test) {
  1397. const list1 = [];
  1398. const list2 = [];
  1399. for (let i = 0; i < list.length; i++) {
  1400. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1401. }
  1402. return [list1, list2];
  1403. }
  1404. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1405. var flow = (superClass => {
  1406. var _temp;
  1407. return _temp = class extends superClass {
  1408. constructor(...args) {
  1409. super(...args);
  1410. this.flowPragma = undefined;
  1411. }
  1412. getScopeHandler() {
  1413. return FlowScopeHandler;
  1414. }
  1415. shouldParseTypes() {
  1416. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1417. }
  1418. shouldParseEnums() {
  1419. return !!this.getPluginOption("flow", "enums");
  1420. }
  1421. finishToken(type, val) {
  1422. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1423. if (this.flowPragma === undefined) {
  1424. this.flowPragma = null;
  1425. }
  1426. }
  1427. return super.finishToken(type, val);
  1428. }
  1429. addComment(comment) {
  1430. if (this.flowPragma === undefined) {
  1431. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1432. if (!matches) ; else if (matches[1] === "flow") {
  1433. this.flowPragma = "flow";
  1434. } else if (matches[1] === "noflow") {
  1435. this.flowPragma = "noflow";
  1436. } else {
  1437. throw new Error("Unexpected flow pragma");
  1438. }
  1439. }
  1440. return super.addComment(comment);
  1441. }
  1442. flowParseTypeInitialiser(tok) {
  1443. const oldInType = this.state.inType;
  1444. this.state.inType = true;
  1445. this.expect(tok || types.colon);
  1446. const type = this.flowParseType();
  1447. this.state.inType = oldInType;
  1448. return type;
  1449. }
  1450. flowParsePredicate() {
  1451. const node = this.startNode();
  1452. const moduloLoc = this.state.startLoc;
  1453. const moduloPos = this.state.start;
  1454. this.expect(types.modulo);
  1455. const checksLoc = this.state.startLoc;
  1456. this.expectContextual("checks");
  1457. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1458. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1459. }
  1460. if (this.eat(types.parenL)) {
  1461. node.value = this.parseExpression();
  1462. this.expect(types.parenR);
  1463. return this.finishNode(node, "DeclaredPredicate");
  1464. } else {
  1465. return this.finishNode(node, "InferredPredicate");
  1466. }
  1467. }
  1468. flowParseTypeAndPredicateInitialiser() {
  1469. const oldInType = this.state.inType;
  1470. this.state.inType = true;
  1471. this.expect(types.colon);
  1472. let type = null;
  1473. let predicate = null;
  1474. if (this.match(types.modulo)) {
  1475. this.state.inType = oldInType;
  1476. predicate = this.flowParsePredicate();
  1477. } else {
  1478. type = this.flowParseType();
  1479. this.state.inType = oldInType;
  1480. if (this.match(types.modulo)) {
  1481. predicate = this.flowParsePredicate();
  1482. }
  1483. }
  1484. return [type, predicate];
  1485. }
  1486. flowParseDeclareClass(node) {
  1487. this.next();
  1488. this.flowParseInterfaceish(node, true);
  1489. return this.finishNode(node, "DeclareClass");
  1490. }
  1491. flowParseDeclareFunction(node) {
  1492. this.next();
  1493. const id = node.id = this.parseIdentifier();
  1494. const typeNode = this.startNode();
  1495. const typeContainer = this.startNode();
  1496. if (this.isRelational("<")) {
  1497. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1498. } else {
  1499. typeNode.typeParameters = null;
  1500. }
  1501. this.expect(types.parenL);
  1502. const tmp = this.flowParseFunctionTypeParams();
  1503. typeNode.params = tmp.params;
  1504. typeNode.rest = tmp.rest;
  1505. typeNode.this = tmp._this;
  1506. this.expect(types.parenR);
  1507. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1508. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1509. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1510. this.resetEndLocation(id);
  1511. this.semicolon();
  1512. this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
  1513. return this.finishNode(node, "DeclareFunction");
  1514. }
  1515. flowParseDeclare(node, insideModule) {
  1516. if (this.match(types._class)) {
  1517. return this.flowParseDeclareClass(node);
  1518. } else if (this.match(types._function)) {
  1519. return this.flowParseDeclareFunction(node);
  1520. } else if (this.match(types._var)) {
  1521. return this.flowParseDeclareVariable(node);
  1522. } else if (this.eatContextual("module")) {
  1523. if (this.match(types.dot)) {
  1524. return this.flowParseDeclareModuleExports(node);
  1525. } else {
  1526. if (insideModule) {
  1527. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1528. }
  1529. return this.flowParseDeclareModule(node);
  1530. }
  1531. } else if (this.isContextual("type")) {
  1532. return this.flowParseDeclareTypeAlias(node);
  1533. } else if (this.isContextual("opaque")) {
  1534. return this.flowParseDeclareOpaqueType(node);
  1535. } else if (this.isContextual("interface")) {
  1536. return this.flowParseDeclareInterface(node);
  1537. } else if (this.match(types._export)) {
  1538. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1539. } else {
  1540. throw this.unexpected();
  1541. }
  1542. }
  1543. flowParseDeclareVariable(node) {
  1544. this.next();
  1545. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1546. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1547. this.semicolon();
  1548. return this.finishNode(node, "DeclareVariable");
  1549. }
  1550. flowParseDeclareModule(node) {
  1551. this.scope.enter(SCOPE_OTHER);
  1552. if (this.match(types.string)) {
  1553. node.id = this.parseExprAtom();
  1554. } else {
  1555. node.id = this.parseIdentifier();
  1556. }
  1557. const bodyNode = node.body = this.startNode();
  1558. const body = bodyNode.body = [];
  1559. this.expect(types.braceL);
  1560. while (!this.match(types.braceR)) {
  1561. let bodyNode = this.startNode();
  1562. if (this.match(types._import)) {
  1563. this.next();
  1564. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1565. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1566. }
  1567. this.parseImport(bodyNode);
  1568. } else {
  1569. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1570. bodyNode = this.flowParseDeclare(bodyNode, true);
  1571. }
  1572. body.push(bodyNode);
  1573. }
  1574. this.scope.exit();
  1575. this.expect(types.braceR);
  1576. this.finishNode(bodyNode, "BlockStatement");
  1577. let kind = null;
  1578. let hasModuleExport = false;
  1579. body.forEach(bodyElement => {
  1580. if (isEsModuleType(bodyElement)) {
  1581. if (kind === "CommonJS") {
  1582. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1583. }
  1584. kind = "ES";
  1585. } else if (bodyElement.type === "DeclareModuleExports") {
  1586. if (hasModuleExport) {
  1587. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1588. }
  1589. if (kind === "ES") {
  1590. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1591. }
  1592. kind = "CommonJS";
  1593. hasModuleExport = true;
  1594. }
  1595. });
  1596. node.kind = kind || "CommonJS";
  1597. return this.finishNode(node, "DeclareModule");
  1598. }
  1599. flowParseDeclareExportDeclaration(node, insideModule) {
  1600. this.expect(types._export);
  1601. if (this.eat(types._default)) {
  1602. if (this.match(types._function) || this.match(types._class)) {
  1603. node.declaration = this.flowParseDeclare(this.startNode());
  1604. } else {
  1605. node.declaration = this.flowParseType();
  1606. this.semicolon();
  1607. }
  1608. node.default = true;
  1609. return this.finishNode(node, "DeclareExportDeclaration");
  1610. } else {
  1611. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1612. const label = this.state.value;
  1613. const suggestion = exportSuggestions[label];
  1614. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1615. }
  1616. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1617. node.declaration = this.flowParseDeclare(this.startNode());
  1618. node.default = false;
  1619. return this.finishNode(node, "DeclareExportDeclaration");
  1620. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1621. node = this.parseExport(node);
  1622. if (node.type === "ExportNamedDeclaration") {
  1623. node.type = "ExportDeclaration";
  1624. node.default = false;
  1625. delete node.exportKind;
  1626. }
  1627. node.type = "Declare" + node.type;
  1628. return node;
  1629. }
  1630. }
  1631. throw this.unexpected();
  1632. }
  1633. flowParseDeclareModuleExports(node) {
  1634. this.next();
  1635. this.expectContextual("exports");
  1636. node.typeAnnotation = this.flowParseTypeAnnotation();
  1637. this.semicolon();
  1638. return this.finishNode(node, "DeclareModuleExports");
  1639. }
  1640. flowParseDeclareTypeAlias(node) {
  1641. this.next();
  1642. this.flowParseTypeAlias(node);
  1643. node.type = "DeclareTypeAlias";
  1644. return node;
  1645. }
  1646. flowParseDeclareOpaqueType(node) {
  1647. this.next();
  1648. this.flowParseOpaqueType(node, true);
  1649. node.type = "DeclareOpaqueType";
  1650. return node;
  1651. }
  1652. flowParseDeclareInterface(node) {
  1653. this.next();
  1654. this.flowParseInterfaceish(node);
  1655. return this.finishNode(node, "DeclareInterface");
  1656. }
  1657. flowParseInterfaceish(node, isClass = false) {
  1658. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1659. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1660. if (this.isRelational("<")) {
  1661. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1662. } else {
  1663. node.typeParameters = null;
  1664. }
  1665. node.extends = [];
  1666. node.implements = [];
  1667. node.mixins = [];
  1668. if (this.eat(types._extends)) {
  1669. do {
  1670. node.extends.push(this.flowParseInterfaceExtends());
  1671. } while (!isClass && this.eat(types.comma));
  1672. }
  1673. if (this.isContextual("mixins")) {
  1674. this.next();
  1675. do {
  1676. node.mixins.push(this.flowParseInterfaceExtends());
  1677. } while (this.eat(types.comma));
  1678. }
  1679. if (this.isContextual("implements")) {
  1680. this.next();
  1681. do {
  1682. node.implements.push(this.flowParseInterfaceExtends());
  1683. } while (this.eat(types.comma));
  1684. }
  1685. node.body = this.flowParseObjectType({
  1686. allowStatic: isClass,
  1687. allowExact: false,
  1688. allowSpread: false,
  1689. allowProto: isClass,
  1690. allowInexact: false
  1691. });
  1692. }
  1693. flowParseInterfaceExtends() {
  1694. const node = this.startNode();
  1695. node.id = this.flowParseQualifiedTypeIdentifier();
  1696. if (this.isRelational("<")) {
  1697. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1698. } else {
  1699. node.typeParameters = null;
  1700. }
  1701. return this.finishNode(node, "InterfaceExtends");
  1702. }
  1703. flowParseInterface(node) {
  1704. this.flowParseInterfaceish(node);
  1705. return this.finishNode(node, "InterfaceDeclaration");
  1706. }
  1707. checkNotUnderscore(word) {
  1708. if (word === "_") {
  1709. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1710. }
  1711. }
  1712. checkReservedType(word, startLoc, declaration) {
  1713. if (!reservedTypes.has(word)) return;
  1714. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1715. }
  1716. flowParseRestrictedIdentifier(liberal, declaration) {
  1717. this.checkReservedType(this.state.value, this.state.start, declaration);
  1718. return this.parseIdentifier(liberal);
  1719. }
  1720. flowParseTypeAlias(node) {
  1721. node.id = this.flowParseRestrictedIdentifier(false, true);
  1722. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1723. if (this.isRelational("<")) {
  1724. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1725. } else {
  1726. node.typeParameters = null;
  1727. }
  1728. node.right = this.flowParseTypeInitialiser(types.eq);
  1729. this.semicolon();
  1730. return this.finishNode(node, "TypeAlias");
  1731. }
  1732. flowParseOpaqueType(node, declare) {
  1733. this.expectContextual("type");
  1734. node.id = this.flowParseRestrictedIdentifier(true, true);
  1735. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1736. if (this.isRelational("<")) {
  1737. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1738. } else {
  1739. node.typeParameters = null;
  1740. }
  1741. node.supertype = null;
  1742. if (this.match(types.colon)) {
  1743. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1744. }
  1745. node.impltype = null;
  1746. if (!declare) {
  1747. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1748. }
  1749. this.semicolon();
  1750. return this.finishNode(node, "OpaqueType");
  1751. }
  1752. flowParseTypeParameter(requireDefault = false) {
  1753. const nodeStart = this.state.start;
  1754. const node = this.startNode();
  1755. const variance = this.flowParseVariance();
  1756. const ident = this.flowParseTypeAnnotatableIdentifier();
  1757. node.name = ident.name;
  1758. node.variance = variance;
  1759. node.bound = ident.typeAnnotation;
  1760. if (this.match(types.eq)) {
  1761. this.eat(types.eq);
  1762. node.default = this.flowParseType();
  1763. } else {
  1764. if (requireDefault) {
  1765. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1766. }
  1767. }
  1768. return this.finishNode(node, "TypeParameter");
  1769. }
  1770. flowParseTypeParameterDeclaration() {
  1771. const oldInType = this.state.inType;
  1772. const node = this.startNode();
  1773. node.params = [];
  1774. this.state.inType = true;
  1775. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1776. this.next();
  1777. } else {
  1778. this.unexpected();
  1779. }
  1780. let defaultRequired = false;
  1781. do {
  1782. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1783. node.params.push(typeParameter);
  1784. if (typeParameter.default) {
  1785. defaultRequired = true;
  1786. }
  1787. if (!this.isRelational(">")) {
  1788. this.expect(types.comma);
  1789. }
  1790. } while (!this.isRelational(">"));
  1791. this.expectRelational(">");
  1792. this.state.inType = oldInType;
  1793. return this.finishNode(node, "TypeParameterDeclaration");
  1794. }
  1795. flowParseTypeParameterInstantiation() {
  1796. const node = this.startNode();
  1797. const oldInType = this.state.inType;
  1798. node.params = [];
  1799. this.state.inType = true;
  1800. this.expectRelational("<");
  1801. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1802. this.state.noAnonFunctionType = false;
  1803. while (!this.isRelational(">")) {
  1804. node.params.push(this.flowParseType());
  1805. if (!this.isRelational(">")) {
  1806. this.expect(types.comma);
  1807. }
  1808. }
  1809. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1810. this.expectRelational(">");
  1811. this.state.inType = oldInType;
  1812. return this.finishNode(node, "TypeParameterInstantiation");
  1813. }
  1814. flowParseTypeParameterInstantiationCallOrNew() {
  1815. const node = this.startNode();
  1816. const oldInType = this.state.inType;
  1817. node.params = [];
  1818. this.state.inType = true;
  1819. this.expectRelational("<");
  1820. while (!this.isRelational(">")) {
  1821. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1822. if (!this.isRelational(">")) {
  1823. this.expect(types.comma);
  1824. }
  1825. }
  1826. this.expectRelational(">");
  1827. this.state.inType = oldInType;
  1828. return this.finishNode(node, "TypeParameterInstantiation");
  1829. }
  1830. flowParseInterfaceType() {
  1831. const node = this.startNode();
  1832. this.expectContextual("interface");
  1833. node.extends = [];
  1834. if (this.eat(types._extends)) {
  1835. do {
  1836. node.extends.push(this.flowParseInterfaceExtends());
  1837. } while (this.eat(types.comma));
  1838. }
  1839. node.body = this.flowParseObjectType({
  1840. allowStatic: false,
  1841. allowExact: false,
  1842. allowSpread: false,
  1843. allowProto: false,
  1844. allowInexact: false
  1845. });
  1846. return this.finishNode(node, "InterfaceTypeAnnotation");
  1847. }
  1848. flowParseObjectPropertyKey() {
  1849. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1850. }
  1851. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1852. node.static = isStatic;
  1853. if (this.lookahead().type === types.colon) {
  1854. node.id = this.flowParseObjectPropertyKey();
  1855. node.key = this.flowParseTypeInitialiser();
  1856. } else {
  1857. node.id = null;
  1858. node.key = this.flowParseType();
  1859. }
  1860. this.expect(types.bracketR);
  1861. node.value = this.flowParseTypeInitialiser();
  1862. node.variance = variance;
  1863. return this.finishNode(node, "ObjectTypeIndexer");
  1864. }
  1865. flowParseObjectTypeInternalSlot(node, isStatic) {
  1866. node.static = isStatic;
  1867. node.id = this.flowParseObjectPropertyKey();
  1868. this.expect(types.bracketR);
  1869. this.expect(types.bracketR);
  1870. if (this.isRelational("<") || this.match(types.parenL)) {
  1871. node.method = true;
  1872. node.optional = false;
  1873. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1874. } else {
  1875. node.method = false;
  1876. if (this.eat(types.question)) {
  1877. node.optional = true;
  1878. }
  1879. node.value = this.flowParseTypeInitialiser();
  1880. }
  1881. return this.finishNode(node, "ObjectTypeInternalSlot");
  1882. }
  1883. flowParseObjectTypeMethodish(node) {
  1884. node.params = [];
  1885. node.rest = null;
  1886. node.typeParameters = null;
  1887. node.this = null;
  1888. if (this.isRelational("<")) {
  1889. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1890. }
  1891. this.expect(types.parenL);
  1892. if (this.match(types._this)) {
  1893. node.this = this.flowParseFunctionTypeParam(true);
  1894. node.this.name = null;
  1895. if (!this.match(types.parenR)) {
  1896. this.expect(types.comma);
  1897. }
  1898. }
  1899. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1900. node.params.push(this.flowParseFunctionTypeParam(false));
  1901. if (!this.match(types.parenR)) {
  1902. this.expect(types.comma);
  1903. }
  1904. }
  1905. if (this.eat(types.ellipsis)) {
  1906. node.rest = this.flowParseFunctionTypeParam(false);
  1907. }
  1908. this.expect(types.parenR);
  1909. node.returnType = this.flowParseTypeInitialiser();
  1910. return this.finishNode(node, "FunctionTypeAnnotation");
  1911. }
  1912. flowParseObjectTypeCallProperty(node, isStatic) {
  1913. const valueNode = this.startNode();
  1914. node.static = isStatic;
  1915. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1916. return this.finishNode(node, "ObjectTypeCallProperty");
  1917. }
  1918. flowParseObjectType({
  1919. allowStatic,
  1920. allowExact,
  1921. allowSpread,
  1922. allowProto,
  1923. allowInexact
  1924. }) {
  1925. const oldInType = this.state.inType;
  1926. this.state.inType = true;
  1927. const nodeStart = this.startNode();
  1928. nodeStart.callProperties = [];
  1929. nodeStart.properties = [];
  1930. nodeStart.indexers = [];
  1931. nodeStart.internalSlots = [];
  1932. let endDelim;
  1933. let exact;
  1934. let inexact = false;
  1935. if (allowExact && this.match(types.braceBarL)) {
  1936. this.expect(types.braceBarL);
  1937. endDelim = types.braceBarR;
  1938. exact = true;
  1939. } else {
  1940. this.expect(types.braceL);
  1941. endDelim = types.braceR;
  1942. exact = false;
  1943. }
  1944. nodeStart.exact = exact;
  1945. while (!this.match(endDelim)) {
  1946. let isStatic = false;
  1947. let protoStart = null;
  1948. let inexactStart = null;
  1949. const node = this.startNode();
  1950. if (allowProto && this.isContextual("proto")) {
  1951. const lookahead = this.lookahead();
  1952. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1953. this.next();
  1954. protoStart = this.state.start;
  1955. allowStatic = false;
  1956. }
  1957. }
  1958. if (allowStatic && this.isContextual("static")) {
  1959. const lookahead = this.lookahead();
  1960. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1961. this.next();
  1962. isStatic = true;
  1963. }
  1964. }
  1965. const variance = this.flowParseVariance();
  1966. if (this.eat(types.bracketL)) {
  1967. if (protoStart != null) {
  1968. this.unexpected(protoStart);
  1969. }
  1970. if (this.eat(types.bracketL)) {
  1971. if (variance) {
  1972. this.unexpected(variance.start);
  1973. }
  1974. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1975. } else {
  1976. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1977. }
  1978. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1979. if (protoStart != null) {
  1980. this.unexpected(protoStart);
  1981. }
  1982. if (variance) {
  1983. this.unexpected(variance.start);
  1984. }
  1985. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1986. } else {
  1987. let kind = "init";
  1988. if (this.isContextual("get") || this.isContextual("set")) {
  1989. const lookahead = this.lookahead();
  1990. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1991. kind = this.state.value;
  1992. this.next();
  1993. }
  1994. }
  1995. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1996. if (propOrInexact === null) {
  1997. inexact = true;
  1998. inexactStart = this.state.lastTokStart;
  1999. } else {
  2000. nodeStart.properties.push(propOrInexact);
  2001. }
  2002. }
  2003. this.flowObjectTypeSemicolon();
  2004. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  2005. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  2006. }
  2007. }
  2008. this.expect(endDelim);
  2009. if (allowSpread) {
  2010. nodeStart.inexact = inexact;
  2011. }
  2012. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  2013. this.state.inType = oldInType;
  2014. return out;
  2015. }
  2016. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  2017. if (this.eat(types.ellipsis)) {
  2018. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  2019. if (isInexactToken) {
  2020. if (!allowSpread) {
  2021. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  2022. } else if (!allowInexact) {
  2023. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  2024. }
  2025. if (variance) {
  2026. this.raise(variance.start, FlowErrors.InexactVariance);
  2027. }
  2028. return null;
  2029. }
  2030. if (!allowSpread) {
  2031. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  2032. }
  2033. if (protoStart != null) {
  2034. this.unexpected(protoStart);
  2035. }
  2036. if (variance) {
  2037. this.raise(variance.start, FlowErrors.SpreadVariance);
  2038. }
  2039. node.argument = this.flowParseType();
  2040. return this.finishNode(node, "ObjectTypeSpreadProperty");
  2041. } else {
  2042. node.key = this.flowParseObjectPropertyKey();
  2043. node.static = isStatic;
  2044. node.proto = protoStart != null;
  2045. node.kind = kind;
  2046. let optional = false;
  2047. if (this.isRelational("<") || this.match(types.parenL)) {
  2048. node.method = true;
  2049. if (protoStart != null) {
  2050. this.unexpected(protoStart);
  2051. }
  2052. if (variance) {
  2053. this.unexpected(variance.start);
  2054. }
  2055. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  2056. if (kind === "get" || kind === "set") {
  2057. this.flowCheckGetterSetterParams(node);
  2058. }
  2059. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  2060. this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor);
  2061. }
  2062. } else {
  2063. if (kind !== "init") this.unexpected();
  2064. node.method = false;
  2065. if (this.eat(types.question)) {
  2066. optional = true;
  2067. }
  2068. node.value = this.flowParseTypeInitialiser();
  2069. node.variance = variance;
  2070. }
  2071. node.optional = optional;
  2072. return this.finishNode(node, "ObjectTypeProperty");
  2073. }
  2074. }
  2075. flowCheckGetterSetterParams(property) {
  2076. const paramCount = property.kind === "get" ? 0 : 1;
  2077. const start = property.start;
  2078. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  2079. if (property.value.this) {
  2080. this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam);
  2081. }
  2082. if (length !== paramCount) {
  2083. if (property.kind === "get") {
  2084. this.raise(start, ErrorMessages.BadGetterArity);
  2085. } else {
  2086. this.raise(start, ErrorMessages.BadSetterArity);
  2087. }
  2088. }
  2089. if (property.kind === "set" && property.value.rest) {
  2090. this.raise(start, ErrorMessages.BadSetterRestParameter);
  2091. }
  2092. }
  2093. flowObjectTypeSemicolon() {
  2094. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  2095. this.unexpected();
  2096. }
  2097. }
  2098. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  2099. startPos = startPos || this.state.start;
  2100. startLoc = startLoc || this.state.startLoc;
  2101. let node = id || this.flowParseRestrictedIdentifier(true);
  2102. while (this.eat(types.dot)) {
  2103. const node2 = this.startNodeAt(startPos, startLoc);
  2104. node2.qualification = node;
  2105. node2.id = this.flowParseRestrictedIdentifier(true);
  2106. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  2107. }
  2108. return node;
  2109. }
  2110. flowParseGenericType(startPos, startLoc, id) {
  2111. const node = this.startNodeAt(startPos, startLoc);
  2112. node.typeParameters = null;
  2113. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  2114. if (this.isRelational("<")) {
  2115. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2116. }
  2117. return this.finishNode(node, "GenericTypeAnnotation");
  2118. }
  2119. flowParseTypeofType() {
  2120. const node = this.startNode();
  2121. this.expect(types._typeof);
  2122. node.argument = this.flowParsePrimaryType();
  2123. return this.finishNode(node, "TypeofTypeAnnotation");
  2124. }
  2125. flowParseTupleType() {
  2126. const node = this.startNode();
  2127. node.types = [];
  2128. this.expect(types.bracketL);
  2129. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  2130. node.types.push(this.flowParseType());
  2131. if (this.match(types.bracketR)) break;
  2132. this.expect(types.comma);
  2133. }
  2134. this.expect(types.bracketR);
  2135. return this.finishNode(node, "TupleTypeAnnotation");
  2136. }
  2137. flowParseFunctionTypeParam(first) {
  2138. let name = null;
  2139. let optional = false;
  2140. let typeAnnotation = null;
  2141. const node = this.startNode();
  2142. const lh = this.lookahead();
  2143. const isThis = this.state.type === types._this;
  2144. if (lh.type === types.colon || lh.type === types.question) {
  2145. if (isThis && !first) {
  2146. this.raise(node.start, FlowErrors.ThisParamMustBeFirst);
  2147. }
  2148. name = this.parseIdentifier(isThis);
  2149. if (this.eat(types.question)) {
  2150. optional = true;
  2151. if (isThis) {
  2152. this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional);
  2153. }
  2154. }
  2155. typeAnnotation = this.flowParseTypeInitialiser();
  2156. } else {
  2157. typeAnnotation = this.flowParseType();
  2158. }
  2159. node.name = name;
  2160. node.optional = optional;
  2161. node.typeAnnotation = typeAnnotation;
  2162. return this.finishNode(node, "FunctionTypeParam");
  2163. }
  2164. reinterpretTypeAsFunctionTypeParam(type) {
  2165. const node = this.startNodeAt(type.start, type.loc.start);
  2166. node.name = null;
  2167. node.optional = false;
  2168. node.typeAnnotation = type;
  2169. return this.finishNode(node, "FunctionTypeParam");
  2170. }
  2171. flowParseFunctionTypeParams(params = []) {
  2172. let rest = null;
  2173. let _this = null;
  2174. if (this.match(types._this)) {
  2175. _this = this.flowParseFunctionTypeParam(true);
  2176. _this.name = null;
  2177. if (!this.match(types.parenR)) {
  2178. this.expect(types.comma);
  2179. }
  2180. }
  2181. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  2182. params.push(this.flowParseFunctionTypeParam(false));
  2183. if (!this.match(types.parenR)) {
  2184. this.expect(types.comma);
  2185. }
  2186. }
  2187. if (this.eat(types.ellipsis)) {
  2188. rest = this.flowParseFunctionTypeParam(false);
  2189. }
  2190. return {
  2191. params,
  2192. rest,
  2193. _this
  2194. };
  2195. }
  2196. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  2197. switch (id.name) {
  2198. case "any":
  2199. return this.finishNode(node, "AnyTypeAnnotation");
  2200. case "bool":
  2201. case "boolean":
  2202. return this.finishNode(node, "BooleanTypeAnnotation");
  2203. case "mixed":
  2204. return this.finishNode(node, "MixedTypeAnnotation");
  2205. case "empty":
  2206. return this.finishNode(node, "EmptyTypeAnnotation");
  2207. case "number":
  2208. return this.finishNode(node, "NumberTypeAnnotation");
  2209. case "string":
  2210. return this.finishNode(node, "StringTypeAnnotation");
  2211. case "symbol":
  2212. return this.finishNode(node, "SymbolTypeAnnotation");
  2213. default:
  2214. this.checkNotUnderscore(id.name);
  2215. return this.flowParseGenericType(startPos, startLoc, id);
  2216. }
  2217. }
  2218. flowParsePrimaryType() {
  2219. const startPos = this.state.start;
  2220. const startLoc = this.state.startLoc;
  2221. const node = this.startNode();
  2222. let tmp;
  2223. let type;
  2224. let isGroupedType = false;
  2225. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2226. switch (this.state.type) {
  2227. case types.name:
  2228. if (this.isContextual("interface")) {
  2229. return this.flowParseInterfaceType();
  2230. }
  2231. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  2232. case types.braceL:
  2233. return this.flowParseObjectType({
  2234. allowStatic: false,
  2235. allowExact: false,
  2236. allowSpread: true,
  2237. allowProto: false,
  2238. allowInexact: true
  2239. });
  2240. case types.braceBarL:
  2241. return this.flowParseObjectType({
  2242. allowStatic: false,
  2243. allowExact: true,
  2244. allowSpread: true,
  2245. allowProto: false,
  2246. allowInexact: false
  2247. });
  2248. case types.bracketL:
  2249. this.state.noAnonFunctionType = false;
  2250. type = this.flowParseTupleType();
  2251. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2252. return type;
  2253. case types.relational:
  2254. if (this.state.value === "<") {
  2255. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2256. this.expect(types.parenL);
  2257. tmp = this.flowParseFunctionTypeParams();
  2258. node.params = tmp.params;
  2259. node.rest = tmp.rest;
  2260. node.this = tmp._this;
  2261. this.expect(types.parenR);
  2262. this.expect(types.arrow);
  2263. node.returnType = this.flowParseType();
  2264. return this.finishNode(node, "FunctionTypeAnnotation");
  2265. }
  2266. break;
  2267. case types.parenL:
  2268. this.next();
  2269. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  2270. if (this.match(types.name) || this.match(types._this)) {
  2271. const token = this.lookahead().type;
  2272. isGroupedType = token !== types.question && token !== types.colon;
  2273. } else {
  2274. isGroupedType = true;
  2275. }
  2276. }
  2277. if (isGroupedType) {
  2278. this.state.noAnonFunctionType = false;
  2279. type = this.flowParseType();
  2280. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2281. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  2282. this.expect(types.parenR);
  2283. return type;
  2284. } else {
  2285. this.eat(types.comma);
  2286. }
  2287. }
  2288. if (type) {
  2289. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  2290. } else {
  2291. tmp = this.flowParseFunctionTypeParams();
  2292. }
  2293. node.params = tmp.params;
  2294. node.rest = tmp.rest;
  2295. node.this = tmp._this;
  2296. this.expect(types.parenR);
  2297. this.expect(types.arrow);
  2298. node.returnType = this.flowParseType();
  2299. node.typeParameters = null;
  2300. return this.finishNode(node, "FunctionTypeAnnotation");
  2301. case types.string:
  2302. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  2303. case types._true:
  2304. case types._false:
  2305. node.value = this.match(types._true);
  2306. this.next();
  2307. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  2308. case types.plusMin:
  2309. if (this.state.value === "-") {
  2310. this.next();
  2311. if (this.match(types.num)) {
  2312. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  2313. }
  2314. if (this.match(types.bigint)) {
  2315. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  2316. }
  2317. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  2318. }
  2319. throw this.unexpected();
  2320. case types.num:
  2321. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  2322. case types.bigint:
  2323. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  2324. case types._void:
  2325. this.next();
  2326. return this.finishNode(node, "VoidTypeAnnotation");
  2327. case types._null:
  2328. this.next();
  2329. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2330. case types._this:
  2331. this.next();
  2332. return this.finishNode(node, "ThisTypeAnnotation");
  2333. case types.star:
  2334. this.next();
  2335. return this.finishNode(node, "ExistsTypeAnnotation");
  2336. default:
  2337. if (this.state.type.keyword === "typeof") {
  2338. return this.flowParseTypeofType();
  2339. } else if (this.state.type.keyword) {
  2340. const label = this.state.type.label;
  2341. this.next();
  2342. return super.createIdentifier(node, label);
  2343. }
  2344. }
  2345. throw this.unexpected();
  2346. }
  2347. flowParsePostfixType() {
  2348. const startPos = this.state.start,
  2349. startLoc = this.state.startLoc;
  2350. let type = this.flowParsePrimaryType();
  2351. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2352. const node = this.startNodeAt(startPos, startLoc);
  2353. node.elementType = type;
  2354. this.expect(types.bracketL);
  2355. this.expect(types.bracketR);
  2356. type = this.finishNode(node, "ArrayTypeAnnotation");
  2357. }
  2358. return type;
  2359. }
  2360. flowParsePrefixType() {
  2361. const node = this.startNode();
  2362. if (this.eat(types.question)) {
  2363. node.typeAnnotation = this.flowParsePrefixType();
  2364. return this.finishNode(node, "NullableTypeAnnotation");
  2365. } else {
  2366. return this.flowParsePostfixType();
  2367. }
  2368. }
  2369. flowParseAnonFunctionWithoutParens() {
  2370. const param = this.flowParsePrefixType();
  2371. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2372. const node = this.startNodeAt(param.start, param.loc.start);
  2373. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2374. node.rest = null;
  2375. node.this = null;
  2376. node.returnType = this.flowParseType();
  2377. node.typeParameters = null;
  2378. return this.finishNode(node, "FunctionTypeAnnotation");
  2379. }
  2380. return param;
  2381. }
  2382. flowParseIntersectionType() {
  2383. const node = this.startNode();
  2384. this.eat(types.bitwiseAND);
  2385. const type = this.flowParseAnonFunctionWithoutParens();
  2386. node.types = [type];
  2387. while (this.eat(types.bitwiseAND)) {
  2388. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2389. }
  2390. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2391. }
  2392. flowParseUnionType() {
  2393. const node = this.startNode();
  2394. this.eat(types.bitwiseOR);
  2395. const type = this.flowParseIntersectionType();
  2396. node.types = [type];
  2397. while (this.eat(types.bitwiseOR)) {
  2398. node.types.push(this.flowParseIntersectionType());
  2399. }
  2400. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2401. }
  2402. flowParseType() {
  2403. const oldInType = this.state.inType;
  2404. this.state.inType = true;
  2405. const type = this.flowParseUnionType();
  2406. this.state.inType = oldInType;
  2407. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2408. return type;
  2409. }
  2410. flowParseTypeOrImplicitInstantiation() {
  2411. if (this.state.type === types.name && this.state.value === "_") {
  2412. const startPos = this.state.start;
  2413. const startLoc = this.state.startLoc;
  2414. const node = this.parseIdentifier();
  2415. return this.flowParseGenericType(startPos, startLoc, node);
  2416. } else {
  2417. return this.flowParseType();
  2418. }
  2419. }
  2420. flowParseTypeAnnotation() {
  2421. const node = this.startNode();
  2422. node.typeAnnotation = this.flowParseTypeInitialiser();
  2423. return this.finishNode(node, "TypeAnnotation");
  2424. }
  2425. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2426. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2427. if (this.match(types.colon)) {
  2428. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2429. this.resetEndLocation(ident);
  2430. }
  2431. return ident;
  2432. }
  2433. typeCastToParameter(node) {
  2434. node.expression.typeAnnotation = node.typeAnnotation;
  2435. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2436. return node.expression;
  2437. }
  2438. flowParseVariance() {
  2439. let variance = null;
  2440. if (this.match(types.plusMin)) {
  2441. variance = this.startNode();
  2442. if (this.state.value === "+") {
  2443. variance.kind = "plus";
  2444. } else {
  2445. variance.kind = "minus";
  2446. }
  2447. this.next();
  2448. this.finishNode(variance, "Variance");
  2449. }
  2450. return variance;
  2451. }
  2452. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2453. if (allowExpressionBody) {
  2454. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2455. }
  2456. return super.parseFunctionBody(node, false, isMethod);
  2457. }
  2458. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2459. if (this.match(types.colon)) {
  2460. const typeNode = this.startNode();
  2461. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2462. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2463. }
  2464. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2465. }
  2466. parseStatement(context, topLevel) {
  2467. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2468. const lookahead = this.lookahead();
  2469. if (lookahead.type === types.name || isKeyword(lookahead.value)) {
  2470. const node = this.startNode();
  2471. this.next();
  2472. return this.flowParseInterface(node);
  2473. }
  2474. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2475. const node = this.startNode();
  2476. this.next();
  2477. return this.flowParseEnumDeclaration(node);
  2478. }
  2479. const stmt = super.parseStatement(context, topLevel);
  2480. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2481. this.flowPragma = null;
  2482. }
  2483. return stmt;
  2484. }
  2485. parseExpressionStatement(node, expr) {
  2486. if (expr.type === "Identifier") {
  2487. if (expr.name === "declare") {
  2488. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2489. return this.flowParseDeclare(node);
  2490. }
  2491. } else if (this.match(types.name)) {
  2492. if (expr.name === "interface") {
  2493. return this.flowParseInterface(node);
  2494. } else if (expr.name === "type") {
  2495. return this.flowParseTypeAlias(node);
  2496. } else if (expr.name === "opaque") {
  2497. return this.flowParseOpaqueType(node, false);
  2498. }
  2499. }
  2500. }
  2501. return super.parseExpressionStatement(node, expr);
  2502. }
  2503. shouldParseExportDeclaration() {
  2504. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2505. }
  2506. isExportDefaultSpecifier() {
  2507. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2508. return false;
  2509. }
  2510. return super.isExportDefaultSpecifier();
  2511. }
  2512. parseExportDefaultExpression() {
  2513. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2514. const node = this.startNode();
  2515. this.next();
  2516. return this.flowParseEnumDeclaration(node);
  2517. }
  2518. return super.parseExportDefaultExpression();
  2519. }
  2520. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  2521. if (!this.match(types.question)) return expr;
  2522. if (refNeedsArrowPos) {
  2523. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  2524. if (!result.node) {
  2525. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2526. return expr;
  2527. }
  2528. if (result.error) this.state = result.failState;
  2529. return result.node;
  2530. }
  2531. this.expect(types.question);
  2532. const state = this.state.clone();
  2533. const originalNoArrowAt = this.state.noArrowAt;
  2534. const node = this.startNodeAt(startPos, startLoc);
  2535. let {
  2536. consequent,
  2537. failed
  2538. } = this.tryParseConditionalConsequent();
  2539. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2540. if (failed || invalid.length > 0) {
  2541. const noArrowAt = [...originalNoArrowAt];
  2542. if (invalid.length > 0) {
  2543. this.state = state;
  2544. this.state.noArrowAt = noArrowAt;
  2545. for (let i = 0; i < invalid.length; i++) {
  2546. noArrowAt.push(invalid[i].start);
  2547. }
  2548. ({
  2549. consequent,
  2550. failed
  2551. } = this.tryParseConditionalConsequent());
  2552. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2553. }
  2554. if (failed && valid.length > 1) {
  2555. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2556. }
  2557. if (failed && valid.length === 1) {
  2558. this.state = state;
  2559. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2560. ({
  2561. consequent,
  2562. failed
  2563. } = this.tryParseConditionalConsequent());
  2564. }
  2565. }
  2566. this.getArrowLikeExpressions(consequent, true);
  2567. this.state.noArrowAt = originalNoArrowAt;
  2568. this.expect(types.colon);
  2569. node.test = expr;
  2570. node.consequent = consequent;
  2571. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  2572. return this.finishNode(node, "ConditionalExpression");
  2573. }
  2574. tryParseConditionalConsequent() {
  2575. this.state.noArrowParamsConversionAt.push(this.state.start);
  2576. const consequent = this.parseMaybeAssignAllowIn();
  2577. const failed = !this.match(types.colon);
  2578. this.state.noArrowParamsConversionAt.pop();
  2579. return {
  2580. consequent,
  2581. failed
  2582. };
  2583. }
  2584. getArrowLikeExpressions(node, disallowInvalid) {
  2585. const stack = [node];
  2586. const arrows = [];
  2587. while (stack.length !== 0) {
  2588. const node = stack.pop();
  2589. if (node.type === "ArrowFunctionExpression") {
  2590. if (node.typeParameters || !node.returnType) {
  2591. this.finishArrowValidation(node);
  2592. } else {
  2593. arrows.push(node);
  2594. }
  2595. stack.push(node.body);
  2596. } else if (node.type === "ConditionalExpression") {
  2597. stack.push(node.consequent);
  2598. stack.push(node.alternate);
  2599. }
  2600. }
  2601. if (disallowInvalid) {
  2602. arrows.forEach(node => this.finishArrowValidation(node));
  2603. return [arrows, []];
  2604. }
  2605. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2606. }
  2607. finishArrowValidation(node) {
  2608. var _node$extra;
  2609. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  2610. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2611. super.checkParams(node, false, true);
  2612. this.scope.exit();
  2613. }
  2614. forwardNoArrowParamsConversionAt(node, parse) {
  2615. let result;
  2616. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2617. this.state.noArrowParamsConversionAt.push(this.state.start);
  2618. result = parse();
  2619. this.state.noArrowParamsConversionAt.pop();
  2620. } else {
  2621. result = parse();
  2622. }
  2623. return result;
  2624. }
  2625. parseParenItem(node, startPos, startLoc) {
  2626. node = super.parseParenItem(node, startPos, startLoc);
  2627. if (this.eat(types.question)) {
  2628. node.optional = true;
  2629. this.resetEndLocation(node);
  2630. }
  2631. if (this.match(types.colon)) {
  2632. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2633. typeCastNode.expression = node;
  2634. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2635. return this.finishNode(typeCastNode, "TypeCastExpression");
  2636. }
  2637. return node;
  2638. }
  2639. assertModuleNodeAllowed(node) {
  2640. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2641. return;
  2642. }
  2643. super.assertModuleNodeAllowed(node);
  2644. }
  2645. parseExport(node) {
  2646. const decl = super.parseExport(node);
  2647. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2648. decl.exportKind = decl.exportKind || "value";
  2649. }
  2650. return decl;
  2651. }
  2652. parseExportDeclaration(node) {
  2653. if (this.isContextual("type")) {
  2654. node.exportKind = "type";
  2655. const declarationNode = this.startNode();
  2656. this.next();
  2657. if (this.match(types.braceL)) {
  2658. node.specifiers = this.parseExportSpecifiers();
  2659. this.parseExportFrom(node);
  2660. return null;
  2661. } else {
  2662. return this.flowParseTypeAlias(declarationNode);
  2663. }
  2664. } else if (this.isContextual("opaque")) {
  2665. node.exportKind = "type";
  2666. const declarationNode = this.startNode();
  2667. this.next();
  2668. return this.flowParseOpaqueType(declarationNode, false);
  2669. } else if (this.isContextual("interface")) {
  2670. node.exportKind = "type";
  2671. const declarationNode = this.startNode();
  2672. this.next();
  2673. return this.flowParseInterface(declarationNode);
  2674. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2675. node.exportKind = "value";
  2676. const declarationNode = this.startNode();
  2677. this.next();
  2678. return this.flowParseEnumDeclaration(declarationNode);
  2679. } else {
  2680. return super.parseExportDeclaration(node);
  2681. }
  2682. }
  2683. eatExportStar(node) {
  2684. if (super.eatExportStar(...arguments)) return true;
  2685. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2686. node.exportKind = "type";
  2687. this.next();
  2688. this.next();
  2689. return true;
  2690. }
  2691. return false;
  2692. }
  2693. maybeParseExportNamespaceSpecifier(node) {
  2694. const pos = this.state.start;
  2695. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2696. if (hasNamespace && node.exportKind === "type") {
  2697. this.unexpected(pos);
  2698. }
  2699. return hasNamespace;
  2700. }
  2701. parseClassId(node, isStatement, optionalId) {
  2702. super.parseClassId(node, isStatement, optionalId);
  2703. if (this.isRelational("<")) {
  2704. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2705. }
  2706. }
  2707. parseClassMember(classBody, member, state) {
  2708. const pos = this.state.start;
  2709. if (this.isContextual("declare")) {
  2710. if (this.parseClassMemberFromModifier(classBody, member)) {
  2711. return;
  2712. }
  2713. member.declare = true;
  2714. }
  2715. super.parseClassMember(classBody, member, state);
  2716. if (member.declare) {
  2717. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  2718. this.raise(pos, FlowErrors.DeclareClassElement);
  2719. } else if (member.value) {
  2720. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2721. }
  2722. }
  2723. }
  2724. getTokenFromCode(code) {
  2725. const next = this.input.charCodeAt(this.state.pos + 1);
  2726. if (code === 123 && next === 124) {
  2727. return this.finishOp(types.braceBarL, 2);
  2728. } else if (this.state.inType && (code === 62 || code === 60)) {
  2729. return this.finishOp(types.relational, 1);
  2730. } else if (this.state.inType && code === 63) {
  2731. return this.finishOp(types.question, 1);
  2732. } else if (isIteratorStart(code, next)) {
  2733. this.state.isIterator = true;
  2734. return super.readWord();
  2735. } else {
  2736. return super.getTokenFromCode(code);
  2737. }
  2738. }
  2739. isAssignable(node, isBinding) {
  2740. switch (node.type) {
  2741. case "Identifier":
  2742. case "ObjectPattern":
  2743. case "ArrayPattern":
  2744. case "AssignmentPattern":
  2745. return true;
  2746. case "ObjectExpression":
  2747. {
  2748. const last = node.properties.length - 1;
  2749. return node.properties.every((prop, i) => {
  2750. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2751. });
  2752. }
  2753. case "ObjectProperty":
  2754. return this.isAssignable(node.value);
  2755. case "SpreadElement":
  2756. return this.isAssignable(node.argument);
  2757. case "ArrayExpression":
  2758. return node.elements.every(element => this.isAssignable(element));
  2759. case "AssignmentExpression":
  2760. return node.operator === "=";
  2761. case "ParenthesizedExpression":
  2762. case "TypeCastExpression":
  2763. return this.isAssignable(node.expression);
  2764. case "MemberExpression":
  2765. case "OptionalMemberExpression":
  2766. return !isBinding;
  2767. default:
  2768. return false;
  2769. }
  2770. }
  2771. toAssignable(node, isLHS = false) {
  2772. if (node.type === "TypeCastExpression") {
  2773. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  2774. } else {
  2775. return super.toAssignable(node, isLHS);
  2776. }
  2777. }
  2778. toAssignableList(exprList, trailingCommaPos, isLHS) {
  2779. for (let i = 0; i < exprList.length; i++) {
  2780. const expr = exprList[i];
  2781. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  2782. exprList[i] = this.typeCastToParameter(expr);
  2783. }
  2784. }
  2785. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  2786. }
  2787. toReferencedList(exprList, isParenthesizedExpr) {
  2788. for (let i = 0; i < exprList.length; i++) {
  2789. var _expr$extra;
  2790. const expr = exprList[i];
  2791. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2792. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2793. }
  2794. }
  2795. return exprList;
  2796. }
  2797. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  2798. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  2799. if (canBePattern && !this.state.maybeInArrowParameters) {
  2800. this.toReferencedList(node.elements);
  2801. }
  2802. return node;
  2803. }
  2804. checkLVal(expr, ...args) {
  2805. if (expr.type !== "TypeCastExpression") {
  2806. return super.checkLVal(expr, ...args);
  2807. }
  2808. }
  2809. parseClassProperty(node) {
  2810. if (this.match(types.colon)) {
  2811. node.typeAnnotation = this.flowParseTypeAnnotation();
  2812. }
  2813. return super.parseClassProperty(node);
  2814. }
  2815. parseClassPrivateProperty(node) {
  2816. if (this.match(types.colon)) {
  2817. node.typeAnnotation = this.flowParseTypeAnnotation();
  2818. }
  2819. return super.parseClassPrivateProperty(node);
  2820. }
  2821. isClassMethod() {
  2822. return this.isRelational("<") || super.isClassMethod();
  2823. }
  2824. isClassProperty() {
  2825. return this.match(types.colon) || super.isClassProperty();
  2826. }
  2827. isNonstaticConstructor(method) {
  2828. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2829. }
  2830. isThisParam(param) {
  2831. return param.type === "Identifier" && param.name === "this";
  2832. }
  2833. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2834. if (method.variance) {
  2835. this.unexpected(method.variance.start);
  2836. }
  2837. delete method.variance;
  2838. if (this.isRelational("<")) {
  2839. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2840. }
  2841. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2842. if (method.params && isConstructor) {
  2843. const params = method.params;
  2844. if (params.length > 0 && this.isThisParam(params[0])) {
  2845. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  2846. }
  2847. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  2848. const params = method.value.params;
  2849. if (params.length > 0 && this.isThisParam(params[0])) {
  2850. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  2851. }
  2852. }
  2853. }
  2854. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2855. if (method.variance) {
  2856. this.unexpected(method.variance.start);
  2857. }
  2858. delete method.variance;
  2859. if (this.isRelational("<")) {
  2860. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2861. }
  2862. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2863. }
  2864. parseClassSuper(node) {
  2865. super.parseClassSuper(node);
  2866. if (node.superClass && this.isRelational("<")) {
  2867. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2868. }
  2869. if (this.isContextual("implements")) {
  2870. this.next();
  2871. const implemented = node.implements = [];
  2872. do {
  2873. const node = this.startNode();
  2874. node.id = this.flowParseRestrictedIdentifier(true);
  2875. if (this.isRelational("<")) {
  2876. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2877. } else {
  2878. node.typeParameters = null;
  2879. }
  2880. implemented.push(this.finishNode(node, "ClassImplements"));
  2881. } while (this.eat(types.comma));
  2882. }
  2883. }
  2884. checkGetterSetterParams(method) {
  2885. super.checkGetterSetterParams(method);
  2886. const params = this.getObjectOrClassMethodParams(method);
  2887. if (params.length > 0) {
  2888. const param = params[0];
  2889. if (this.isThisParam(param) && method.kind === "get") {
  2890. this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam);
  2891. } else if (this.isThisParam(param)) {
  2892. this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam);
  2893. }
  2894. }
  2895. }
  2896. parsePropertyName(node, isPrivateNameAllowed) {
  2897. const variance = this.flowParseVariance();
  2898. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2899. node.variance = variance;
  2900. return key;
  2901. }
  2902. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  2903. if (prop.variance) {
  2904. this.unexpected(prop.variance.start);
  2905. }
  2906. delete prop.variance;
  2907. let typeParameters;
  2908. if (this.isRelational("<") && !isAccessor) {
  2909. typeParameters = this.flowParseTypeParameterDeclaration();
  2910. if (!this.match(types.parenL)) this.unexpected();
  2911. }
  2912. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  2913. if (typeParameters) {
  2914. (prop.value || prop).typeParameters = typeParameters;
  2915. }
  2916. }
  2917. parseAssignableListItemTypes(param) {
  2918. if (this.eat(types.question)) {
  2919. if (param.type !== "Identifier") {
  2920. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  2921. }
  2922. if (this.isThisParam(param)) {
  2923. this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional);
  2924. }
  2925. param.optional = true;
  2926. }
  2927. if (this.match(types.colon)) {
  2928. param.typeAnnotation = this.flowParseTypeAnnotation();
  2929. } else if (this.isThisParam(param)) {
  2930. this.raise(param.start, FlowErrors.ThisParamAnnotationRequired);
  2931. }
  2932. if (this.match(types.eq) && this.isThisParam(param)) {
  2933. this.raise(param.start, FlowErrors.ThisParamNoDefault);
  2934. }
  2935. this.resetEndLocation(param);
  2936. return param;
  2937. }
  2938. parseMaybeDefault(startPos, startLoc, left) {
  2939. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2940. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2941. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  2942. }
  2943. return node;
  2944. }
  2945. shouldParseDefaultImport(node) {
  2946. if (!hasTypeImportKind(node)) {
  2947. return super.shouldParseDefaultImport(node);
  2948. }
  2949. return isMaybeDefaultImport(this.state);
  2950. }
  2951. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2952. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2953. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  2954. node.specifiers.push(this.finishNode(specifier, type));
  2955. }
  2956. maybeParseDefaultImportSpecifier(node) {
  2957. node.importKind = "value";
  2958. let kind = null;
  2959. if (this.match(types._typeof)) {
  2960. kind = "typeof";
  2961. } else if (this.isContextual("type")) {
  2962. kind = "type";
  2963. }
  2964. if (kind) {
  2965. const lh = this.lookahead();
  2966. if (kind === "type" && lh.type === types.star) {
  2967. this.unexpected(lh.start);
  2968. }
  2969. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2970. this.next();
  2971. node.importKind = kind;
  2972. }
  2973. }
  2974. return super.maybeParseDefaultImportSpecifier(node);
  2975. }
  2976. parseImportSpecifier(node) {
  2977. const specifier = this.startNode();
  2978. const firstIdentLoc = this.state.start;
  2979. const firstIdent = this.parseModuleExportName();
  2980. let specifierTypeKind = null;
  2981. if (firstIdent.type === "Identifier") {
  2982. if (firstIdent.name === "type") {
  2983. specifierTypeKind = "type";
  2984. } else if (firstIdent.name === "typeof") {
  2985. specifierTypeKind = "typeof";
  2986. }
  2987. }
  2988. let isBinding = false;
  2989. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2990. const as_ident = this.parseIdentifier(true);
  2991. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2992. specifier.imported = as_ident;
  2993. specifier.importKind = specifierTypeKind;
  2994. specifier.local = as_ident.__clone();
  2995. } else {
  2996. specifier.imported = firstIdent;
  2997. specifier.importKind = null;
  2998. specifier.local = this.parseIdentifier();
  2999. }
  3000. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  3001. specifier.imported = this.parseIdentifier(true);
  3002. specifier.importKind = specifierTypeKind;
  3003. if (this.eatContextual("as")) {
  3004. specifier.local = this.parseIdentifier();
  3005. } else {
  3006. isBinding = true;
  3007. specifier.local = specifier.imported.__clone();
  3008. }
  3009. } else {
  3010. if (firstIdent.type === "StringLiteral") {
  3011. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  3012. }
  3013. isBinding = true;
  3014. specifier.imported = firstIdent;
  3015. specifier.importKind = null;
  3016. specifier.local = specifier.imported.__clone();
  3017. }
  3018. const nodeIsTypeImport = hasTypeImportKind(node);
  3019. const specifierIsTypeImport = hasTypeImportKind(specifier);
  3020. if (nodeIsTypeImport && specifierIsTypeImport) {
  3021. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  3022. }
  3023. if (nodeIsTypeImport || specifierIsTypeImport) {
  3024. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  3025. }
  3026. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  3027. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  3028. }
  3029. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  3030. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  3031. }
  3032. parseBindingAtom() {
  3033. switch (this.state.type) {
  3034. case types._this:
  3035. return this.parseIdentifier(true);
  3036. default:
  3037. return super.parseBindingAtom();
  3038. }
  3039. }
  3040. parseFunctionParams(node, allowModifiers) {
  3041. const kind = node.kind;
  3042. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  3043. node.typeParameters = this.flowParseTypeParameterDeclaration();
  3044. }
  3045. super.parseFunctionParams(node, allowModifiers);
  3046. }
  3047. parseVarId(decl, kind) {
  3048. super.parseVarId(decl, kind);
  3049. if (this.match(types.colon)) {
  3050. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  3051. this.resetEndLocation(decl.id);
  3052. }
  3053. }
  3054. parseAsyncArrowFromCallExpression(node, call) {
  3055. if (this.match(types.colon)) {
  3056. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  3057. this.state.noAnonFunctionType = true;
  3058. node.returnType = this.flowParseTypeAnnotation();
  3059. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  3060. }
  3061. return super.parseAsyncArrowFromCallExpression(node, call);
  3062. }
  3063. shouldParseAsyncArrow() {
  3064. return this.match(types.colon) || super.shouldParseAsyncArrow();
  3065. }
  3066. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  3067. var _jsx;
  3068. let state = null;
  3069. let jsx;
  3070. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  3071. state = this.state.clone();
  3072. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  3073. if (!jsx.error) return jsx.node;
  3074. const {
  3075. context
  3076. } = this.state;
  3077. if (context[context.length - 1] === types$1.j_oTag) {
  3078. context.length -= 2;
  3079. } else if (context[context.length - 1] === types$1.j_expr) {
  3080. context.length -= 1;
  3081. }
  3082. }
  3083. if ((_jsx = jsx) != null && _jsx.error || this.isRelational("<")) {
  3084. var _jsx2, _jsx3;
  3085. state = state || this.state.clone();
  3086. let typeParameters;
  3087. const arrow = this.tryParse(abort => {
  3088. var _arrowExpression$extr;
  3089. typeParameters = this.flowParseTypeParameterDeclaration();
  3090. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  3091. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  3092. this.resetStartLocationFromNode(result, typeParameters);
  3093. return result;
  3094. });
  3095. if (arrowExpression.type !== "ArrowFunctionExpression" && (_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) {
  3096. abort();
  3097. }
  3098. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  3099. expr.typeParameters = typeParameters;
  3100. this.resetStartLocationFromNode(expr, typeParameters);
  3101. return arrowExpression;
  3102. }, state);
  3103. let arrowExpression = null;
  3104. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  3105. if (!arrow.error && !arrow.aborted) {
  3106. if (arrow.node.async) {
  3107. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  3108. }
  3109. return arrow.node;
  3110. }
  3111. arrowExpression = arrow.node;
  3112. }
  3113. if ((_jsx2 = jsx) != null && _jsx2.node) {
  3114. this.state = jsx.failState;
  3115. return jsx.node;
  3116. }
  3117. if (arrowExpression) {
  3118. this.state = arrow.failState;
  3119. return arrowExpression;
  3120. }
  3121. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  3122. if (arrow.thrown) throw arrow.error;
  3123. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  3124. }
  3125. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  3126. }
  3127. parseArrow(node) {
  3128. if (this.match(types.colon)) {
  3129. const result = this.tryParse(() => {
  3130. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  3131. this.state.noAnonFunctionType = true;
  3132. const typeNode = this.startNode();
  3133. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  3134. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  3135. if (this.canInsertSemicolon()) this.unexpected();
  3136. if (!this.match(types.arrow)) this.unexpected();
  3137. return typeNode;
  3138. });
  3139. if (result.thrown) return null;
  3140. if (result.error) this.state = result.failState;
  3141. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  3142. }
  3143. return super.parseArrow(node);
  3144. }
  3145. shouldParseArrow() {
  3146. return this.match(types.colon) || super.shouldParseArrow();
  3147. }
  3148. setArrowFunctionParameters(node, params) {
  3149. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  3150. node.params = params;
  3151. } else {
  3152. super.setArrowFunctionParameters(node, params);
  3153. }
  3154. }
  3155. checkParams(node, allowDuplicates, isArrowFunction) {
  3156. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  3157. return;
  3158. }
  3159. for (let i = 0; i < node.params.length; i++) {
  3160. if (this.isThisParam(node.params[i]) && i > 0) {
  3161. this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst);
  3162. }
  3163. }
  3164. return super.checkParams(...arguments);
  3165. }
  3166. parseParenAndDistinguishExpression(canBeArrow) {
  3167. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  3168. }
  3169. parseSubscripts(base, startPos, startLoc, noCalls) {
  3170. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  3171. this.next();
  3172. const node = this.startNodeAt(startPos, startLoc);
  3173. node.callee = base;
  3174. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  3175. base = this.finishNode(node, "CallExpression");
  3176. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  3177. const state = this.state.clone();
  3178. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  3179. if (!arrow.error && !arrow.aborted) return arrow.node;
  3180. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  3181. if (result.node && !result.error) return result.node;
  3182. if (arrow.node) {
  3183. this.state = arrow.failState;
  3184. return arrow.node;
  3185. }
  3186. if (result.node) {
  3187. this.state = result.failState;
  3188. return result.node;
  3189. }
  3190. throw arrow.error || result.error;
  3191. }
  3192. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  3193. }
  3194. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  3195. if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
  3196. subscriptState.optionalChainMember = true;
  3197. if (noCalls) {
  3198. subscriptState.stop = true;
  3199. return base;
  3200. }
  3201. this.next();
  3202. const node = this.startNodeAt(startPos, startLoc);
  3203. node.callee = base;
  3204. node.typeArguments = this.flowParseTypeParameterInstantiation();
  3205. this.expect(types.parenL);
  3206. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  3207. node.optional = true;
  3208. return this.finishCallExpression(node, true);
  3209. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  3210. const node = this.startNodeAt(startPos, startLoc);
  3211. node.callee = base;
  3212. const result = this.tryParse(() => {
  3213. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  3214. this.expect(types.parenL);
  3215. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  3216. if (subscriptState.optionalChainMember) node.optional = false;
  3217. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  3218. });
  3219. if (result.node) {
  3220. if (result.error) this.state = result.failState;
  3221. return result.node;
  3222. }
  3223. }
  3224. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  3225. }
  3226. parseNewArguments(node) {
  3227. let targs = null;
  3228. if (this.shouldParseTypes() && this.isRelational("<")) {
  3229. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  3230. }
  3231. node.typeArguments = targs;
  3232. super.parseNewArguments(node);
  3233. }
  3234. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  3235. const node = this.startNodeAt(startPos, startLoc);
  3236. this.parseFunctionParams(node);
  3237. if (!this.parseArrow(node)) return;
  3238. return this.parseArrowExpression(node, undefined, true);
  3239. }
  3240. readToken_mult_modulo(code) {
  3241. const next = this.input.charCodeAt(this.state.pos + 1);
  3242. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  3243. this.state.hasFlowComment = false;
  3244. this.state.pos += 2;
  3245. this.nextToken();
  3246. return;
  3247. }
  3248. super.readToken_mult_modulo(code);
  3249. }
  3250. readToken_pipe_amp(code) {
  3251. const next = this.input.charCodeAt(this.state.pos + 1);
  3252. if (code === 124 && next === 125) {
  3253. this.finishOp(types.braceBarR, 2);
  3254. return;
  3255. }
  3256. super.readToken_pipe_amp(code);
  3257. }
  3258. parseTopLevel(file, program) {
  3259. const fileNode = super.parseTopLevel(file, program);
  3260. if (this.state.hasFlowComment) {
  3261. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  3262. }
  3263. return fileNode;
  3264. }
  3265. skipBlockComment() {
  3266. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  3267. if (this.state.hasFlowComment) {
  3268. this.unexpected(null, FlowErrors.NestedFlowComment);
  3269. }
  3270. this.hasFlowCommentCompletion();
  3271. this.state.pos += this.skipFlowComment();
  3272. this.state.hasFlowComment = true;
  3273. return;
  3274. }
  3275. if (this.state.hasFlowComment) {
  3276. const end = this.input.indexOf("*-/", this.state.pos += 2);
  3277. if (end === -1) {
  3278. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  3279. }
  3280. this.state.pos = end + 3;
  3281. return;
  3282. }
  3283. super.skipBlockComment();
  3284. }
  3285. skipFlowComment() {
  3286. const {
  3287. pos
  3288. } = this.state;
  3289. let shiftToFirstNonWhiteSpace = 2;
  3290. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  3291. shiftToFirstNonWhiteSpace++;
  3292. }
  3293. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  3294. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  3295. if (ch2 === 58 && ch3 === 58) {
  3296. return shiftToFirstNonWhiteSpace + 2;
  3297. }
  3298. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  3299. return shiftToFirstNonWhiteSpace + 12;
  3300. }
  3301. if (ch2 === 58 && ch3 !== 58) {
  3302. return shiftToFirstNonWhiteSpace;
  3303. }
  3304. return false;
  3305. }
  3306. hasFlowCommentCompletion() {
  3307. const end = this.input.indexOf("*/", this.state.pos);
  3308. if (end === -1) {
  3309. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  3310. }
  3311. }
  3312. flowEnumErrorBooleanMemberNotInitialized(pos, {
  3313. enumName,
  3314. memberName
  3315. }) {
  3316. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  3317. }
  3318. flowEnumErrorInvalidMemberName(pos, {
  3319. enumName,
  3320. memberName
  3321. }) {
  3322. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  3323. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  3324. }
  3325. flowEnumErrorDuplicateMemberName(pos, {
  3326. enumName,
  3327. memberName
  3328. }) {
  3329. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  3330. }
  3331. flowEnumErrorInconsistentMemberValues(pos, {
  3332. enumName
  3333. }) {
  3334. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  3335. }
  3336. flowEnumErrorInvalidExplicitType(pos, {
  3337. enumName,
  3338. suppliedType
  3339. }) {
  3340. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  3341. }
  3342. flowEnumErrorInvalidMemberInitializer(pos, {
  3343. enumName,
  3344. explicitType,
  3345. memberName
  3346. }) {
  3347. let message = null;
  3348. switch (explicitType) {
  3349. case "boolean":
  3350. case "number":
  3351. case "string":
  3352. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  3353. break;
  3354. case "symbol":
  3355. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  3356. break;
  3357. default:
  3358. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  3359. }
  3360. return this.raise(pos, message, enumName, memberName, explicitType);
  3361. }
  3362. flowEnumErrorNumberMemberNotInitialized(pos, {
  3363. enumName,
  3364. memberName
  3365. }) {
  3366. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  3367. }
  3368. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  3369. enumName
  3370. }) {
  3371. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  3372. }
  3373. flowEnumMemberInit() {
  3374. const startPos = this.state.start;
  3375. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  3376. switch (this.state.type) {
  3377. case types.num:
  3378. {
  3379. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  3380. if (endOfInit()) {
  3381. return {
  3382. type: "number",
  3383. pos: literal.start,
  3384. value: literal
  3385. };
  3386. }
  3387. return {
  3388. type: "invalid",
  3389. pos: startPos
  3390. };
  3391. }
  3392. case types.string:
  3393. {
  3394. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  3395. if (endOfInit()) {
  3396. return {
  3397. type: "string",
  3398. pos: literal.start,
  3399. value: literal
  3400. };
  3401. }
  3402. return {
  3403. type: "invalid",
  3404. pos: startPos
  3405. };
  3406. }
  3407. case types._true:
  3408. case types._false:
  3409. {
  3410. const literal = this.parseBooleanLiteral();
  3411. if (endOfInit()) {
  3412. return {
  3413. type: "boolean",
  3414. pos: literal.start,
  3415. value: literal
  3416. };
  3417. }
  3418. return {
  3419. type: "invalid",
  3420. pos: startPos
  3421. };
  3422. }
  3423. default:
  3424. return {
  3425. type: "invalid",
  3426. pos: startPos
  3427. };
  3428. }
  3429. }
  3430. flowEnumMemberRaw() {
  3431. const pos = this.state.start;
  3432. const id = this.parseIdentifier(true);
  3433. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3434. type: "none",
  3435. pos
  3436. };
  3437. return {
  3438. id,
  3439. init
  3440. };
  3441. }
  3442. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3443. const {
  3444. explicitType
  3445. } = context;
  3446. if (explicitType === null) {
  3447. return;
  3448. }
  3449. if (explicitType !== expectedType) {
  3450. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3451. }
  3452. }
  3453. flowEnumMembers({
  3454. enumName,
  3455. explicitType
  3456. }) {
  3457. const seenNames = new Set();
  3458. const members = {
  3459. booleanMembers: [],
  3460. numberMembers: [],
  3461. stringMembers: [],
  3462. defaultedMembers: []
  3463. };
  3464. let hasUnknownMembers = false;
  3465. while (!this.match(types.braceR)) {
  3466. if (this.eat(types.ellipsis)) {
  3467. hasUnknownMembers = true;
  3468. break;
  3469. }
  3470. const memberNode = this.startNode();
  3471. const {
  3472. id,
  3473. init
  3474. } = this.flowEnumMemberRaw();
  3475. const memberName = id.name;
  3476. if (memberName === "") {
  3477. continue;
  3478. }
  3479. if (/^[a-z]/.test(memberName)) {
  3480. this.flowEnumErrorInvalidMemberName(id.start, {
  3481. enumName,
  3482. memberName
  3483. });
  3484. }
  3485. if (seenNames.has(memberName)) {
  3486. this.flowEnumErrorDuplicateMemberName(id.start, {
  3487. enumName,
  3488. memberName
  3489. });
  3490. }
  3491. seenNames.add(memberName);
  3492. const context = {
  3493. enumName,
  3494. explicitType,
  3495. memberName
  3496. };
  3497. memberNode.id = id;
  3498. switch (init.type) {
  3499. case "boolean":
  3500. {
  3501. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3502. memberNode.init = init.value;
  3503. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3504. break;
  3505. }
  3506. case "number":
  3507. {
  3508. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3509. memberNode.init = init.value;
  3510. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3511. break;
  3512. }
  3513. case "string":
  3514. {
  3515. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3516. memberNode.init = init.value;
  3517. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3518. break;
  3519. }
  3520. case "invalid":
  3521. {
  3522. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3523. }
  3524. case "none":
  3525. {
  3526. switch (explicitType) {
  3527. case "boolean":
  3528. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3529. break;
  3530. case "number":
  3531. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3532. break;
  3533. default:
  3534. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3535. }
  3536. }
  3537. }
  3538. if (!this.match(types.braceR)) {
  3539. this.expect(types.comma);
  3540. }
  3541. }
  3542. return {
  3543. members,
  3544. hasUnknownMembers
  3545. };
  3546. }
  3547. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3548. enumName
  3549. }) {
  3550. if (initializedMembers.length === 0) {
  3551. return defaultedMembers;
  3552. } else if (defaultedMembers.length === 0) {
  3553. return initializedMembers;
  3554. } else if (defaultedMembers.length > initializedMembers.length) {
  3555. for (const member of initializedMembers) {
  3556. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3557. enumName
  3558. });
  3559. }
  3560. return defaultedMembers;
  3561. } else {
  3562. for (const member of defaultedMembers) {
  3563. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3564. enumName
  3565. });
  3566. }
  3567. return initializedMembers;
  3568. }
  3569. }
  3570. flowEnumParseExplicitType({
  3571. enumName
  3572. }) {
  3573. if (this.eatContextual("of")) {
  3574. if (!this.match(types.name)) {
  3575. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3576. enumName,
  3577. suppliedType: null
  3578. });
  3579. }
  3580. const {
  3581. value
  3582. } = this.state;
  3583. this.next();
  3584. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3585. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3586. enumName,
  3587. suppliedType: value
  3588. });
  3589. }
  3590. return value;
  3591. }
  3592. return null;
  3593. }
  3594. flowEnumBody(node, {
  3595. enumName,
  3596. nameLoc
  3597. }) {
  3598. const explicitType = this.flowEnumParseExplicitType({
  3599. enumName
  3600. });
  3601. this.expect(types.braceL);
  3602. const {
  3603. members,
  3604. hasUnknownMembers
  3605. } = this.flowEnumMembers({
  3606. enumName,
  3607. explicitType
  3608. });
  3609. node.hasUnknownMembers = hasUnknownMembers;
  3610. switch (explicitType) {
  3611. case "boolean":
  3612. node.explicitType = true;
  3613. node.members = members.booleanMembers;
  3614. this.expect(types.braceR);
  3615. return this.finishNode(node, "EnumBooleanBody");
  3616. case "number":
  3617. node.explicitType = true;
  3618. node.members = members.numberMembers;
  3619. this.expect(types.braceR);
  3620. return this.finishNode(node, "EnumNumberBody");
  3621. case "string":
  3622. node.explicitType = true;
  3623. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3624. enumName
  3625. });
  3626. this.expect(types.braceR);
  3627. return this.finishNode(node, "EnumStringBody");
  3628. case "symbol":
  3629. node.members = members.defaultedMembers;
  3630. this.expect(types.braceR);
  3631. return this.finishNode(node, "EnumSymbolBody");
  3632. default:
  3633. {
  3634. const empty = () => {
  3635. node.members = [];
  3636. this.expect(types.braceR);
  3637. return this.finishNode(node, "EnumStringBody");
  3638. };
  3639. node.explicitType = false;
  3640. const boolsLen = members.booleanMembers.length;
  3641. const numsLen = members.numberMembers.length;
  3642. const strsLen = members.stringMembers.length;
  3643. const defaultedLen = members.defaultedMembers.length;
  3644. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3645. return empty();
  3646. } else if (!boolsLen && !numsLen) {
  3647. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3648. enumName
  3649. });
  3650. this.expect(types.braceR);
  3651. return this.finishNode(node, "EnumStringBody");
  3652. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3653. for (const member of members.defaultedMembers) {
  3654. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3655. enumName,
  3656. memberName: member.id.name
  3657. });
  3658. }
  3659. node.members = members.booleanMembers;
  3660. this.expect(types.braceR);
  3661. return this.finishNode(node, "EnumBooleanBody");
  3662. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3663. for (const member of members.defaultedMembers) {
  3664. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3665. enumName,
  3666. memberName: member.id.name
  3667. });
  3668. }
  3669. node.members = members.numberMembers;
  3670. this.expect(types.braceR);
  3671. return this.finishNode(node, "EnumNumberBody");
  3672. } else {
  3673. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3674. enumName
  3675. });
  3676. return empty();
  3677. }
  3678. }
  3679. }
  3680. }
  3681. flowParseEnumDeclaration(node) {
  3682. const id = this.parseIdentifier();
  3683. node.id = id;
  3684. node.body = this.flowEnumBody(this.startNode(), {
  3685. enumName: id.name,
  3686. nameLoc: id.start
  3687. });
  3688. return this.finishNode(node, "EnumDeclaration");
  3689. }
  3690. updateContext(prevType) {
  3691. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  3692. this.state.exprAllowed = false;
  3693. } else {
  3694. super.updateContext(prevType);
  3695. }
  3696. }
  3697. isLookaheadToken_lt() {
  3698. const next = this.nextTokenStart();
  3699. if (this.input.charCodeAt(next) === 60) {
  3700. const afterNext = this.input.charCodeAt(next + 1);
  3701. return afterNext !== 60 && afterNext !== 61;
  3702. }
  3703. return false;
  3704. }
  3705. maybeUnwrapTypeCastExpression(node) {
  3706. return node.type === "TypeCastExpression" ? node.expression : node;
  3707. }
  3708. }, _temp;
  3709. });
  3710. const entities = {
  3711. quot: "\u0022",
  3712. amp: "&",
  3713. apos: "\u0027",
  3714. lt: "<",
  3715. gt: ">",
  3716. nbsp: "\u00A0",
  3717. iexcl: "\u00A1",
  3718. cent: "\u00A2",
  3719. pound: "\u00A3",
  3720. curren: "\u00A4",
  3721. yen: "\u00A5",
  3722. brvbar: "\u00A6",
  3723. sect: "\u00A7",
  3724. uml: "\u00A8",
  3725. copy: "\u00A9",
  3726. ordf: "\u00AA",
  3727. laquo: "\u00AB",
  3728. not: "\u00AC",
  3729. shy: "\u00AD",
  3730. reg: "\u00AE",
  3731. macr: "\u00AF",
  3732. deg: "\u00B0",
  3733. plusmn: "\u00B1",
  3734. sup2: "\u00B2",
  3735. sup3: "\u00B3",
  3736. acute: "\u00B4",
  3737. micro: "\u00B5",
  3738. para: "\u00B6",
  3739. middot: "\u00B7",
  3740. cedil: "\u00B8",
  3741. sup1: "\u00B9",
  3742. ordm: "\u00BA",
  3743. raquo: "\u00BB",
  3744. frac14: "\u00BC",
  3745. frac12: "\u00BD",
  3746. frac34: "\u00BE",
  3747. iquest: "\u00BF",
  3748. Agrave: "\u00C0",
  3749. Aacute: "\u00C1",
  3750. Acirc: "\u00C2",
  3751. Atilde: "\u00C3",
  3752. Auml: "\u00C4",
  3753. Aring: "\u00C5",
  3754. AElig: "\u00C6",
  3755. Ccedil: "\u00C7",
  3756. Egrave: "\u00C8",
  3757. Eacute: "\u00C9",
  3758. Ecirc: "\u00CA",
  3759. Euml: "\u00CB",
  3760. Igrave: "\u00CC",
  3761. Iacute: "\u00CD",
  3762. Icirc: "\u00CE",
  3763. Iuml: "\u00CF",
  3764. ETH: "\u00D0",
  3765. Ntilde: "\u00D1",
  3766. Ograve: "\u00D2",
  3767. Oacute: "\u00D3",
  3768. Ocirc: "\u00D4",
  3769. Otilde: "\u00D5",
  3770. Ouml: "\u00D6",
  3771. times: "\u00D7",
  3772. Oslash: "\u00D8",
  3773. Ugrave: "\u00D9",
  3774. Uacute: "\u00DA",
  3775. Ucirc: "\u00DB",
  3776. Uuml: "\u00DC",
  3777. Yacute: "\u00DD",
  3778. THORN: "\u00DE",
  3779. szlig: "\u00DF",
  3780. agrave: "\u00E0",
  3781. aacute: "\u00E1",
  3782. acirc: "\u00E2",
  3783. atilde: "\u00E3",
  3784. auml: "\u00E4",
  3785. aring: "\u00E5",
  3786. aelig: "\u00E6",
  3787. ccedil: "\u00E7",
  3788. egrave: "\u00E8",
  3789. eacute: "\u00E9",
  3790. ecirc: "\u00EA",
  3791. euml: "\u00EB",
  3792. igrave: "\u00EC",
  3793. iacute: "\u00ED",
  3794. icirc: "\u00EE",
  3795. iuml: "\u00EF",
  3796. eth: "\u00F0",
  3797. ntilde: "\u00F1",
  3798. ograve: "\u00F2",
  3799. oacute: "\u00F3",
  3800. ocirc: "\u00F4",
  3801. otilde: "\u00F5",
  3802. ouml: "\u00F6",
  3803. divide: "\u00F7",
  3804. oslash: "\u00F8",
  3805. ugrave: "\u00F9",
  3806. uacute: "\u00FA",
  3807. ucirc: "\u00FB",
  3808. uuml: "\u00FC",
  3809. yacute: "\u00FD",
  3810. thorn: "\u00FE",
  3811. yuml: "\u00FF",
  3812. OElig: "\u0152",
  3813. oelig: "\u0153",
  3814. Scaron: "\u0160",
  3815. scaron: "\u0161",
  3816. Yuml: "\u0178",
  3817. fnof: "\u0192",
  3818. circ: "\u02C6",
  3819. tilde: "\u02DC",
  3820. Alpha: "\u0391",
  3821. Beta: "\u0392",
  3822. Gamma: "\u0393",
  3823. Delta: "\u0394",
  3824. Epsilon: "\u0395",
  3825. Zeta: "\u0396",
  3826. Eta: "\u0397",
  3827. Theta: "\u0398",
  3828. Iota: "\u0399",
  3829. Kappa: "\u039A",
  3830. Lambda: "\u039B",
  3831. Mu: "\u039C",
  3832. Nu: "\u039D",
  3833. Xi: "\u039E",
  3834. Omicron: "\u039F",
  3835. Pi: "\u03A0",
  3836. Rho: "\u03A1",
  3837. Sigma: "\u03A3",
  3838. Tau: "\u03A4",
  3839. Upsilon: "\u03A5",
  3840. Phi: "\u03A6",
  3841. Chi: "\u03A7",
  3842. Psi: "\u03A8",
  3843. Omega: "\u03A9",
  3844. alpha: "\u03B1",
  3845. beta: "\u03B2",
  3846. gamma: "\u03B3",
  3847. delta: "\u03B4",
  3848. epsilon: "\u03B5",
  3849. zeta: "\u03B6",
  3850. eta: "\u03B7",
  3851. theta: "\u03B8",
  3852. iota: "\u03B9",
  3853. kappa: "\u03BA",
  3854. lambda: "\u03BB",
  3855. mu: "\u03BC",
  3856. nu: "\u03BD",
  3857. xi: "\u03BE",
  3858. omicron: "\u03BF",
  3859. pi: "\u03C0",
  3860. rho: "\u03C1",
  3861. sigmaf: "\u03C2",
  3862. sigma: "\u03C3",
  3863. tau: "\u03C4",
  3864. upsilon: "\u03C5",
  3865. phi: "\u03C6",
  3866. chi: "\u03C7",
  3867. psi: "\u03C8",
  3868. omega: "\u03C9",
  3869. thetasym: "\u03D1",
  3870. upsih: "\u03D2",
  3871. piv: "\u03D6",
  3872. ensp: "\u2002",
  3873. emsp: "\u2003",
  3874. thinsp: "\u2009",
  3875. zwnj: "\u200C",
  3876. zwj: "\u200D",
  3877. lrm: "\u200E",
  3878. rlm: "\u200F",
  3879. ndash: "\u2013",
  3880. mdash: "\u2014",
  3881. lsquo: "\u2018",
  3882. rsquo: "\u2019",
  3883. sbquo: "\u201A",
  3884. ldquo: "\u201C",
  3885. rdquo: "\u201D",
  3886. bdquo: "\u201E",
  3887. dagger: "\u2020",
  3888. Dagger: "\u2021",
  3889. bull: "\u2022",
  3890. hellip: "\u2026",
  3891. permil: "\u2030",
  3892. prime: "\u2032",
  3893. Prime: "\u2033",
  3894. lsaquo: "\u2039",
  3895. rsaquo: "\u203A",
  3896. oline: "\u203E",
  3897. frasl: "\u2044",
  3898. euro: "\u20AC",
  3899. image: "\u2111",
  3900. weierp: "\u2118",
  3901. real: "\u211C",
  3902. trade: "\u2122",
  3903. alefsym: "\u2135",
  3904. larr: "\u2190",
  3905. uarr: "\u2191",
  3906. rarr: "\u2192",
  3907. darr: "\u2193",
  3908. harr: "\u2194",
  3909. crarr: "\u21B5",
  3910. lArr: "\u21D0",
  3911. uArr: "\u21D1",
  3912. rArr: "\u21D2",
  3913. dArr: "\u21D3",
  3914. hArr: "\u21D4",
  3915. forall: "\u2200",
  3916. part: "\u2202",
  3917. exist: "\u2203",
  3918. empty: "\u2205",
  3919. nabla: "\u2207",
  3920. isin: "\u2208",
  3921. notin: "\u2209",
  3922. ni: "\u220B",
  3923. prod: "\u220F",
  3924. sum: "\u2211",
  3925. minus: "\u2212",
  3926. lowast: "\u2217",
  3927. radic: "\u221A",
  3928. prop: "\u221D",
  3929. infin: "\u221E",
  3930. ang: "\u2220",
  3931. and: "\u2227",
  3932. or: "\u2228",
  3933. cap: "\u2229",
  3934. cup: "\u222A",
  3935. int: "\u222B",
  3936. there4: "\u2234",
  3937. sim: "\u223C",
  3938. cong: "\u2245",
  3939. asymp: "\u2248",
  3940. ne: "\u2260",
  3941. equiv: "\u2261",
  3942. le: "\u2264",
  3943. ge: "\u2265",
  3944. sub: "\u2282",
  3945. sup: "\u2283",
  3946. nsub: "\u2284",
  3947. sube: "\u2286",
  3948. supe: "\u2287",
  3949. oplus: "\u2295",
  3950. otimes: "\u2297",
  3951. perp: "\u22A5",
  3952. sdot: "\u22C5",
  3953. lceil: "\u2308",
  3954. rceil: "\u2309",
  3955. lfloor: "\u230A",
  3956. rfloor: "\u230B",
  3957. lang: "\u2329",
  3958. rang: "\u232A",
  3959. loz: "\u25CA",
  3960. spades: "\u2660",
  3961. clubs: "\u2663",
  3962. hearts: "\u2665",
  3963. diams: "\u2666"
  3964. };
  3965. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3966. const DECIMAL_NUMBER = /^\d+$/;
  3967. const JsxErrors = Object.freeze({
  3968. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3969. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3970. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3971. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  3972. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3973. UnterminatedJsxContent: "Unterminated JSX contents",
  3974. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3975. });
  3976. types$1.j_oTag = new TokContext("<tag", false);
  3977. types$1.j_cTag = new TokContext("</tag", false);
  3978. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3979. types.jsxName = new TokenType("jsxName");
  3980. types.jsxText = new TokenType("jsxText", {
  3981. beforeExpr: true
  3982. });
  3983. types.jsxTagStart = new TokenType("jsxTagStart", {
  3984. startsExpr: true
  3985. });
  3986. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3987. types.jsxTagStart.updateContext = function () {
  3988. this.state.context.push(types$1.j_expr);
  3989. this.state.context.push(types$1.j_oTag);
  3990. this.state.exprAllowed = false;
  3991. };
  3992. types.jsxTagEnd.updateContext = function (prevType) {
  3993. const out = this.state.context.pop();
  3994. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3995. this.state.context.pop();
  3996. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3997. } else {
  3998. this.state.exprAllowed = true;
  3999. }
  4000. };
  4001. function isFragment(object) {
  4002. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  4003. }
  4004. function getQualifiedJSXName(object) {
  4005. if (object.type === "JSXIdentifier") {
  4006. return object.name;
  4007. }
  4008. if (object.type === "JSXNamespacedName") {
  4009. return object.namespace.name + ":" + object.name.name;
  4010. }
  4011. if (object.type === "JSXMemberExpression") {
  4012. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  4013. }
  4014. throw new Error("Node had unexpected type: " + object.type);
  4015. }
  4016. var jsx = (superClass => class extends superClass {
  4017. jsxReadToken() {
  4018. let out = "";
  4019. let chunkStart = this.state.pos;
  4020. for (;;) {
  4021. if (this.state.pos >= this.length) {
  4022. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  4023. }
  4024. const ch = this.input.charCodeAt(this.state.pos);
  4025. switch (ch) {
  4026. case 60:
  4027. case 123:
  4028. if (this.state.pos === this.state.start) {
  4029. if (ch === 60 && this.state.exprAllowed) {
  4030. ++this.state.pos;
  4031. return this.finishToken(types.jsxTagStart);
  4032. }
  4033. return super.getTokenFromCode(ch);
  4034. }
  4035. out += this.input.slice(chunkStart, this.state.pos);
  4036. return this.finishToken(types.jsxText, out);
  4037. case 38:
  4038. out += this.input.slice(chunkStart, this.state.pos);
  4039. out += this.jsxReadEntity();
  4040. chunkStart = this.state.pos;
  4041. break;
  4042. case 62:
  4043. case 125:
  4044. default:
  4045. if (isNewLine(ch)) {
  4046. out += this.input.slice(chunkStart, this.state.pos);
  4047. out += this.jsxReadNewLine(true);
  4048. chunkStart = this.state.pos;
  4049. } else {
  4050. ++this.state.pos;
  4051. }
  4052. }
  4053. }
  4054. }
  4055. jsxReadNewLine(normalizeCRLF) {
  4056. const ch = this.input.charCodeAt(this.state.pos);
  4057. let out;
  4058. ++this.state.pos;
  4059. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  4060. ++this.state.pos;
  4061. out = normalizeCRLF ? "\n" : "\r\n";
  4062. } else {
  4063. out = String.fromCharCode(ch);
  4064. }
  4065. ++this.state.curLine;
  4066. this.state.lineStart = this.state.pos;
  4067. return out;
  4068. }
  4069. jsxReadString(quote) {
  4070. let out = "";
  4071. let chunkStart = ++this.state.pos;
  4072. for (;;) {
  4073. if (this.state.pos >= this.length) {
  4074. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  4075. }
  4076. const ch = this.input.charCodeAt(this.state.pos);
  4077. if (ch === quote) break;
  4078. if (ch === 38) {
  4079. out += this.input.slice(chunkStart, this.state.pos);
  4080. out += this.jsxReadEntity();
  4081. chunkStart = this.state.pos;
  4082. } else if (isNewLine(ch)) {
  4083. out += this.input.slice(chunkStart, this.state.pos);
  4084. out += this.jsxReadNewLine(false);
  4085. chunkStart = this.state.pos;
  4086. } else {
  4087. ++this.state.pos;
  4088. }
  4089. }
  4090. out += this.input.slice(chunkStart, this.state.pos++);
  4091. return this.finishToken(types.string, out);
  4092. }
  4093. jsxReadEntity() {
  4094. let str = "";
  4095. let count = 0;
  4096. let entity;
  4097. let ch = this.input[this.state.pos];
  4098. const startPos = ++this.state.pos;
  4099. while (this.state.pos < this.length && count++ < 10) {
  4100. ch = this.input[this.state.pos++];
  4101. if (ch === ";") {
  4102. if (str[0] === "#") {
  4103. if (str[1] === "x") {
  4104. str = str.substr(2);
  4105. if (HEX_NUMBER.test(str)) {
  4106. entity = String.fromCodePoint(parseInt(str, 16));
  4107. }
  4108. } else {
  4109. str = str.substr(1);
  4110. if (DECIMAL_NUMBER.test(str)) {
  4111. entity = String.fromCodePoint(parseInt(str, 10));
  4112. }
  4113. }
  4114. } else {
  4115. entity = entities[str];
  4116. }
  4117. break;
  4118. }
  4119. str += ch;
  4120. }
  4121. if (!entity) {
  4122. this.state.pos = startPos;
  4123. return "&";
  4124. }
  4125. return entity;
  4126. }
  4127. jsxReadWord() {
  4128. let ch;
  4129. const start = this.state.pos;
  4130. do {
  4131. ch = this.input.charCodeAt(++this.state.pos);
  4132. } while (isIdentifierChar(ch) || ch === 45);
  4133. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  4134. }
  4135. jsxParseIdentifier() {
  4136. const node = this.startNode();
  4137. if (this.match(types.jsxName)) {
  4138. node.name = this.state.value;
  4139. } else if (this.state.type.keyword) {
  4140. node.name = this.state.type.keyword;
  4141. } else {
  4142. this.unexpected();
  4143. }
  4144. this.next();
  4145. return this.finishNode(node, "JSXIdentifier");
  4146. }
  4147. jsxParseNamespacedName() {
  4148. const startPos = this.state.start;
  4149. const startLoc = this.state.startLoc;
  4150. const name = this.jsxParseIdentifier();
  4151. if (!this.eat(types.colon)) return name;
  4152. const node = this.startNodeAt(startPos, startLoc);
  4153. node.namespace = name;
  4154. node.name = this.jsxParseIdentifier();
  4155. return this.finishNode(node, "JSXNamespacedName");
  4156. }
  4157. jsxParseElementName() {
  4158. const startPos = this.state.start;
  4159. const startLoc = this.state.startLoc;
  4160. let node = this.jsxParseNamespacedName();
  4161. if (node.type === "JSXNamespacedName") {
  4162. return node;
  4163. }
  4164. while (this.eat(types.dot)) {
  4165. const newNode = this.startNodeAt(startPos, startLoc);
  4166. newNode.object = node;
  4167. newNode.property = this.jsxParseIdentifier();
  4168. node = this.finishNode(newNode, "JSXMemberExpression");
  4169. }
  4170. return node;
  4171. }
  4172. jsxParseAttributeValue() {
  4173. let node;
  4174. switch (this.state.type) {
  4175. case types.braceL:
  4176. node = this.startNode();
  4177. this.next();
  4178. node = this.jsxParseExpressionContainer(node);
  4179. if (node.expression.type === "JSXEmptyExpression") {
  4180. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  4181. }
  4182. return node;
  4183. case types.jsxTagStart:
  4184. case types.string:
  4185. return this.parseExprAtom();
  4186. default:
  4187. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  4188. }
  4189. }
  4190. jsxParseEmptyExpression() {
  4191. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  4192. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  4193. }
  4194. jsxParseSpreadChild(node) {
  4195. this.next();
  4196. node.expression = this.parseExpression();
  4197. this.expect(types.braceR);
  4198. return this.finishNode(node, "JSXSpreadChild");
  4199. }
  4200. jsxParseExpressionContainer(node) {
  4201. if (this.match(types.braceR)) {
  4202. node.expression = this.jsxParseEmptyExpression();
  4203. } else {
  4204. const expression = this.parseExpression();
  4205. node.expression = expression;
  4206. }
  4207. this.expect(types.braceR);
  4208. return this.finishNode(node, "JSXExpressionContainer");
  4209. }
  4210. jsxParseAttribute() {
  4211. const node = this.startNode();
  4212. if (this.eat(types.braceL)) {
  4213. this.expect(types.ellipsis);
  4214. node.argument = this.parseMaybeAssignAllowIn();
  4215. this.expect(types.braceR);
  4216. return this.finishNode(node, "JSXSpreadAttribute");
  4217. }
  4218. node.name = this.jsxParseNamespacedName();
  4219. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  4220. return this.finishNode(node, "JSXAttribute");
  4221. }
  4222. jsxParseOpeningElementAt(startPos, startLoc) {
  4223. const node = this.startNodeAt(startPos, startLoc);
  4224. if (this.match(types.jsxTagEnd)) {
  4225. this.expect(types.jsxTagEnd);
  4226. return this.finishNode(node, "JSXOpeningFragment");
  4227. }
  4228. node.name = this.jsxParseElementName();
  4229. return this.jsxParseOpeningElementAfterName(node);
  4230. }
  4231. jsxParseOpeningElementAfterName(node) {
  4232. const attributes = [];
  4233. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  4234. attributes.push(this.jsxParseAttribute());
  4235. }
  4236. node.attributes = attributes;
  4237. node.selfClosing = this.eat(types.slash);
  4238. this.expect(types.jsxTagEnd);
  4239. return this.finishNode(node, "JSXOpeningElement");
  4240. }
  4241. jsxParseClosingElementAt(startPos, startLoc) {
  4242. const node = this.startNodeAt(startPos, startLoc);
  4243. if (this.match(types.jsxTagEnd)) {
  4244. this.expect(types.jsxTagEnd);
  4245. return this.finishNode(node, "JSXClosingFragment");
  4246. }
  4247. node.name = this.jsxParseElementName();
  4248. this.expect(types.jsxTagEnd);
  4249. return this.finishNode(node, "JSXClosingElement");
  4250. }
  4251. jsxParseElementAt(startPos, startLoc) {
  4252. const node = this.startNodeAt(startPos, startLoc);
  4253. const children = [];
  4254. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  4255. let closingElement = null;
  4256. if (!openingElement.selfClosing) {
  4257. contents: for (;;) {
  4258. switch (this.state.type) {
  4259. case types.jsxTagStart:
  4260. startPos = this.state.start;
  4261. startLoc = this.state.startLoc;
  4262. this.next();
  4263. if (this.eat(types.slash)) {
  4264. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  4265. break contents;
  4266. }
  4267. children.push(this.jsxParseElementAt(startPos, startLoc));
  4268. break;
  4269. case types.jsxText:
  4270. children.push(this.parseExprAtom());
  4271. break;
  4272. case types.braceL:
  4273. {
  4274. const node = this.startNode();
  4275. this.next();
  4276. if (this.match(types.ellipsis)) {
  4277. children.push(this.jsxParseSpreadChild(node));
  4278. } else {
  4279. children.push(this.jsxParseExpressionContainer(node));
  4280. }
  4281. break;
  4282. }
  4283. default:
  4284. throw this.unexpected();
  4285. }
  4286. }
  4287. if (isFragment(openingElement) && !isFragment(closingElement)) {
  4288. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  4289. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  4290. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  4291. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  4292. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  4293. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  4294. }
  4295. }
  4296. }
  4297. if (isFragment(openingElement)) {
  4298. node.openingFragment = openingElement;
  4299. node.closingFragment = closingElement;
  4300. } else {
  4301. node.openingElement = openingElement;
  4302. node.closingElement = closingElement;
  4303. }
  4304. node.children = children;
  4305. if (this.isRelational("<")) {
  4306. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  4307. }
  4308. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  4309. }
  4310. jsxParseElement() {
  4311. const startPos = this.state.start;
  4312. const startLoc = this.state.startLoc;
  4313. this.next();
  4314. return this.jsxParseElementAt(startPos, startLoc);
  4315. }
  4316. parseExprAtom(refExpressionErrors) {
  4317. if (this.match(types.jsxText)) {
  4318. return this.parseLiteral(this.state.value, "JSXText");
  4319. } else if (this.match(types.jsxTagStart)) {
  4320. return this.jsxParseElement();
  4321. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  4322. this.finishToken(types.jsxTagStart);
  4323. return this.jsxParseElement();
  4324. } else {
  4325. return super.parseExprAtom(refExpressionErrors);
  4326. }
  4327. }
  4328. getTokenFromCode(code) {
  4329. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  4330. const context = this.curContext();
  4331. if (context === types$1.j_expr) {
  4332. return this.jsxReadToken();
  4333. }
  4334. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  4335. if (isIdentifierStart(code)) {
  4336. return this.jsxReadWord();
  4337. }
  4338. if (code === 62) {
  4339. ++this.state.pos;
  4340. return this.finishToken(types.jsxTagEnd);
  4341. }
  4342. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  4343. return this.jsxReadString(code);
  4344. }
  4345. }
  4346. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  4347. ++this.state.pos;
  4348. return this.finishToken(types.jsxTagStart);
  4349. }
  4350. return super.getTokenFromCode(code);
  4351. }
  4352. updateContext(prevType) {
  4353. if (this.match(types.braceL)) {
  4354. const curContext = this.curContext();
  4355. if (curContext === types$1.j_oTag) {
  4356. this.state.context.push(types$1.braceExpression);
  4357. } else if (curContext === types$1.j_expr) {
  4358. this.state.context.push(types$1.templateQuasi);
  4359. } else {
  4360. super.updateContext(prevType);
  4361. }
  4362. this.state.exprAllowed = true;
  4363. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  4364. this.state.context.length -= 2;
  4365. this.state.context.push(types$1.j_cTag);
  4366. this.state.exprAllowed = false;
  4367. } else {
  4368. return super.updateContext(prevType);
  4369. }
  4370. }
  4371. });
  4372. class TypeScriptScope extends Scope {
  4373. constructor(...args) {
  4374. super(...args);
  4375. this.types = [];
  4376. this.enums = [];
  4377. this.constEnums = [];
  4378. this.classes = [];
  4379. this.exportOnlyBindings = [];
  4380. }
  4381. }
  4382. class TypeScriptScopeHandler extends ScopeHandler {
  4383. createScope(flags) {
  4384. return new TypeScriptScope(flags);
  4385. }
  4386. declareName(name, bindingType, pos) {
  4387. const scope = this.currentScope();
  4388. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4389. this.maybeExportDefined(scope, name);
  4390. scope.exportOnlyBindings.push(name);
  4391. return;
  4392. }
  4393. super.declareName(...arguments);
  4394. if (bindingType & BIND_KIND_TYPE) {
  4395. if (!(bindingType & BIND_KIND_VALUE)) {
  4396. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4397. this.maybeExportDefined(scope, name);
  4398. }
  4399. scope.types.push(name);
  4400. }
  4401. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4402. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4403. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4404. }
  4405. isRedeclaredInScope(scope, name, bindingType) {
  4406. if (scope.enums.indexOf(name) > -1) {
  4407. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4408. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4409. const wasConst = scope.constEnums.indexOf(name) > -1;
  4410. return isConst !== wasConst;
  4411. }
  4412. return true;
  4413. }
  4414. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4415. if (scope.lexical.indexOf(name) > -1) {
  4416. return !!(bindingType & BIND_KIND_VALUE);
  4417. } else {
  4418. return false;
  4419. }
  4420. }
  4421. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4422. return true;
  4423. }
  4424. return super.isRedeclaredInScope(...arguments);
  4425. }
  4426. checkLocalExport(id) {
  4427. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4428. super.checkLocalExport(id);
  4429. }
  4430. }
  4431. }
  4432. const PARAM = 0b0000,
  4433. PARAM_YIELD = 0b0001,
  4434. PARAM_AWAIT = 0b0010,
  4435. PARAM_RETURN = 0b0100,
  4436. PARAM_IN = 0b1000;
  4437. class ProductionParameterHandler {
  4438. constructor() {
  4439. this.stacks = [];
  4440. }
  4441. enter(flags) {
  4442. this.stacks.push(flags);
  4443. }
  4444. exit() {
  4445. this.stacks.pop();
  4446. }
  4447. currentFlags() {
  4448. return this.stacks[this.stacks.length - 1];
  4449. }
  4450. get hasAwait() {
  4451. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4452. }
  4453. get hasYield() {
  4454. return (this.currentFlags() & PARAM_YIELD) > 0;
  4455. }
  4456. get hasReturn() {
  4457. return (this.currentFlags() & PARAM_RETURN) > 0;
  4458. }
  4459. get hasIn() {
  4460. return (this.currentFlags() & PARAM_IN) > 0;
  4461. }
  4462. }
  4463. function functionFlags(isAsync, isGenerator) {
  4464. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4465. }
  4466. function nonNull(x) {
  4467. if (x == null) {
  4468. throw new Error(`Unexpected ${x} value.`);
  4469. }
  4470. return x;
  4471. }
  4472. function assert(x) {
  4473. if (!x) {
  4474. throw new Error("Assert fail");
  4475. }
  4476. }
  4477. const TSErrors = Object.freeze({
  4478. AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.",
  4479. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4480. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4481. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  4482. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  4483. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  4484. DuplicateModifier: "Duplicate modifier: '%0'",
  4485. DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
  4486. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4487. EmptyTypeArguments: "Type argument list cannot be empty.",
  4488. EmptyTypeParameters: "Type parameter list cannot be empty.",
  4489. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  4490. ImportAliasHasImportType: "An import alias can not use 'import type'",
  4491. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4492. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4493. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4494. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
  4495. InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
  4496. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  4497. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  4498. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  4499. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  4500. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4501. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4502. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4503. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4504. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  4505. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4506. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  4507. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4508. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4509. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4510. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4511. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4512. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4513. });
  4514. function keywordTypeFromName(value) {
  4515. switch (value) {
  4516. case "any":
  4517. return "TSAnyKeyword";
  4518. case "boolean":
  4519. return "TSBooleanKeyword";
  4520. case "bigint":
  4521. return "TSBigIntKeyword";
  4522. case "never":
  4523. return "TSNeverKeyword";
  4524. case "number":
  4525. return "TSNumberKeyword";
  4526. case "object":
  4527. return "TSObjectKeyword";
  4528. case "string":
  4529. return "TSStringKeyword";
  4530. case "symbol":
  4531. return "TSSymbolKeyword";
  4532. case "undefined":
  4533. return "TSUndefinedKeyword";
  4534. case "unknown":
  4535. return "TSUnknownKeyword";
  4536. default:
  4537. return undefined;
  4538. }
  4539. }
  4540. function tsIsAccessModifier(modifier) {
  4541. return modifier === "private" || modifier === "public" || modifier === "protected";
  4542. }
  4543. var typescript = (superClass => class extends superClass {
  4544. getScopeHandler() {
  4545. return TypeScriptScopeHandler;
  4546. }
  4547. tsIsIdentifier() {
  4548. return this.match(types.name);
  4549. }
  4550. tsNextTokenCanFollowModifier() {
  4551. this.next();
  4552. return (this.match(types.bracketL) || this.match(types.braceL) || this.match(types.star) || this.match(types.ellipsis) || this.match(types.hash) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  4553. }
  4554. tsParseModifier(allowedModifiers) {
  4555. if (!this.match(types.name)) {
  4556. return undefined;
  4557. }
  4558. const modifier = this.state.value;
  4559. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4560. return modifier;
  4561. }
  4562. return undefined;
  4563. }
  4564. tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate) {
  4565. for (;;) {
  4566. const startPos = this.state.start;
  4567. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []));
  4568. if (!modifier) break;
  4569. if (tsIsAccessModifier(modifier)) {
  4570. if (modified.accessibility) {
  4571. this.raise(startPos, TSErrors.DuplicateAccessibilityModifier);
  4572. } else {
  4573. modified.accessibility = modifier;
  4574. }
  4575. } else {
  4576. if (Object.hasOwnProperty.call(modified, modifier)) {
  4577. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4578. }
  4579. modified[modifier] = true;
  4580. }
  4581. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  4582. this.raise(startPos, errorTemplate, modifier);
  4583. }
  4584. }
  4585. }
  4586. tsIsListTerminator(kind) {
  4587. switch (kind) {
  4588. case "EnumMembers":
  4589. case "TypeMembers":
  4590. return this.match(types.braceR);
  4591. case "HeritageClauseElement":
  4592. return this.match(types.braceL);
  4593. case "TupleElementTypes":
  4594. return this.match(types.bracketR);
  4595. case "TypeParametersOrArguments":
  4596. return this.isRelational(">");
  4597. }
  4598. throw new Error("Unreachable");
  4599. }
  4600. tsParseList(kind, parseElement) {
  4601. const result = [];
  4602. while (!this.tsIsListTerminator(kind)) {
  4603. result.push(parseElement());
  4604. }
  4605. return result;
  4606. }
  4607. tsParseDelimitedList(kind, parseElement) {
  4608. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4609. }
  4610. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4611. const result = [];
  4612. for (;;) {
  4613. if (this.tsIsListTerminator(kind)) {
  4614. break;
  4615. }
  4616. const element = parseElement();
  4617. if (element == null) {
  4618. return undefined;
  4619. }
  4620. result.push(element);
  4621. if (this.eat(types.comma)) {
  4622. continue;
  4623. }
  4624. if (this.tsIsListTerminator(kind)) {
  4625. break;
  4626. }
  4627. if (expectSuccess) {
  4628. this.expect(types.comma);
  4629. }
  4630. return undefined;
  4631. }
  4632. return result;
  4633. }
  4634. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4635. if (!skipFirstToken) {
  4636. if (bracket) {
  4637. this.expect(types.bracketL);
  4638. } else {
  4639. this.expectRelational("<");
  4640. }
  4641. }
  4642. const result = this.tsParseDelimitedList(kind, parseElement);
  4643. if (bracket) {
  4644. this.expect(types.bracketR);
  4645. } else {
  4646. this.expectRelational(">");
  4647. }
  4648. return result;
  4649. }
  4650. tsParseImportType() {
  4651. const node = this.startNode();
  4652. this.expect(types._import);
  4653. this.expect(types.parenL);
  4654. if (!this.match(types.string)) {
  4655. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4656. }
  4657. node.argument = this.parseExprAtom();
  4658. this.expect(types.parenR);
  4659. if (this.eat(types.dot)) {
  4660. node.qualifier = this.tsParseEntityName(true);
  4661. }
  4662. if (this.isRelational("<")) {
  4663. node.typeParameters = this.tsParseTypeArguments();
  4664. }
  4665. return this.finishNode(node, "TSImportType");
  4666. }
  4667. tsParseEntityName(allowReservedWords) {
  4668. let entity = this.parseIdentifier();
  4669. while (this.eat(types.dot)) {
  4670. const node = this.startNodeAtNode(entity);
  4671. node.left = entity;
  4672. node.right = this.parseIdentifier(allowReservedWords);
  4673. entity = this.finishNode(node, "TSQualifiedName");
  4674. }
  4675. return entity;
  4676. }
  4677. tsParseTypeReference() {
  4678. const node = this.startNode();
  4679. node.typeName = this.tsParseEntityName(false);
  4680. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4681. node.typeParameters = this.tsParseTypeArguments();
  4682. }
  4683. return this.finishNode(node, "TSTypeReference");
  4684. }
  4685. tsParseThisTypePredicate(lhs) {
  4686. this.next();
  4687. const node = this.startNodeAtNode(lhs);
  4688. node.parameterName = lhs;
  4689. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4690. node.asserts = false;
  4691. return this.finishNode(node, "TSTypePredicate");
  4692. }
  4693. tsParseThisTypeNode() {
  4694. const node = this.startNode();
  4695. this.next();
  4696. return this.finishNode(node, "TSThisType");
  4697. }
  4698. tsParseTypeQuery() {
  4699. const node = this.startNode();
  4700. this.expect(types._typeof);
  4701. if (this.match(types._import)) {
  4702. node.exprName = this.tsParseImportType();
  4703. } else {
  4704. node.exprName = this.tsParseEntityName(true);
  4705. }
  4706. return this.finishNode(node, "TSTypeQuery");
  4707. }
  4708. tsParseTypeParameter() {
  4709. const node = this.startNode();
  4710. node.name = this.parseIdentifierName(node.start);
  4711. node.constraint = this.tsEatThenParseType(types._extends);
  4712. node.default = this.tsEatThenParseType(types.eq);
  4713. return this.finishNode(node, "TSTypeParameter");
  4714. }
  4715. tsTryParseTypeParameters() {
  4716. if (this.isRelational("<")) {
  4717. return this.tsParseTypeParameters();
  4718. }
  4719. }
  4720. tsParseTypeParameters() {
  4721. const node = this.startNode();
  4722. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4723. this.next();
  4724. } else {
  4725. this.unexpected();
  4726. }
  4727. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4728. if (node.params.length === 0) {
  4729. this.raise(node.start, TSErrors.EmptyTypeParameters);
  4730. }
  4731. return this.finishNode(node, "TSTypeParameterDeclaration");
  4732. }
  4733. tsTryNextParseConstantContext() {
  4734. if (this.lookahead().type === types._const) {
  4735. this.next();
  4736. return this.tsParseTypeReference();
  4737. }
  4738. return null;
  4739. }
  4740. tsFillSignature(returnToken, signature) {
  4741. const returnTokenRequired = returnToken === types.arrow;
  4742. signature.typeParameters = this.tsTryParseTypeParameters();
  4743. this.expect(types.parenL);
  4744. signature.parameters = this.tsParseBindingListForSignature();
  4745. if (returnTokenRequired) {
  4746. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4747. } else if (this.match(returnToken)) {
  4748. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4749. }
  4750. }
  4751. tsParseBindingListForSignature() {
  4752. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4753. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4754. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4755. }
  4756. return pattern;
  4757. });
  4758. }
  4759. tsParseTypeMemberSemicolon() {
  4760. if (!this.eat(types.comma)) {
  4761. this.semicolon();
  4762. }
  4763. }
  4764. tsParseSignatureMember(kind, node) {
  4765. this.tsFillSignature(types.colon, node);
  4766. this.tsParseTypeMemberSemicolon();
  4767. return this.finishNode(node, kind);
  4768. }
  4769. tsIsUnambiguouslyIndexSignature() {
  4770. this.next();
  4771. return this.eat(types.name) && this.match(types.colon);
  4772. }
  4773. tsTryParseIndexSignature(node) {
  4774. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4775. return undefined;
  4776. }
  4777. this.expect(types.bracketL);
  4778. const id = this.parseIdentifier();
  4779. id.typeAnnotation = this.tsParseTypeAnnotation();
  4780. this.resetEndLocation(id);
  4781. this.expect(types.bracketR);
  4782. node.parameters = [id];
  4783. const type = this.tsTryParseTypeAnnotation();
  4784. if (type) node.typeAnnotation = type;
  4785. this.tsParseTypeMemberSemicolon();
  4786. return this.finishNode(node, "TSIndexSignature");
  4787. }
  4788. tsParsePropertyOrMethodSignature(node, readonly) {
  4789. if (this.eat(types.question)) node.optional = true;
  4790. const nodeAny = node;
  4791. if (this.match(types.parenL) || this.isRelational("<")) {
  4792. if (readonly) {
  4793. this.raise(node.start, TSErrors.ReadonlyForMethodSignature);
  4794. }
  4795. const method = nodeAny;
  4796. this.tsFillSignature(types.colon, method);
  4797. this.tsParseTypeMemberSemicolon();
  4798. return this.finishNode(method, "TSMethodSignature");
  4799. } else {
  4800. const property = nodeAny;
  4801. if (readonly) property.readonly = true;
  4802. const type = this.tsTryParseTypeAnnotation();
  4803. if (type) property.typeAnnotation = type;
  4804. this.tsParseTypeMemberSemicolon();
  4805. return this.finishNode(property, "TSPropertySignature");
  4806. }
  4807. }
  4808. tsParseTypeMember() {
  4809. const node = this.startNode();
  4810. if (this.match(types.parenL) || this.isRelational("<")) {
  4811. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4812. }
  4813. if (this.match(types._new)) {
  4814. const id = this.startNode();
  4815. this.next();
  4816. if (this.match(types.parenL) || this.isRelational("<")) {
  4817. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4818. } else {
  4819. node.key = this.createIdentifier(id, "new");
  4820. return this.tsParsePropertyOrMethodSignature(node, false);
  4821. }
  4822. }
  4823. this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static"], TSErrors.InvalidModifierOnTypeMember);
  4824. const idx = this.tsTryParseIndexSignature(node);
  4825. if (idx) {
  4826. return idx;
  4827. }
  4828. this.parsePropertyName(node, false);
  4829. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  4830. }
  4831. tsParseTypeLiteral() {
  4832. const node = this.startNode();
  4833. node.members = this.tsParseObjectTypeMembers();
  4834. return this.finishNode(node, "TSTypeLiteral");
  4835. }
  4836. tsParseObjectTypeMembers() {
  4837. this.expect(types.braceL);
  4838. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4839. this.expect(types.braceR);
  4840. return members;
  4841. }
  4842. tsIsStartOfMappedType() {
  4843. this.next();
  4844. if (this.eat(types.plusMin)) {
  4845. return this.isContextual("readonly");
  4846. }
  4847. if (this.isContextual("readonly")) {
  4848. this.next();
  4849. }
  4850. if (!this.match(types.bracketL)) {
  4851. return false;
  4852. }
  4853. this.next();
  4854. if (!this.tsIsIdentifier()) {
  4855. return false;
  4856. }
  4857. this.next();
  4858. return this.match(types._in);
  4859. }
  4860. tsParseMappedTypeParameter() {
  4861. const node = this.startNode();
  4862. node.name = this.parseIdentifierName(node.start);
  4863. node.constraint = this.tsExpectThenParseType(types._in);
  4864. return this.finishNode(node, "TSTypeParameter");
  4865. }
  4866. tsParseMappedType() {
  4867. const node = this.startNode();
  4868. this.expect(types.braceL);
  4869. if (this.match(types.plusMin)) {
  4870. node.readonly = this.state.value;
  4871. this.next();
  4872. this.expectContextual("readonly");
  4873. } else if (this.eatContextual("readonly")) {
  4874. node.readonly = true;
  4875. }
  4876. this.expect(types.bracketL);
  4877. node.typeParameter = this.tsParseMappedTypeParameter();
  4878. node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
  4879. this.expect(types.bracketR);
  4880. if (this.match(types.plusMin)) {
  4881. node.optional = this.state.value;
  4882. this.next();
  4883. this.expect(types.question);
  4884. } else if (this.eat(types.question)) {
  4885. node.optional = true;
  4886. }
  4887. node.typeAnnotation = this.tsTryParseType();
  4888. this.semicolon();
  4889. this.expect(types.braceR);
  4890. return this.finishNode(node, "TSMappedType");
  4891. }
  4892. tsParseTupleType() {
  4893. const node = this.startNode();
  4894. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4895. let seenOptionalElement = false;
  4896. let labeledElements = null;
  4897. node.elementTypes.forEach(elementNode => {
  4898. var _labeledElements;
  4899. let {
  4900. type
  4901. } = elementNode;
  4902. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  4903. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4904. }
  4905. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  4906. if (type === "TSRestType") {
  4907. elementNode = elementNode.typeAnnotation;
  4908. type = elementNode.type;
  4909. }
  4910. const isLabeled = type === "TSNamedTupleMember";
  4911. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  4912. if (labeledElements !== isLabeled) {
  4913. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  4914. }
  4915. });
  4916. return this.finishNode(node, "TSTupleType");
  4917. }
  4918. tsParseTupleElementType() {
  4919. const {
  4920. start: startPos,
  4921. startLoc
  4922. } = this.state;
  4923. const rest = this.eat(types.ellipsis);
  4924. let type = this.tsParseType();
  4925. const optional = this.eat(types.question);
  4926. const labeled = this.eat(types.colon);
  4927. if (labeled) {
  4928. const labeledNode = this.startNodeAtNode(type);
  4929. labeledNode.optional = optional;
  4930. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  4931. labeledNode.label = type.typeName;
  4932. } else {
  4933. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  4934. labeledNode.label = type;
  4935. }
  4936. labeledNode.elementType = this.tsParseType();
  4937. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  4938. } else if (optional) {
  4939. const optionalTypeNode = this.startNodeAtNode(type);
  4940. optionalTypeNode.typeAnnotation = type;
  4941. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  4942. }
  4943. if (rest) {
  4944. const restNode = this.startNodeAt(startPos, startLoc);
  4945. restNode.typeAnnotation = type;
  4946. type = this.finishNode(restNode, "TSRestType");
  4947. }
  4948. return type;
  4949. }
  4950. tsParseParenthesizedType() {
  4951. const node = this.startNode();
  4952. this.expect(types.parenL);
  4953. node.typeAnnotation = this.tsParseType();
  4954. this.expect(types.parenR);
  4955. return this.finishNode(node, "TSParenthesizedType");
  4956. }
  4957. tsParseFunctionOrConstructorType(type, abstract) {
  4958. const node = this.startNode();
  4959. if (type === "TSConstructorType") {
  4960. node.abstract = !!abstract;
  4961. if (abstract) this.next();
  4962. this.next();
  4963. }
  4964. this.tsFillSignature(types.arrow, node);
  4965. return this.finishNode(node, type);
  4966. }
  4967. tsParseLiteralTypeNode() {
  4968. const node = this.startNode();
  4969. node.literal = (() => {
  4970. switch (this.state.type) {
  4971. case types.num:
  4972. case types.bigint:
  4973. case types.string:
  4974. case types._true:
  4975. case types._false:
  4976. return this.parseExprAtom();
  4977. default:
  4978. throw this.unexpected();
  4979. }
  4980. })();
  4981. return this.finishNode(node, "TSLiteralType");
  4982. }
  4983. tsParseTemplateLiteralType() {
  4984. const node = this.startNode();
  4985. node.literal = this.parseTemplate(false);
  4986. return this.finishNode(node, "TSLiteralType");
  4987. }
  4988. parseTemplateSubstitution() {
  4989. if (this.state.inType) return this.tsParseType();
  4990. return super.parseTemplateSubstitution();
  4991. }
  4992. tsParseThisTypeOrThisTypePredicate() {
  4993. const thisKeyword = this.tsParseThisTypeNode();
  4994. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4995. return this.tsParseThisTypePredicate(thisKeyword);
  4996. } else {
  4997. return thisKeyword;
  4998. }
  4999. }
  5000. tsParseNonArrayType() {
  5001. switch (this.state.type) {
  5002. case types.name:
  5003. case types._void:
  5004. case types._null:
  5005. {
  5006. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  5007. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  5008. const node = this.startNode();
  5009. this.next();
  5010. return this.finishNode(node, type);
  5011. }
  5012. return this.tsParseTypeReference();
  5013. }
  5014. case types.string:
  5015. case types.num:
  5016. case types.bigint:
  5017. case types._true:
  5018. case types._false:
  5019. return this.tsParseLiteralTypeNode();
  5020. case types.plusMin:
  5021. if (this.state.value === "-") {
  5022. const node = this.startNode();
  5023. const nextToken = this.lookahead();
  5024. if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
  5025. throw this.unexpected();
  5026. }
  5027. node.literal = this.parseMaybeUnary();
  5028. return this.finishNode(node, "TSLiteralType");
  5029. }
  5030. break;
  5031. case types._this:
  5032. return this.tsParseThisTypeOrThisTypePredicate();
  5033. case types._typeof:
  5034. return this.tsParseTypeQuery();
  5035. case types._import:
  5036. return this.tsParseImportType();
  5037. case types.braceL:
  5038. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  5039. case types.bracketL:
  5040. return this.tsParseTupleType();
  5041. case types.parenL:
  5042. return this.tsParseParenthesizedType();
  5043. case types.backQuote:
  5044. return this.tsParseTemplateLiteralType();
  5045. }
  5046. throw this.unexpected();
  5047. }
  5048. tsParseArrayTypeOrHigher() {
  5049. let type = this.tsParseNonArrayType();
  5050. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  5051. if (this.match(types.bracketR)) {
  5052. const node = this.startNodeAtNode(type);
  5053. node.elementType = type;
  5054. this.expect(types.bracketR);
  5055. type = this.finishNode(node, "TSArrayType");
  5056. } else {
  5057. const node = this.startNodeAtNode(type);
  5058. node.objectType = type;
  5059. node.indexType = this.tsParseType();
  5060. this.expect(types.bracketR);
  5061. type = this.finishNode(node, "TSIndexedAccessType");
  5062. }
  5063. }
  5064. return type;
  5065. }
  5066. tsParseTypeOperator(operator) {
  5067. const node = this.startNode();
  5068. this.expectContextual(operator);
  5069. node.operator = operator;
  5070. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  5071. if (operator === "readonly") {
  5072. this.tsCheckTypeAnnotationForReadOnly(node);
  5073. }
  5074. return this.finishNode(node, "TSTypeOperator");
  5075. }
  5076. tsCheckTypeAnnotationForReadOnly(node) {
  5077. switch (node.typeAnnotation.type) {
  5078. case "TSTupleType":
  5079. case "TSArrayType":
  5080. return;
  5081. default:
  5082. this.raise(node.start, TSErrors.UnexpectedReadonly);
  5083. }
  5084. }
  5085. tsParseInferType() {
  5086. const node = this.startNode();
  5087. this.expectContextual("infer");
  5088. const typeParameter = this.startNode();
  5089. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  5090. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  5091. return this.finishNode(node, "TSInferType");
  5092. }
  5093. tsParseTypeOperatorOrHigher() {
  5094. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  5095. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  5096. }
  5097. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  5098. const node = this.startNode();
  5099. const hasLeadingOperator = this.eat(operator);
  5100. const types = [];
  5101. do {
  5102. types.push(parseConstituentType());
  5103. } while (this.eat(operator));
  5104. if (types.length === 1 && !hasLeadingOperator) {
  5105. return types[0];
  5106. }
  5107. node.types = types;
  5108. return this.finishNode(node, kind);
  5109. }
  5110. tsParseIntersectionTypeOrHigher() {
  5111. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  5112. }
  5113. tsParseUnionTypeOrHigher() {
  5114. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  5115. }
  5116. tsIsStartOfFunctionType() {
  5117. if (this.isRelational("<")) {
  5118. return true;
  5119. }
  5120. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  5121. }
  5122. tsSkipParameterStart() {
  5123. if (this.match(types.name) || this.match(types._this)) {
  5124. this.next();
  5125. return true;
  5126. }
  5127. if (this.match(types.braceL)) {
  5128. let braceStackCounter = 1;
  5129. this.next();
  5130. while (braceStackCounter > 0) {
  5131. if (this.match(types.braceL)) {
  5132. ++braceStackCounter;
  5133. } else if (this.match(types.braceR)) {
  5134. --braceStackCounter;
  5135. }
  5136. this.next();
  5137. }
  5138. return true;
  5139. }
  5140. if (this.match(types.bracketL)) {
  5141. let braceStackCounter = 1;
  5142. this.next();
  5143. while (braceStackCounter > 0) {
  5144. if (this.match(types.bracketL)) {
  5145. ++braceStackCounter;
  5146. } else if (this.match(types.bracketR)) {
  5147. --braceStackCounter;
  5148. }
  5149. this.next();
  5150. }
  5151. return true;
  5152. }
  5153. return false;
  5154. }
  5155. tsIsUnambiguouslyStartOfFunctionType() {
  5156. this.next();
  5157. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  5158. return true;
  5159. }
  5160. if (this.tsSkipParameterStart()) {
  5161. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  5162. return true;
  5163. }
  5164. if (this.match(types.parenR)) {
  5165. this.next();
  5166. if (this.match(types.arrow)) {
  5167. return true;
  5168. }
  5169. }
  5170. }
  5171. return false;
  5172. }
  5173. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  5174. return this.tsInType(() => {
  5175. const t = this.startNode();
  5176. this.expect(returnToken);
  5177. const node = this.startNode();
  5178. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  5179. if (asserts && this.match(types._this)) {
  5180. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  5181. if (thisTypePredicate.type === "TSThisType") {
  5182. node.parameterName = thisTypePredicate;
  5183. node.asserts = true;
  5184. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  5185. } else {
  5186. this.resetStartLocationFromNode(thisTypePredicate, node);
  5187. thisTypePredicate.asserts = true;
  5188. }
  5189. t.typeAnnotation = thisTypePredicate;
  5190. return this.finishNode(t, "TSTypeAnnotation");
  5191. }
  5192. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  5193. if (!typePredicateVariable) {
  5194. if (!asserts) {
  5195. return this.tsParseTypeAnnotation(false, t);
  5196. }
  5197. node.parameterName = this.parseIdentifier();
  5198. node.asserts = asserts;
  5199. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  5200. return this.finishNode(t, "TSTypeAnnotation");
  5201. }
  5202. const type = this.tsParseTypeAnnotation(false);
  5203. node.parameterName = typePredicateVariable;
  5204. node.typeAnnotation = type;
  5205. node.asserts = asserts;
  5206. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  5207. return this.finishNode(t, "TSTypeAnnotation");
  5208. });
  5209. }
  5210. tsTryParseTypeOrTypePredicateAnnotation() {
  5211. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  5212. }
  5213. tsTryParseTypeAnnotation() {
  5214. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  5215. }
  5216. tsTryParseType() {
  5217. return this.tsEatThenParseType(types.colon);
  5218. }
  5219. tsParseTypePredicatePrefix() {
  5220. const id = this.parseIdentifier();
  5221. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  5222. this.next();
  5223. return id;
  5224. }
  5225. }
  5226. tsParseTypePredicateAsserts() {
  5227. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  5228. return false;
  5229. }
  5230. const containsEsc = this.state.containsEsc;
  5231. this.next();
  5232. if (!this.match(types.name) && !this.match(types._this)) {
  5233. return false;
  5234. }
  5235. if (containsEsc) {
  5236. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  5237. }
  5238. return true;
  5239. }
  5240. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  5241. this.tsInType(() => {
  5242. if (eatColon) this.expect(types.colon);
  5243. t.typeAnnotation = this.tsParseType();
  5244. });
  5245. return this.finishNode(t, "TSTypeAnnotation");
  5246. }
  5247. tsParseType() {
  5248. assert(this.state.inType);
  5249. const type = this.tsParseNonConditionalType();
  5250. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  5251. return type;
  5252. }
  5253. const node = this.startNodeAtNode(type);
  5254. node.checkType = type;
  5255. node.extendsType = this.tsParseNonConditionalType();
  5256. this.expect(types.question);
  5257. node.trueType = this.tsParseType();
  5258. this.expect(types.colon);
  5259. node.falseType = this.tsParseType();
  5260. return this.finishNode(node, "TSConditionalType");
  5261. }
  5262. isAbstractConstructorSignature() {
  5263. return this.isContextual("abstract") && this.lookahead().type === types._new;
  5264. }
  5265. tsParseNonConditionalType() {
  5266. if (this.tsIsStartOfFunctionType()) {
  5267. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  5268. }
  5269. if (this.match(types._new)) {
  5270. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  5271. } else if (this.isAbstractConstructorSignature()) {
  5272. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  5273. }
  5274. return this.tsParseUnionTypeOrHigher();
  5275. }
  5276. tsParseTypeAssertion() {
  5277. const node = this.startNode();
  5278. const _const = this.tsTryNextParseConstantContext();
  5279. node.typeAnnotation = _const || this.tsNextThenParseType();
  5280. this.expectRelational(">");
  5281. node.expression = this.parseMaybeUnary();
  5282. return this.finishNode(node, "TSTypeAssertion");
  5283. }
  5284. tsParseHeritageClause(descriptor) {
  5285. const originalStart = this.state.start;
  5286. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  5287. if (!delimitedList.length) {
  5288. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  5289. }
  5290. return delimitedList;
  5291. }
  5292. tsParseExpressionWithTypeArguments() {
  5293. const node = this.startNode();
  5294. node.expression = this.tsParseEntityName(false);
  5295. if (this.isRelational("<")) {
  5296. node.typeParameters = this.tsParseTypeArguments();
  5297. }
  5298. return this.finishNode(node, "TSExpressionWithTypeArguments");
  5299. }
  5300. tsParseInterfaceDeclaration(node) {
  5301. node.id = this.parseIdentifier();
  5302. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  5303. node.typeParameters = this.tsTryParseTypeParameters();
  5304. if (this.eat(types._extends)) {
  5305. node.extends = this.tsParseHeritageClause("extends");
  5306. }
  5307. const body = this.startNode();
  5308. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  5309. node.body = this.finishNode(body, "TSInterfaceBody");
  5310. return this.finishNode(node, "TSInterfaceDeclaration");
  5311. }
  5312. tsParseTypeAliasDeclaration(node) {
  5313. node.id = this.parseIdentifier();
  5314. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  5315. node.typeParameters = this.tsTryParseTypeParameters();
  5316. node.typeAnnotation = this.tsInType(() => {
  5317. this.expect(types.eq);
  5318. if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
  5319. const node = this.startNode();
  5320. this.next();
  5321. return this.finishNode(node, "TSIntrinsicKeyword");
  5322. }
  5323. return this.tsParseType();
  5324. });
  5325. this.semicolon();
  5326. return this.finishNode(node, "TSTypeAliasDeclaration");
  5327. }
  5328. tsInNoContext(cb) {
  5329. const oldContext = this.state.context;
  5330. this.state.context = [oldContext[0]];
  5331. try {
  5332. return cb();
  5333. } finally {
  5334. this.state.context = oldContext;
  5335. }
  5336. }
  5337. tsInType(cb) {
  5338. const oldInType = this.state.inType;
  5339. this.state.inType = true;
  5340. try {
  5341. return cb();
  5342. } finally {
  5343. this.state.inType = oldInType;
  5344. }
  5345. }
  5346. tsEatThenParseType(token) {
  5347. return !this.match(token) ? undefined : this.tsNextThenParseType();
  5348. }
  5349. tsExpectThenParseType(token) {
  5350. return this.tsDoThenParseType(() => this.expect(token));
  5351. }
  5352. tsNextThenParseType() {
  5353. return this.tsDoThenParseType(() => this.next());
  5354. }
  5355. tsDoThenParseType(cb) {
  5356. return this.tsInType(() => {
  5357. cb();
  5358. return this.tsParseType();
  5359. });
  5360. }
  5361. tsParseEnumMember() {
  5362. const node = this.startNode();
  5363. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  5364. if (this.eat(types.eq)) {
  5365. node.initializer = this.parseMaybeAssignAllowIn();
  5366. }
  5367. return this.finishNode(node, "TSEnumMember");
  5368. }
  5369. tsParseEnumDeclaration(node, isConst) {
  5370. if (isConst) node.const = true;
  5371. node.id = this.parseIdentifier();
  5372. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  5373. this.expect(types.braceL);
  5374. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  5375. this.expect(types.braceR);
  5376. return this.finishNode(node, "TSEnumDeclaration");
  5377. }
  5378. tsParseModuleBlock() {
  5379. const node = this.startNode();
  5380. this.scope.enter(SCOPE_OTHER);
  5381. this.expect(types.braceL);
  5382. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  5383. this.scope.exit();
  5384. return this.finishNode(node, "TSModuleBlock");
  5385. }
  5386. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  5387. node.id = this.parseIdentifier();
  5388. if (!nested) {
  5389. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  5390. }
  5391. if (this.eat(types.dot)) {
  5392. const inner = this.startNode();
  5393. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  5394. node.body = inner;
  5395. } else {
  5396. this.scope.enter(SCOPE_TS_MODULE);
  5397. this.prodParam.enter(PARAM);
  5398. node.body = this.tsParseModuleBlock();
  5399. this.prodParam.exit();
  5400. this.scope.exit();
  5401. }
  5402. return this.finishNode(node, "TSModuleDeclaration");
  5403. }
  5404. tsParseAmbientExternalModuleDeclaration(node) {
  5405. if (this.isContextual("global")) {
  5406. node.global = true;
  5407. node.id = this.parseIdentifier();
  5408. } else if (this.match(types.string)) {
  5409. node.id = this.parseExprAtom();
  5410. } else {
  5411. this.unexpected();
  5412. }
  5413. if (this.match(types.braceL)) {
  5414. this.scope.enter(SCOPE_TS_MODULE);
  5415. this.prodParam.enter(PARAM);
  5416. node.body = this.tsParseModuleBlock();
  5417. this.prodParam.exit();
  5418. this.scope.exit();
  5419. } else {
  5420. this.semicolon();
  5421. }
  5422. return this.finishNode(node, "TSModuleDeclaration");
  5423. }
  5424. tsParseImportEqualsDeclaration(node, isExport) {
  5425. node.isExport = isExport || false;
  5426. node.id = this.parseIdentifier();
  5427. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  5428. this.expect(types.eq);
  5429. const moduleReference = this.tsParseModuleReference();
  5430. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  5431. this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType);
  5432. }
  5433. node.moduleReference = moduleReference;
  5434. this.semicolon();
  5435. return this.finishNode(node, "TSImportEqualsDeclaration");
  5436. }
  5437. tsIsExternalModuleReference() {
  5438. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5439. }
  5440. tsParseModuleReference() {
  5441. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5442. }
  5443. tsParseExternalModuleReference() {
  5444. const node = this.startNode();
  5445. this.expectContextual("require");
  5446. this.expect(types.parenL);
  5447. if (!this.match(types.string)) {
  5448. throw this.unexpected();
  5449. }
  5450. node.expression = this.parseExprAtom();
  5451. this.expect(types.parenR);
  5452. return this.finishNode(node, "TSExternalModuleReference");
  5453. }
  5454. tsLookAhead(f) {
  5455. const state = this.state.clone();
  5456. const res = f();
  5457. this.state = state;
  5458. return res;
  5459. }
  5460. tsTryParseAndCatch(f) {
  5461. const result = this.tryParse(abort => f() || abort());
  5462. if (result.aborted || !result.node) return undefined;
  5463. if (result.error) this.state = result.failState;
  5464. return result.node;
  5465. }
  5466. tsTryParse(f) {
  5467. const state = this.state.clone();
  5468. const result = f();
  5469. if (result !== undefined && result !== false) {
  5470. return result;
  5471. } else {
  5472. this.state = state;
  5473. return undefined;
  5474. }
  5475. }
  5476. tsTryParseDeclare(nany) {
  5477. if (this.isLineTerminator()) {
  5478. return;
  5479. }
  5480. let starttype = this.state.type;
  5481. let kind;
  5482. if (this.isContextual("let")) {
  5483. starttype = types._var;
  5484. kind = "let";
  5485. }
  5486. return this.tsInDeclareContext(() => {
  5487. switch (starttype) {
  5488. case types._function:
  5489. nany.declare = true;
  5490. return this.parseFunctionStatement(nany, false, true);
  5491. case types._class:
  5492. nany.declare = true;
  5493. return this.parseClass(nany, true, false);
  5494. case types._const:
  5495. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5496. this.expect(types._const);
  5497. this.expectContextual("enum");
  5498. return this.tsParseEnumDeclaration(nany, true);
  5499. }
  5500. case types._var:
  5501. kind = kind || this.state.value;
  5502. return this.parseVarStatement(nany, kind);
  5503. case types.name:
  5504. {
  5505. const value = this.state.value;
  5506. if (value === "global") {
  5507. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5508. } else {
  5509. return this.tsParseDeclaration(nany, value, true);
  5510. }
  5511. }
  5512. }
  5513. });
  5514. }
  5515. tsTryParseExportDeclaration() {
  5516. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5517. }
  5518. tsParseExpressionStatement(node, expr) {
  5519. switch (expr.name) {
  5520. case "declare":
  5521. {
  5522. const declaration = this.tsTryParseDeclare(node);
  5523. if (declaration) {
  5524. declaration.declare = true;
  5525. return declaration;
  5526. }
  5527. break;
  5528. }
  5529. case "global":
  5530. if (this.match(types.braceL)) {
  5531. this.scope.enter(SCOPE_TS_MODULE);
  5532. this.prodParam.enter(PARAM);
  5533. const mod = node;
  5534. mod.global = true;
  5535. mod.id = expr;
  5536. mod.body = this.tsParseModuleBlock();
  5537. this.scope.exit();
  5538. this.prodParam.exit();
  5539. return this.finishNode(mod, "TSModuleDeclaration");
  5540. }
  5541. break;
  5542. default:
  5543. return this.tsParseDeclaration(node, expr.name, false);
  5544. }
  5545. }
  5546. tsParseDeclaration(node, value, next) {
  5547. switch (value) {
  5548. case "abstract":
  5549. if (this.tsCheckLineTerminator(next) && (this.match(types._class) || this.match(types.name))) {
  5550. return this.tsParseAbstractDeclaration(node);
  5551. }
  5552. break;
  5553. case "enum":
  5554. if (next || this.match(types.name)) {
  5555. if (next) this.next();
  5556. return this.tsParseEnumDeclaration(node, false);
  5557. }
  5558. break;
  5559. case "interface":
  5560. if (this.tsCheckLineTerminator(next) && this.match(types.name)) {
  5561. return this.tsParseInterfaceDeclaration(node);
  5562. }
  5563. break;
  5564. case "module":
  5565. if (this.tsCheckLineTerminator(next)) {
  5566. if (this.match(types.string)) {
  5567. return this.tsParseAmbientExternalModuleDeclaration(node);
  5568. } else if (this.match(types.name)) {
  5569. return this.tsParseModuleOrNamespaceDeclaration(node);
  5570. }
  5571. }
  5572. break;
  5573. case "namespace":
  5574. if (this.tsCheckLineTerminator(next) && this.match(types.name)) {
  5575. return this.tsParseModuleOrNamespaceDeclaration(node);
  5576. }
  5577. break;
  5578. case "type":
  5579. if (this.tsCheckLineTerminator(next) && this.match(types.name)) {
  5580. return this.tsParseTypeAliasDeclaration(node);
  5581. }
  5582. break;
  5583. }
  5584. }
  5585. tsCheckLineTerminator(next) {
  5586. if (next) {
  5587. if (this.hasFollowingLineBreak()) return false;
  5588. this.next();
  5589. return true;
  5590. }
  5591. return !this.isLineTerminator();
  5592. }
  5593. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5594. if (!this.isRelational("<")) {
  5595. return undefined;
  5596. }
  5597. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5598. this.state.maybeInArrowParameters = true;
  5599. const res = this.tsTryParseAndCatch(() => {
  5600. const node = this.startNodeAt(startPos, startLoc);
  5601. node.typeParameters = this.tsParseTypeParameters();
  5602. super.parseFunctionParams(node);
  5603. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5604. this.expect(types.arrow);
  5605. return node;
  5606. });
  5607. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5608. if (!res) {
  5609. return undefined;
  5610. }
  5611. return this.parseArrowExpression(res, null, true);
  5612. }
  5613. tsParseTypeArguments() {
  5614. const node = this.startNode();
  5615. node.params = this.tsInType(() => this.tsInNoContext(() => {
  5616. this.expectRelational("<");
  5617. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  5618. }));
  5619. if (node.params.length === 0) {
  5620. this.raise(node.start, TSErrors.EmptyTypeArguments);
  5621. }
  5622. this.state.exprAllowed = false;
  5623. this.expectRelational(">");
  5624. return this.finishNode(node, "TSTypeParameterInstantiation");
  5625. }
  5626. tsIsDeclarationStart() {
  5627. if (this.match(types.name)) {
  5628. switch (this.state.value) {
  5629. case "abstract":
  5630. case "declare":
  5631. case "enum":
  5632. case "interface":
  5633. case "module":
  5634. case "namespace":
  5635. case "type":
  5636. return true;
  5637. }
  5638. }
  5639. return false;
  5640. }
  5641. isExportDefaultSpecifier() {
  5642. if (this.tsIsDeclarationStart()) return false;
  5643. return super.isExportDefaultSpecifier();
  5644. }
  5645. parseAssignableListItem(allowModifiers, decorators) {
  5646. const startPos = this.state.start;
  5647. const startLoc = this.state.startLoc;
  5648. let accessibility;
  5649. let readonly = false;
  5650. if (allowModifiers !== undefined) {
  5651. accessibility = this.parseAccessModifier();
  5652. readonly = !!this.tsParseModifier(["readonly"]);
  5653. if (allowModifiers === false && (accessibility || readonly)) {
  5654. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  5655. }
  5656. }
  5657. const left = this.parseMaybeDefault();
  5658. this.parseAssignableListItemTypes(left);
  5659. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  5660. if (accessibility || readonly) {
  5661. const pp = this.startNodeAt(startPos, startLoc);
  5662. if (decorators.length) {
  5663. pp.decorators = decorators;
  5664. }
  5665. if (accessibility) pp.accessibility = accessibility;
  5666. if (readonly) pp.readonly = readonly;
  5667. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  5668. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  5669. }
  5670. pp.parameter = elt;
  5671. return this.finishNode(pp, "TSParameterProperty");
  5672. }
  5673. if (decorators.length) {
  5674. left.decorators = decorators;
  5675. }
  5676. return elt;
  5677. }
  5678. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5679. if (this.match(types.colon)) {
  5680. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5681. }
  5682. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  5683. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  5684. this.finishNode(node, bodilessType);
  5685. return;
  5686. }
  5687. if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) {
  5688. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  5689. if (node.declare) {
  5690. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  5691. return;
  5692. }
  5693. }
  5694. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5695. }
  5696. registerFunctionStatementId(node) {
  5697. if (!node.body && node.id) {
  5698. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  5699. } else {
  5700. super.registerFunctionStatementId(...arguments);
  5701. }
  5702. }
  5703. tsCheckForInvalidTypeCasts(items) {
  5704. items.forEach(node => {
  5705. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  5706. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  5707. }
  5708. });
  5709. }
  5710. toReferencedList(exprList, isInParens) {
  5711. this.tsCheckForInvalidTypeCasts(exprList);
  5712. return exprList;
  5713. }
  5714. parseArrayLike(...args) {
  5715. const node = super.parseArrayLike(...args);
  5716. if (node.type === "ArrayExpression") {
  5717. this.tsCheckForInvalidTypeCasts(node.elements);
  5718. }
  5719. return node;
  5720. }
  5721. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5722. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5723. this.state.exprAllowed = false;
  5724. this.next();
  5725. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5726. nonNullExpression.expression = base;
  5727. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5728. }
  5729. if (this.isRelational("<")) {
  5730. const result = this.tsTryParseAndCatch(() => {
  5731. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5732. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5733. if (asyncArrowFn) {
  5734. return asyncArrowFn;
  5735. }
  5736. }
  5737. const node = this.startNodeAt(startPos, startLoc);
  5738. node.callee = base;
  5739. const typeArguments = this.tsParseTypeArguments();
  5740. if (typeArguments) {
  5741. if (!noCalls && this.eat(types.parenL)) {
  5742. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5743. this.tsCheckForInvalidTypeCasts(node.arguments);
  5744. node.typeParameters = typeArguments;
  5745. if (state.optionalChainMember) {
  5746. node.optional = false;
  5747. }
  5748. return this.finishCallExpression(node, state.optionalChainMember);
  5749. } else if (this.match(types.backQuote)) {
  5750. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  5751. result.typeParameters = typeArguments;
  5752. return result;
  5753. }
  5754. }
  5755. this.unexpected();
  5756. });
  5757. if (result) return result;
  5758. }
  5759. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5760. }
  5761. parseNewArguments(node) {
  5762. if (this.isRelational("<")) {
  5763. const typeParameters = this.tsTryParseAndCatch(() => {
  5764. const args = this.tsParseTypeArguments();
  5765. if (!this.match(types.parenL)) this.unexpected();
  5766. return args;
  5767. });
  5768. if (typeParameters) {
  5769. node.typeParameters = typeParameters;
  5770. }
  5771. }
  5772. super.parseNewArguments(node);
  5773. }
  5774. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  5775. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5776. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5777. node.expression = left;
  5778. const _const = this.tsTryNextParseConstantContext();
  5779. if (_const) {
  5780. node.typeAnnotation = _const;
  5781. } else {
  5782. node.typeAnnotation = this.tsNextThenParseType();
  5783. }
  5784. this.finishNode(node, "TSAsExpression");
  5785. this.reScan_lt_gt();
  5786. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  5787. }
  5788. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  5789. }
  5790. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5791. checkDuplicateExports() {}
  5792. parseImport(node) {
  5793. node.importKind = "value";
  5794. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5795. let ahead = this.lookahead();
  5796. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from") && ahead.type !== types.eq) {
  5797. node.importKind = "type";
  5798. this.next();
  5799. ahead = this.lookahead();
  5800. }
  5801. if (this.match(types.name) && ahead.type === types.eq) {
  5802. return this.tsParseImportEqualsDeclaration(node);
  5803. }
  5804. }
  5805. const importNode = super.parseImport(node);
  5806. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5807. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5808. }
  5809. return importNode;
  5810. }
  5811. parseExport(node) {
  5812. if (this.match(types._import)) {
  5813. this.next();
  5814. if (this.isContextual("type") && this.lookaheadCharCode() !== 61) {
  5815. node.importKind = "type";
  5816. this.next();
  5817. } else {
  5818. node.importKind = "value";
  5819. }
  5820. return this.tsParseImportEqualsDeclaration(node, true);
  5821. } else if (this.eat(types.eq)) {
  5822. const assign = node;
  5823. assign.expression = this.parseExpression();
  5824. this.semicolon();
  5825. return this.finishNode(assign, "TSExportAssignment");
  5826. } else if (this.eatContextual("as")) {
  5827. const decl = node;
  5828. this.expectContextual("namespace");
  5829. decl.id = this.parseIdentifier();
  5830. this.semicolon();
  5831. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5832. } else {
  5833. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5834. this.next();
  5835. node.exportKind = "type";
  5836. } else {
  5837. node.exportKind = "value";
  5838. }
  5839. return super.parseExport(node);
  5840. }
  5841. }
  5842. isAbstractClass() {
  5843. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5844. }
  5845. parseExportDefaultExpression() {
  5846. if (this.isAbstractClass()) {
  5847. const cls = this.startNode();
  5848. this.next();
  5849. cls.abstract = true;
  5850. this.parseClass(cls, true, true);
  5851. return cls;
  5852. }
  5853. if (this.state.value === "interface") {
  5854. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5855. if (result) return result;
  5856. }
  5857. return super.parseExportDefaultExpression();
  5858. }
  5859. parseStatementContent(context, topLevel) {
  5860. if (this.state.type === types._const) {
  5861. const ahead = this.lookahead();
  5862. if (ahead.type === types.name && ahead.value === "enum") {
  5863. const node = this.startNode();
  5864. this.expect(types._const);
  5865. this.expectContextual("enum");
  5866. return this.tsParseEnumDeclaration(node, true);
  5867. }
  5868. }
  5869. return super.parseStatementContent(context, topLevel);
  5870. }
  5871. parseAccessModifier() {
  5872. return this.tsParseModifier(["public", "protected", "private"]);
  5873. }
  5874. parseClassMember(classBody, member, state) {
  5875. this.tsParseModifiers(member, ["declare", "private", "public", "protected"]);
  5876. const callParseClassMember = () => {
  5877. super.parseClassMember(classBody, member, state);
  5878. };
  5879. if (member.declare) {
  5880. this.tsInDeclareContext(callParseClassMember);
  5881. } else {
  5882. callParseClassMember();
  5883. }
  5884. }
  5885. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  5886. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5887. const idx = this.tsTryParseIndexSignature(member);
  5888. if (idx) {
  5889. classBody.body.push(idx);
  5890. if (member.abstract) {
  5891. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5892. }
  5893. if (isStatic) {
  5894. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5895. }
  5896. if (member.accessibility) {
  5897. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5898. }
  5899. if (member.declare) {
  5900. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  5901. }
  5902. return;
  5903. }
  5904. if (!this.state.inAbstractClass && member.abstract) {
  5905. this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod);
  5906. }
  5907. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  5908. }
  5909. parsePostMemberNameModifiers(methodOrProp) {
  5910. const optional = this.eat(types.question);
  5911. if (optional) methodOrProp.optional = true;
  5912. if (methodOrProp.readonly && this.match(types.parenL)) {
  5913. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5914. }
  5915. if (methodOrProp.declare && this.match(types.parenL)) {
  5916. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5917. }
  5918. }
  5919. parseExpressionStatement(node, expr) {
  5920. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5921. return decl || super.parseExpressionStatement(node, expr);
  5922. }
  5923. shouldParseExportDeclaration() {
  5924. if (this.tsIsDeclarationStart()) return true;
  5925. return super.shouldParseExportDeclaration();
  5926. }
  5927. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  5928. if (!refNeedsArrowPos || !this.match(types.question)) {
  5929. return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  5930. }
  5931. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  5932. if (!result.node) {
  5933. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5934. return expr;
  5935. }
  5936. if (result.error) this.state = result.failState;
  5937. return result.node;
  5938. }
  5939. parseParenItem(node, startPos, startLoc) {
  5940. node = super.parseParenItem(node, startPos, startLoc);
  5941. if (this.eat(types.question)) {
  5942. node.optional = true;
  5943. this.resetEndLocation(node);
  5944. }
  5945. if (this.match(types.colon)) {
  5946. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5947. typeCastNode.expression = node;
  5948. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5949. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5950. }
  5951. return node;
  5952. }
  5953. parseExportDeclaration(node) {
  5954. const startPos = this.state.start;
  5955. const startLoc = this.state.startLoc;
  5956. const isDeclare = this.eatContextual("declare");
  5957. if (isDeclare && (this.isContextual("declare") || !this.shouldParseExportDeclaration())) {
  5958. throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare);
  5959. }
  5960. let declaration;
  5961. if (this.match(types.name)) {
  5962. declaration = this.tsTryParseExportDeclaration();
  5963. }
  5964. if (!declaration) {
  5965. declaration = super.parseExportDeclaration(node);
  5966. }
  5967. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5968. node.exportKind = "type";
  5969. }
  5970. if (declaration && isDeclare) {
  5971. this.resetStartLocation(declaration, startPos, startLoc);
  5972. declaration.declare = true;
  5973. }
  5974. return declaration;
  5975. }
  5976. parseClassId(node, isStatement, optionalId) {
  5977. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5978. return;
  5979. }
  5980. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5981. const typeParameters = this.tsTryParseTypeParameters();
  5982. if (typeParameters) node.typeParameters = typeParameters;
  5983. }
  5984. parseClassPropertyAnnotation(node) {
  5985. if (!node.optional && this.eat(types.bang)) {
  5986. node.definite = true;
  5987. }
  5988. const type = this.tsTryParseTypeAnnotation();
  5989. if (type) node.typeAnnotation = type;
  5990. }
  5991. parseClassProperty(node) {
  5992. this.parseClassPropertyAnnotation(node);
  5993. if (this.state.isDeclareContext && this.match(types.eq)) {
  5994. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5995. }
  5996. return super.parseClassProperty(node);
  5997. }
  5998. parseClassPrivateProperty(node) {
  5999. if (node.abstract) {
  6000. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  6001. }
  6002. if (node.accessibility) {
  6003. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  6004. }
  6005. this.parseClassPropertyAnnotation(node);
  6006. return super.parseClassPrivateProperty(node);
  6007. }
  6008. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  6009. const typeParameters = this.tsTryParseTypeParameters();
  6010. if (typeParameters && isConstructor) {
  6011. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  6012. }
  6013. if (typeParameters) method.typeParameters = typeParameters;
  6014. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  6015. }
  6016. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  6017. const typeParameters = this.tsTryParseTypeParameters();
  6018. if (typeParameters) method.typeParameters = typeParameters;
  6019. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  6020. }
  6021. parseClassSuper(node) {
  6022. super.parseClassSuper(node);
  6023. if (node.superClass && this.isRelational("<")) {
  6024. node.superTypeParameters = this.tsParseTypeArguments();
  6025. }
  6026. if (this.eatContextual("implements")) {
  6027. node.implements = this.tsParseHeritageClause("implements");
  6028. }
  6029. }
  6030. parseObjPropValue(prop, ...args) {
  6031. const typeParameters = this.tsTryParseTypeParameters();
  6032. if (typeParameters) prop.typeParameters = typeParameters;
  6033. super.parseObjPropValue(prop, ...args);
  6034. }
  6035. parseFunctionParams(node, allowModifiers) {
  6036. const typeParameters = this.tsTryParseTypeParameters();
  6037. if (typeParameters) node.typeParameters = typeParameters;
  6038. super.parseFunctionParams(node, allowModifiers);
  6039. }
  6040. parseVarId(decl, kind) {
  6041. super.parseVarId(decl, kind);
  6042. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  6043. decl.definite = true;
  6044. }
  6045. const type = this.tsTryParseTypeAnnotation();
  6046. if (type) {
  6047. decl.id.typeAnnotation = type;
  6048. this.resetEndLocation(decl.id);
  6049. }
  6050. }
  6051. parseAsyncArrowFromCallExpression(node, call) {
  6052. if (this.match(types.colon)) {
  6053. node.returnType = this.tsParseTypeAnnotation();
  6054. }
  6055. return super.parseAsyncArrowFromCallExpression(node, call);
  6056. }
  6057. parseMaybeAssign(...args) {
  6058. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  6059. let state;
  6060. let jsx;
  6061. let typeCast;
  6062. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  6063. state = this.state.clone();
  6064. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  6065. if (!jsx.error) return jsx.node;
  6066. const {
  6067. context
  6068. } = this.state;
  6069. if (context[context.length - 1] === types$1.j_oTag) {
  6070. context.length -= 2;
  6071. } else if (context[context.length - 1] === types$1.j_expr) {
  6072. context.length -= 1;
  6073. }
  6074. }
  6075. if (!((_jsx = jsx) != null && _jsx.error) && !this.isRelational("<")) {
  6076. return super.parseMaybeAssign(...args);
  6077. }
  6078. let typeParameters;
  6079. state = state || this.state.clone();
  6080. const arrow = this.tryParse(abort => {
  6081. var _typeParameters;
  6082. typeParameters = this.tsParseTypeParameters();
  6083. const expr = super.parseMaybeAssign(...args);
  6084. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  6085. abort();
  6086. }
  6087. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  6088. this.resetStartLocationFromNode(expr, typeParameters);
  6089. }
  6090. expr.typeParameters = typeParameters;
  6091. return expr;
  6092. }, state);
  6093. if (!arrow.error && !arrow.aborted) return arrow.node;
  6094. if (!jsx) {
  6095. assert(!this.hasPlugin("jsx"));
  6096. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  6097. if (!typeCast.error) return typeCast.node;
  6098. }
  6099. if ((_jsx2 = jsx) != null && _jsx2.node) {
  6100. this.state = jsx.failState;
  6101. return jsx.node;
  6102. }
  6103. if (arrow.node) {
  6104. this.state = arrow.failState;
  6105. return arrow.node;
  6106. }
  6107. if ((_typeCast = typeCast) != null && _typeCast.node) {
  6108. this.state = typeCast.failState;
  6109. return typeCast.node;
  6110. }
  6111. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  6112. if (arrow.thrown) throw arrow.error;
  6113. if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error;
  6114. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  6115. }
  6116. parseMaybeUnary(refExpressionErrors) {
  6117. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  6118. return this.tsParseTypeAssertion();
  6119. } else {
  6120. return super.parseMaybeUnary(refExpressionErrors);
  6121. }
  6122. }
  6123. parseArrow(node) {
  6124. if (this.match(types.colon)) {
  6125. const result = this.tryParse(abort => {
  6126. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  6127. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  6128. return returnType;
  6129. });
  6130. if (result.aborted) return;
  6131. if (!result.thrown) {
  6132. if (result.error) this.state = result.failState;
  6133. node.returnType = result.node;
  6134. }
  6135. }
  6136. return super.parseArrow(node);
  6137. }
  6138. parseAssignableListItemTypes(param) {
  6139. if (this.eat(types.question)) {
  6140. if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) {
  6141. this.raise(param.start, TSErrors.PatternIsOptional);
  6142. }
  6143. param.optional = true;
  6144. }
  6145. const type = this.tsTryParseTypeAnnotation();
  6146. if (type) param.typeAnnotation = type;
  6147. this.resetEndLocation(param);
  6148. return param;
  6149. }
  6150. toAssignable(node, isLHS = false) {
  6151. switch (node.type) {
  6152. case "TSTypeCastExpression":
  6153. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  6154. case "TSParameterProperty":
  6155. return super.toAssignable(node, isLHS);
  6156. case "TSAsExpression":
  6157. case "TSNonNullExpression":
  6158. case "TSTypeAssertion":
  6159. node.expression = this.toAssignable(node.expression, isLHS);
  6160. return node;
  6161. default:
  6162. return super.toAssignable(node, isLHS);
  6163. }
  6164. }
  6165. checkLVal(expr, contextDescription, ...args) {
  6166. switch (expr.type) {
  6167. case "TSTypeCastExpression":
  6168. return;
  6169. case "TSParameterProperty":
  6170. this.checkLVal(expr.parameter, "parameter property", ...args);
  6171. return;
  6172. case "TSAsExpression":
  6173. case "TSNonNullExpression":
  6174. case "TSTypeAssertion":
  6175. this.checkLVal(expr.expression, contextDescription, ...args);
  6176. return;
  6177. default:
  6178. super.checkLVal(expr, contextDescription, ...args);
  6179. return;
  6180. }
  6181. }
  6182. parseBindingAtom() {
  6183. switch (this.state.type) {
  6184. case types._this:
  6185. return this.parseIdentifier(true);
  6186. default:
  6187. return super.parseBindingAtom();
  6188. }
  6189. }
  6190. parseMaybeDecoratorArguments(expr) {
  6191. if (this.isRelational("<")) {
  6192. const typeArguments = this.tsParseTypeArguments();
  6193. if (this.match(types.parenL)) {
  6194. const call = super.parseMaybeDecoratorArguments(expr);
  6195. call.typeParameters = typeArguments;
  6196. return call;
  6197. }
  6198. this.unexpected(this.state.start, types.parenL);
  6199. }
  6200. return super.parseMaybeDecoratorArguments(expr);
  6201. }
  6202. isClassMethod() {
  6203. return this.isRelational("<") || super.isClassMethod();
  6204. }
  6205. isClassProperty() {
  6206. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  6207. }
  6208. parseMaybeDefault(...args) {
  6209. const node = super.parseMaybeDefault(...args);
  6210. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  6211. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  6212. }
  6213. return node;
  6214. }
  6215. getTokenFromCode(code) {
  6216. if (this.state.inType && (code === 62 || code === 60)) {
  6217. return this.finishOp(types.relational, 1);
  6218. } else {
  6219. return super.getTokenFromCode(code);
  6220. }
  6221. }
  6222. reScan_lt_gt() {
  6223. if (this.match(types.relational)) {
  6224. const code = this.input.charCodeAt(this.state.start);
  6225. if (code === 60 || code === 62) {
  6226. this.state.pos -= 1;
  6227. this.readToken_lt_gt(code);
  6228. }
  6229. }
  6230. }
  6231. toAssignableList(exprList) {
  6232. for (let i = 0; i < exprList.length; i++) {
  6233. const expr = exprList[i];
  6234. if (!expr) continue;
  6235. switch (expr.type) {
  6236. case "TSTypeCastExpression":
  6237. exprList[i] = this.typeCastToParameter(expr);
  6238. break;
  6239. case "TSAsExpression":
  6240. case "TSTypeAssertion":
  6241. if (!this.state.maybeInArrowParameters) {
  6242. exprList[i] = this.typeCastToParameter(expr);
  6243. } else {
  6244. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  6245. }
  6246. break;
  6247. }
  6248. }
  6249. return super.toAssignableList(...arguments);
  6250. }
  6251. typeCastToParameter(node) {
  6252. node.expression.typeAnnotation = node.typeAnnotation;
  6253. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  6254. return node.expression;
  6255. }
  6256. shouldParseArrow() {
  6257. return this.match(types.colon) || super.shouldParseArrow();
  6258. }
  6259. shouldParseAsyncArrow() {
  6260. return this.match(types.colon) || super.shouldParseAsyncArrow();
  6261. }
  6262. canHaveLeadingDecorator() {
  6263. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  6264. }
  6265. jsxParseOpeningElementAfterName(node) {
  6266. if (this.isRelational("<")) {
  6267. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  6268. if (typeArguments) node.typeParameters = typeArguments;
  6269. }
  6270. return super.jsxParseOpeningElementAfterName(node);
  6271. }
  6272. getGetterSetterExpectedParamCount(method) {
  6273. const baseCount = super.getGetterSetterExpectedParamCount(method);
  6274. const params = this.getObjectOrClassMethodParams(method);
  6275. const firstParam = params[0];
  6276. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  6277. return hasContextParam ? baseCount + 1 : baseCount;
  6278. }
  6279. parseCatchClauseParam() {
  6280. const param = super.parseCatchClauseParam();
  6281. const type = this.tsTryParseTypeAnnotation();
  6282. if (type) {
  6283. param.typeAnnotation = type;
  6284. this.resetEndLocation(param);
  6285. }
  6286. return param;
  6287. }
  6288. tsInDeclareContext(cb) {
  6289. const oldIsDeclareContext = this.state.isDeclareContext;
  6290. this.state.isDeclareContext = true;
  6291. try {
  6292. return cb();
  6293. } finally {
  6294. this.state.isDeclareContext = oldIsDeclareContext;
  6295. }
  6296. }
  6297. parseClass(node, ...args) {
  6298. const oldInAbstractClass = this.state.inAbstractClass;
  6299. this.state.inAbstractClass = !!node.abstract;
  6300. try {
  6301. return super.parseClass(node, ...args);
  6302. } finally {
  6303. this.state.inAbstractClass = oldInAbstractClass;
  6304. }
  6305. }
  6306. tsParseAbstractDeclaration(node) {
  6307. if (this.match(types._class)) {
  6308. node.abstract = true;
  6309. return this.parseClass(node, true, false);
  6310. } else if (this.isContextual("interface")) {
  6311. if (!this.hasFollowingLineBreak()) {
  6312. node.abstract = true;
  6313. this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer);
  6314. this.next();
  6315. return this.tsParseInterfaceDeclaration(node);
  6316. }
  6317. } else {
  6318. this.unexpected(null, types._class);
  6319. }
  6320. }
  6321. parseMethod(...args) {
  6322. const method = super.parseMethod(...args);
  6323. if (method.abstract) {
  6324. const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
  6325. if (hasBody) {
  6326. const {
  6327. key
  6328. } = method;
  6329. this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  6330. }
  6331. }
  6332. return method;
  6333. }
  6334. });
  6335. types.placeholder = new TokenType("%%", {
  6336. startsExpr: true
  6337. });
  6338. var placeholders = (superClass => class extends superClass {
  6339. parsePlaceholder(expectedNode) {
  6340. if (this.match(types.placeholder)) {
  6341. const node = this.startNode();
  6342. this.next();
  6343. this.assertNoSpace("Unexpected space in placeholder.");
  6344. node.name = super.parseIdentifier(true);
  6345. this.assertNoSpace("Unexpected space in placeholder.");
  6346. this.expect(types.placeholder);
  6347. return this.finishPlaceholder(node, expectedNode);
  6348. }
  6349. }
  6350. finishPlaceholder(node, expectedNode) {
  6351. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  6352. node.expectedNode = expectedNode;
  6353. return isFinished ? node : this.finishNode(node, "Placeholder");
  6354. }
  6355. getTokenFromCode(code) {
  6356. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  6357. return this.finishOp(types.placeholder, 2);
  6358. }
  6359. return super.getTokenFromCode(...arguments);
  6360. }
  6361. parseExprAtom() {
  6362. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  6363. }
  6364. parseIdentifier() {
  6365. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  6366. }
  6367. checkReservedWord(word) {
  6368. if (word !== undefined) super.checkReservedWord(...arguments);
  6369. }
  6370. parseBindingAtom() {
  6371. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  6372. }
  6373. checkLVal(expr) {
  6374. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  6375. }
  6376. toAssignable(node) {
  6377. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  6378. node.expectedNode = "Pattern";
  6379. return node;
  6380. }
  6381. return super.toAssignable(...arguments);
  6382. }
  6383. isLet(context) {
  6384. if (super.isLet(context)) {
  6385. return true;
  6386. }
  6387. if (!this.isContextual("let")) {
  6388. return false;
  6389. }
  6390. if (context) return false;
  6391. const nextToken = this.lookahead();
  6392. if (nextToken.type === types.placeholder) {
  6393. return true;
  6394. }
  6395. return false;
  6396. }
  6397. verifyBreakContinue(node) {
  6398. if (node.label && node.label.type === "Placeholder") return;
  6399. super.verifyBreakContinue(...arguments);
  6400. }
  6401. parseExpressionStatement(node, expr) {
  6402. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  6403. return super.parseExpressionStatement(...arguments);
  6404. }
  6405. if (this.match(types.colon)) {
  6406. const stmt = node;
  6407. stmt.label = this.finishPlaceholder(expr, "Identifier");
  6408. this.next();
  6409. stmt.body = this.parseStatement("label");
  6410. return this.finishNode(stmt, "LabeledStatement");
  6411. }
  6412. this.semicolon();
  6413. node.name = expr.name;
  6414. return this.finishPlaceholder(node, "Statement");
  6415. }
  6416. parseBlock() {
  6417. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  6418. }
  6419. parseFunctionId() {
  6420. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  6421. }
  6422. parseClass(node, isStatement, optionalId) {
  6423. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  6424. this.next();
  6425. this.takeDecorators(node);
  6426. const oldStrict = this.state.strict;
  6427. const placeholder = this.parsePlaceholder("Identifier");
  6428. if (placeholder) {
  6429. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  6430. node.id = placeholder;
  6431. } else if (optionalId || !isStatement) {
  6432. node.id = null;
  6433. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  6434. return this.finishNode(node, type);
  6435. } else {
  6436. this.unexpected(null, "A class name is required");
  6437. }
  6438. } else {
  6439. this.parseClassId(node, isStatement, optionalId);
  6440. }
  6441. this.parseClassSuper(node);
  6442. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  6443. return this.finishNode(node, type);
  6444. }
  6445. parseExport(node) {
  6446. const placeholder = this.parsePlaceholder("Identifier");
  6447. if (!placeholder) return super.parseExport(...arguments);
  6448. if (!this.isContextual("from") && !this.match(types.comma)) {
  6449. node.specifiers = [];
  6450. node.source = null;
  6451. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  6452. return this.finishNode(node, "ExportNamedDeclaration");
  6453. }
  6454. this.expectPlugin("exportDefaultFrom");
  6455. const specifier = this.startNode();
  6456. specifier.exported = placeholder;
  6457. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  6458. return super.parseExport(node);
  6459. }
  6460. isExportDefaultSpecifier() {
  6461. if (this.match(types._default)) {
  6462. const next = this.nextTokenStart();
  6463. if (this.isUnparsedContextual(next, "from")) {
  6464. if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
  6465. return true;
  6466. }
  6467. }
  6468. }
  6469. return super.isExportDefaultSpecifier();
  6470. }
  6471. maybeParseExportDefaultSpecifier(node) {
  6472. if (node.specifiers && node.specifiers.length > 0) {
  6473. return true;
  6474. }
  6475. return super.maybeParseExportDefaultSpecifier(...arguments);
  6476. }
  6477. checkExport(node) {
  6478. const {
  6479. specifiers
  6480. } = node;
  6481. if (specifiers != null && specifiers.length) {
  6482. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  6483. }
  6484. super.checkExport(node);
  6485. node.specifiers = specifiers;
  6486. }
  6487. parseImport(node) {
  6488. const placeholder = this.parsePlaceholder("Identifier");
  6489. if (!placeholder) return super.parseImport(...arguments);
  6490. node.specifiers = [];
  6491. if (!this.isContextual("from") && !this.match(types.comma)) {
  6492. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  6493. this.semicolon();
  6494. return this.finishNode(node, "ImportDeclaration");
  6495. }
  6496. const specifier = this.startNodeAtNode(placeholder);
  6497. specifier.local = placeholder;
  6498. this.finishNode(specifier, "ImportDefaultSpecifier");
  6499. node.specifiers.push(specifier);
  6500. if (this.eat(types.comma)) {
  6501. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  6502. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  6503. }
  6504. this.expectContextual("from");
  6505. node.source = this.parseImportSource();
  6506. this.semicolon();
  6507. return this.finishNode(node, "ImportDeclaration");
  6508. }
  6509. parseImportSource() {
  6510. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  6511. }
  6512. });
  6513. var v8intrinsic = (superClass => class extends superClass {
  6514. parseV8Intrinsic() {
  6515. if (this.match(types.modulo)) {
  6516. const v8IntrinsicStart = this.state.start;
  6517. const node = this.startNode();
  6518. this.eat(types.modulo);
  6519. if (this.match(types.name)) {
  6520. const name = this.parseIdentifierName(this.state.start);
  6521. const identifier = this.createIdentifier(node, name);
  6522. identifier.type = "V8IntrinsicIdentifier";
  6523. if (this.match(types.parenL)) {
  6524. return identifier;
  6525. }
  6526. }
  6527. this.unexpected(v8IntrinsicStart);
  6528. }
  6529. }
  6530. parseExprAtom() {
  6531. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  6532. }
  6533. });
  6534. function hasPlugin(plugins, name) {
  6535. return plugins.some(plugin => {
  6536. if (Array.isArray(plugin)) {
  6537. return plugin[0] === name;
  6538. } else {
  6539. return plugin === name;
  6540. }
  6541. });
  6542. }
  6543. function getPluginOption(plugins, name, option) {
  6544. const plugin = plugins.find(plugin => {
  6545. if (Array.isArray(plugin)) {
  6546. return plugin[0] === name;
  6547. } else {
  6548. return plugin === name;
  6549. }
  6550. });
  6551. if (plugin && Array.isArray(plugin)) {
  6552. return plugin[1][option];
  6553. }
  6554. return null;
  6555. }
  6556. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6557. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6558. function validatePlugins(plugins) {
  6559. if (hasPlugin(plugins, "decorators")) {
  6560. if (hasPlugin(plugins, "decorators-legacy")) {
  6561. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6562. }
  6563. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6564. if (decoratorsBeforeExport == null) {
  6565. throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'.");
  6566. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6567. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6568. }
  6569. }
  6570. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6571. throw new Error("Cannot combine flow and typescript plugins.");
  6572. }
  6573. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6574. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6575. }
  6576. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6577. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6578. }
  6579. if (hasPlugin(plugins, "moduleAttributes")) {
  6580. if (hasPlugin(plugins, "importAssertions")) {
  6581. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  6582. }
  6583. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  6584. if (moduleAttributesVerionPluginOption !== "may-2020") {
  6585. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  6586. }
  6587. }
  6588. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6589. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6590. }
  6591. }
  6592. const mixinPlugins = {
  6593. estree,
  6594. jsx,
  6595. flow,
  6596. typescript,
  6597. v8intrinsic,
  6598. placeholders
  6599. };
  6600. const mixinPluginNames = Object.keys(mixinPlugins);
  6601. const defaultOptions = {
  6602. sourceType: "script",
  6603. sourceFilename: undefined,
  6604. startLine: 1,
  6605. allowAwaitOutsideFunction: false,
  6606. allowReturnOutsideFunction: false,
  6607. allowImportExportEverywhere: false,
  6608. allowSuperOutsideMethod: false,
  6609. allowUndeclaredExports: false,
  6610. plugins: [],
  6611. strictMode: null,
  6612. ranges: false,
  6613. tokens: false,
  6614. createParenthesizedExpressions: false,
  6615. errorRecovery: false
  6616. };
  6617. function getOptions(opts) {
  6618. const options = {};
  6619. for (const key of Object.keys(defaultOptions)) {
  6620. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6621. }
  6622. return options;
  6623. }
  6624. class State {
  6625. constructor() {
  6626. this.strict = void 0;
  6627. this.curLine = void 0;
  6628. this.startLoc = void 0;
  6629. this.endLoc = void 0;
  6630. this.errors = [];
  6631. this.potentialArrowAt = -1;
  6632. this.noArrowAt = [];
  6633. this.noArrowParamsConversionAt = [];
  6634. this.maybeInArrowParameters = false;
  6635. this.inPipeline = false;
  6636. this.inType = false;
  6637. this.noAnonFunctionType = false;
  6638. this.inPropertyName = false;
  6639. this.hasFlowComment = false;
  6640. this.isIterator = false;
  6641. this.isDeclareContext = false;
  6642. this.inAbstractClass = false;
  6643. this.topicContext = {
  6644. maxNumOfResolvableTopics: 0,
  6645. maxTopicIndex: null
  6646. };
  6647. this.soloAwait = false;
  6648. this.inFSharpPipelineDirectBody = false;
  6649. this.labels = [];
  6650. this.decoratorStack = [[]];
  6651. this.comments = [];
  6652. this.trailingComments = [];
  6653. this.leadingComments = [];
  6654. this.commentStack = [];
  6655. this.commentPreviousNode = null;
  6656. this.pos = 0;
  6657. this.lineStart = 0;
  6658. this.type = types.eof;
  6659. this.value = null;
  6660. this.start = 0;
  6661. this.end = 0;
  6662. this.lastTokEndLoc = null;
  6663. this.lastTokStartLoc = null;
  6664. this.lastTokStart = 0;
  6665. this.lastTokEnd = 0;
  6666. this.context = [types$1.braceStatement];
  6667. this.exprAllowed = true;
  6668. this.containsEsc = false;
  6669. this.strictErrors = new Map();
  6670. this.exportedIdentifiers = [];
  6671. this.tokensLength = 0;
  6672. }
  6673. init(options) {
  6674. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6675. this.curLine = options.startLine;
  6676. this.startLoc = this.endLoc = this.curPosition();
  6677. }
  6678. curPosition() {
  6679. return new Position(this.curLine, this.pos - this.lineStart);
  6680. }
  6681. clone(skipArrays) {
  6682. const state = new State();
  6683. const keys = Object.keys(this);
  6684. for (let i = 0, length = keys.length; i < length; i++) {
  6685. const key = keys[i];
  6686. let val = this[key];
  6687. if (!skipArrays && Array.isArray(val)) {
  6688. val = val.slice();
  6689. }
  6690. state[key] = val;
  6691. }
  6692. return state;
  6693. }
  6694. }
  6695. var _isDigit = function isDigit(code) {
  6696. return code >= 48 && code <= 57;
  6697. };
  6698. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6699. const forbiddenNumericSeparatorSiblings = {
  6700. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6701. hex: [46, 88, 95, 120]
  6702. };
  6703. const allowedNumericSeparatorSiblings = {};
  6704. allowedNumericSeparatorSiblings.bin = [48, 49];
  6705. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6706. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6707. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6708. class Token {
  6709. constructor(state) {
  6710. this.type = state.type;
  6711. this.value = state.value;
  6712. this.start = state.start;
  6713. this.end = state.end;
  6714. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  6715. }
  6716. }
  6717. class Tokenizer extends ParserError {
  6718. constructor(options, input) {
  6719. super();
  6720. this.isLookahead = void 0;
  6721. this.tokens = [];
  6722. this.state = new State();
  6723. this.state.init(options);
  6724. this.input = input;
  6725. this.length = input.length;
  6726. this.isLookahead = false;
  6727. }
  6728. pushToken(token) {
  6729. this.tokens.length = this.state.tokensLength;
  6730. this.tokens.push(token);
  6731. ++this.state.tokensLength;
  6732. }
  6733. next() {
  6734. if (!this.isLookahead) {
  6735. this.checkKeywordEscapes();
  6736. if (this.options.tokens) {
  6737. this.pushToken(new Token(this.state));
  6738. }
  6739. }
  6740. this.state.lastTokEnd = this.state.end;
  6741. this.state.lastTokStart = this.state.start;
  6742. this.state.lastTokEndLoc = this.state.endLoc;
  6743. this.state.lastTokStartLoc = this.state.startLoc;
  6744. this.nextToken();
  6745. }
  6746. eat(type) {
  6747. if (this.match(type)) {
  6748. this.next();
  6749. return true;
  6750. } else {
  6751. return false;
  6752. }
  6753. }
  6754. match(type) {
  6755. return this.state.type === type;
  6756. }
  6757. lookahead() {
  6758. const old = this.state;
  6759. this.state = old.clone(true);
  6760. this.isLookahead = true;
  6761. this.next();
  6762. this.isLookahead = false;
  6763. const curr = this.state;
  6764. this.state = old;
  6765. return curr;
  6766. }
  6767. nextTokenStart() {
  6768. return this.nextTokenStartSince(this.state.pos);
  6769. }
  6770. nextTokenStartSince(pos) {
  6771. skipWhiteSpace.lastIndex = pos;
  6772. const skip = skipWhiteSpace.exec(this.input);
  6773. return pos + skip[0].length;
  6774. }
  6775. lookaheadCharCode() {
  6776. return this.input.charCodeAt(this.nextTokenStart());
  6777. }
  6778. setStrict(strict) {
  6779. this.state.strict = strict;
  6780. if (strict) {
  6781. this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
  6782. this.state.strictErrors.clear();
  6783. }
  6784. }
  6785. curContext() {
  6786. return this.state.context[this.state.context.length - 1];
  6787. }
  6788. nextToken() {
  6789. const curContext = this.curContext();
  6790. if (!(curContext != null && curContext.preserveSpace)) this.skipSpace();
  6791. this.state.start = this.state.pos;
  6792. this.state.startLoc = this.state.curPosition();
  6793. if (this.state.pos >= this.length) {
  6794. this.finishToken(types.eof);
  6795. return;
  6796. }
  6797. const override = curContext == null ? void 0 : curContext.override;
  6798. if (override) {
  6799. override(this);
  6800. } else {
  6801. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6802. }
  6803. }
  6804. pushComment(block, text, start, end, startLoc, endLoc) {
  6805. const comment = {
  6806. type: block ? "CommentBlock" : "CommentLine",
  6807. value: text,
  6808. start: start,
  6809. end: end,
  6810. loc: new SourceLocation(startLoc, endLoc)
  6811. };
  6812. if (this.options.tokens) this.pushToken(comment);
  6813. this.state.comments.push(comment);
  6814. this.addComment(comment);
  6815. }
  6816. skipBlockComment() {
  6817. const startLoc = this.state.curPosition();
  6818. const start = this.state.pos;
  6819. const end = this.input.indexOf("*/", this.state.pos + 2);
  6820. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  6821. this.state.pos = end + 2;
  6822. lineBreakG.lastIndex = start;
  6823. let match;
  6824. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6825. ++this.state.curLine;
  6826. this.state.lineStart = match.index + match[0].length;
  6827. }
  6828. if (this.isLookahead) return;
  6829. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6830. }
  6831. skipLineComment(startSkip) {
  6832. const start = this.state.pos;
  6833. const startLoc = this.state.curPosition();
  6834. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6835. if (this.state.pos < this.length) {
  6836. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6837. ch = this.input.charCodeAt(this.state.pos);
  6838. }
  6839. }
  6840. if (this.isLookahead) return;
  6841. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6842. }
  6843. skipSpace() {
  6844. loop: while (this.state.pos < this.length) {
  6845. const ch = this.input.charCodeAt(this.state.pos);
  6846. switch (ch) {
  6847. case 32:
  6848. case 160:
  6849. case 9:
  6850. ++this.state.pos;
  6851. break;
  6852. case 13:
  6853. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6854. ++this.state.pos;
  6855. }
  6856. case 10:
  6857. case 8232:
  6858. case 8233:
  6859. ++this.state.pos;
  6860. ++this.state.curLine;
  6861. this.state.lineStart = this.state.pos;
  6862. break;
  6863. case 47:
  6864. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6865. case 42:
  6866. this.skipBlockComment();
  6867. break;
  6868. case 47:
  6869. this.skipLineComment(2);
  6870. break;
  6871. default:
  6872. break loop;
  6873. }
  6874. break;
  6875. default:
  6876. if (isWhitespace(ch)) {
  6877. ++this.state.pos;
  6878. } else {
  6879. break loop;
  6880. }
  6881. }
  6882. }
  6883. }
  6884. finishToken(type, val) {
  6885. this.state.end = this.state.pos;
  6886. this.state.endLoc = this.state.curPosition();
  6887. const prevType = this.state.type;
  6888. this.state.type = type;
  6889. this.state.value = val;
  6890. if (!this.isLookahead) this.updateContext(prevType);
  6891. }
  6892. readToken_numberSign() {
  6893. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6894. return;
  6895. }
  6896. const nextPos = this.state.pos + 1;
  6897. const next = this.input.charCodeAt(nextPos);
  6898. if (next >= 48 && next <= 57) {
  6899. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  6900. }
  6901. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  6902. this.expectPlugin("recordAndTuple");
  6903. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6904. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  6905. }
  6906. if (next === 123) {
  6907. this.finishToken(types.braceHashL);
  6908. } else {
  6909. this.finishToken(types.bracketHashL);
  6910. }
  6911. this.state.pos += 2;
  6912. } else {
  6913. this.finishOp(types.hash, 1);
  6914. }
  6915. }
  6916. readToken_dot() {
  6917. const next = this.input.charCodeAt(this.state.pos + 1);
  6918. if (next >= 48 && next <= 57) {
  6919. this.readNumber(true);
  6920. return;
  6921. }
  6922. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6923. this.state.pos += 3;
  6924. this.finishToken(types.ellipsis);
  6925. } else {
  6926. ++this.state.pos;
  6927. this.finishToken(types.dot);
  6928. }
  6929. }
  6930. readToken_slash() {
  6931. if (this.state.exprAllowed && !this.state.inType) {
  6932. ++this.state.pos;
  6933. this.readRegexp();
  6934. return;
  6935. }
  6936. const next = this.input.charCodeAt(this.state.pos + 1);
  6937. if (next === 61) {
  6938. this.finishOp(types.assign, 2);
  6939. } else {
  6940. this.finishOp(types.slash, 1);
  6941. }
  6942. }
  6943. readToken_interpreter() {
  6944. if (this.state.pos !== 0 || this.length < 2) return false;
  6945. let ch = this.input.charCodeAt(this.state.pos + 1);
  6946. if (ch !== 33) return false;
  6947. const start = this.state.pos;
  6948. this.state.pos += 1;
  6949. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6950. ch = this.input.charCodeAt(this.state.pos);
  6951. }
  6952. const value = this.input.slice(start + 2, this.state.pos);
  6953. this.finishToken(types.interpreterDirective, value);
  6954. return true;
  6955. }
  6956. readToken_mult_modulo(code) {
  6957. let type = code === 42 ? types.star : types.modulo;
  6958. let width = 1;
  6959. let next = this.input.charCodeAt(this.state.pos + 1);
  6960. const exprAllowed = this.state.exprAllowed;
  6961. if (code === 42 && next === 42) {
  6962. width++;
  6963. next = this.input.charCodeAt(this.state.pos + 2);
  6964. type = types.exponent;
  6965. }
  6966. if (next === 61 && !exprAllowed) {
  6967. width++;
  6968. type = types.assign;
  6969. }
  6970. this.finishOp(type, width);
  6971. }
  6972. readToken_pipe_amp(code) {
  6973. const next = this.input.charCodeAt(this.state.pos + 1);
  6974. if (next === code) {
  6975. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6976. this.finishOp(types.assign, 3);
  6977. } else {
  6978. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6979. }
  6980. return;
  6981. }
  6982. if (code === 124) {
  6983. if (next === 62) {
  6984. this.finishOp(types.pipeline, 2);
  6985. return;
  6986. }
  6987. if (this.hasPlugin("recordAndTuple") && next === 125) {
  6988. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6989. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  6990. }
  6991. this.finishOp(types.braceBarR, 2);
  6992. return;
  6993. }
  6994. if (this.hasPlugin("recordAndTuple") && next === 93) {
  6995. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6996. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  6997. }
  6998. this.finishOp(types.bracketBarR, 2);
  6999. return;
  7000. }
  7001. }
  7002. if (next === 61) {
  7003. this.finishOp(types.assign, 2);
  7004. return;
  7005. }
  7006. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  7007. }
  7008. readToken_caret() {
  7009. const next = this.input.charCodeAt(this.state.pos + 1);
  7010. if (next === 61) {
  7011. this.finishOp(types.assign, 2);
  7012. } else {
  7013. this.finishOp(types.bitwiseXOR, 1);
  7014. }
  7015. }
  7016. readToken_plus_min(code) {
  7017. const next = this.input.charCodeAt(this.state.pos + 1);
  7018. if (next === code) {
  7019. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
  7020. this.skipLineComment(3);
  7021. this.skipSpace();
  7022. this.nextToken();
  7023. return;
  7024. }
  7025. this.finishOp(types.incDec, 2);
  7026. return;
  7027. }
  7028. if (next === 61) {
  7029. this.finishOp(types.assign, 2);
  7030. } else {
  7031. this.finishOp(types.plusMin, 1);
  7032. }
  7033. }
  7034. readToken_lt_gt(code) {
  7035. const next = this.input.charCodeAt(this.state.pos + 1);
  7036. let size = 1;
  7037. if (next === code) {
  7038. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  7039. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  7040. this.finishOp(types.assign, size + 1);
  7041. return;
  7042. }
  7043. this.finishOp(types.bitShift, size);
  7044. return;
  7045. }
  7046. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  7047. this.skipLineComment(4);
  7048. this.skipSpace();
  7049. this.nextToken();
  7050. return;
  7051. }
  7052. if (next === 61) {
  7053. size = 2;
  7054. }
  7055. this.finishOp(types.relational, size);
  7056. }
  7057. readToken_eq_excl(code) {
  7058. const next = this.input.charCodeAt(this.state.pos + 1);
  7059. if (next === 61) {
  7060. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  7061. return;
  7062. }
  7063. if (code === 61 && next === 62) {
  7064. this.state.pos += 2;
  7065. this.finishToken(types.arrow);
  7066. return;
  7067. }
  7068. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  7069. }
  7070. readToken_question() {
  7071. const next = this.input.charCodeAt(this.state.pos + 1);
  7072. const next2 = this.input.charCodeAt(this.state.pos + 2);
  7073. if (next === 63) {
  7074. if (next2 === 61) {
  7075. this.finishOp(types.assign, 3);
  7076. } else {
  7077. this.finishOp(types.nullishCoalescing, 2);
  7078. }
  7079. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  7080. this.state.pos += 2;
  7081. this.finishToken(types.questionDot);
  7082. } else {
  7083. ++this.state.pos;
  7084. this.finishToken(types.question);
  7085. }
  7086. }
  7087. getTokenFromCode(code) {
  7088. switch (code) {
  7089. case 46:
  7090. this.readToken_dot();
  7091. return;
  7092. case 40:
  7093. ++this.state.pos;
  7094. this.finishToken(types.parenL);
  7095. return;
  7096. case 41:
  7097. ++this.state.pos;
  7098. this.finishToken(types.parenR);
  7099. return;
  7100. case 59:
  7101. ++this.state.pos;
  7102. this.finishToken(types.semi);
  7103. return;
  7104. case 44:
  7105. ++this.state.pos;
  7106. this.finishToken(types.comma);
  7107. return;
  7108. case 91:
  7109. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  7110. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  7111. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  7112. }
  7113. this.finishToken(types.bracketBarL);
  7114. this.state.pos += 2;
  7115. } else {
  7116. ++this.state.pos;
  7117. this.finishToken(types.bracketL);
  7118. }
  7119. return;
  7120. case 93:
  7121. ++this.state.pos;
  7122. this.finishToken(types.bracketR);
  7123. return;
  7124. case 123:
  7125. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  7126. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  7127. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  7128. }
  7129. this.finishToken(types.braceBarL);
  7130. this.state.pos += 2;
  7131. } else {
  7132. ++this.state.pos;
  7133. this.finishToken(types.braceL);
  7134. }
  7135. return;
  7136. case 125:
  7137. ++this.state.pos;
  7138. this.finishToken(types.braceR);
  7139. return;
  7140. case 58:
  7141. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  7142. this.finishOp(types.doubleColon, 2);
  7143. } else {
  7144. ++this.state.pos;
  7145. this.finishToken(types.colon);
  7146. }
  7147. return;
  7148. case 63:
  7149. this.readToken_question();
  7150. return;
  7151. case 96:
  7152. ++this.state.pos;
  7153. this.finishToken(types.backQuote);
  7154. return;
  7155. case 48:
  7156. {
  7157. const next = this.input.charCodeAt(this.state.pos + 1);
  7158. if (next === 120 || next === 88) {
  7159. this.readRadixNumber(16);
  7160. return;
  7161. }
  7162. if (next === 111 || next === 79) {
  7163. this.readRadixNumber(8);
  7164. return;
  7165. }
  7166. if (next === 98 || next === 66) {
  7167. this.readRadixNumber(2);
  7168. return;
  7169. }
  7170. }
  7171. case 49:
  7172. case 50:
  7173. case 51:
  7174. case 52:
  7175. case 53:
  7176. case 54:
  7177. case 55:
  7178. case 56:
  7179. case 57:
  7180. this.readNumber(false);
  7181. return;
  7182. case 34:
  7183. case 39:
  7184. this.readString(code);
  7185. return;
  7186. case 47:
  7187. this.readToken_slash();
  7188. return;
  7189. case 37:
  7190. case 42:
  7191. this.readToken_mult_modulo(code);
  7192. return;
  7193. case 124:
  7194. case 38:
  7195. this.readToken_pipe_amp(code);
  7196. return;
  7197. case 94:
  7198. this.readToken_caret();
  7199. return;
  7200. case 43:
  7201. case 45:
  7202. this.readToken_plus_min(code);
  7203. return;
  7204. case 60:
  7205. case 62:
  7206. this.readToken_lt_gt(code);
  7207. return;
  7208. case 61:
  7209. case 33:
  7210. this.readToken_eq_excl(code);
  7211. return;
  7212. case 126:
  7213. this.finishOp(types.tilde, 1);
  7214. return;
  7215. case 64:
  7216. ++this.state.pos;
  7217. this.finishToken(types.at);
  7218. return;
  7219. case 35:
  7220. this.readToken_numberSign();
  7221. return;
  7222. case 92:
  7223. this.readWord();
  7224. return;
  7225. default:
  7226. if (isIdentifierStart(code)) {
  7227. this.readWord();
  7228. return;
  7229. }
  7230. }
  7231. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  7232. }
  7233. finishOp(type, size) {
  7234. const str = this.input.slice(this.state.pos, this.state.pos + size);
  7235. this.state.pos += size;
  7236. this.finishToken(type, str);
  7237. }
  7238. readRegexp() {
  7239. const start = this.state.pos;
  7240. let escaped, inClass;
  7241. for (;;) {
  7242. if (this.state.pos >= this.length) {
  7243. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  7244. }
  7245. const ch = this.input.charAt(this.state.pos);
  7246. if (lineBreak.test(ch)) {
  7247. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  7248. }
  7249. if (escaped) {
  7250. escaped = false;
  7251. } else {
  7252. if (ch === "[") {
  7253. inClass = true;
  7254. } else if (ch === "]" && inClass) {
  7255. inClass = false;
  7256. } else if (ch === "/" && !inClass) {
  7257. break;
  7258. }
  7259. escaped = ch === "\\";
  7260. }
  7261. ++this.state.pos;
  7262. }
  7263. const content = this.input.slice(start, this.state.pos);
  7264. ++this.state.pos;
  7265. let mods = "";
  7266. while (this.state.pos < this.length) {
  7267. const char = this.input[this.state.pos];
  7268. const charCode = this.input.codePointAt(this.state.pos);
  7269. if (VALID_REGEX_FLAGS.has(char)) {
  7270. if (mods.indexOf(char) > -1) {
  7271. this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
  7272. }
  7273. } else if (isIdentifierChar(charCode) || charCode === 92) {
  7274. this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
  7275. } else {
  7276. break;
  7277. }
  7278. ++this.state.pos;
  7279. mods += char;
  7280. }
  7281. this.finishToken(types.regexp, {
  7282. pattern: content,
  7283. flags: mods
  7284. });
  7285. }
  7286. readInt(radix, len, forceLen, allowNumSeparator = true) {
  7287. const start = this.state.pos;
  7288. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  7289. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  7290. let invalid = false;
  7291. let total = 0;
  7292. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  7293. const code = this.input.charCodeAt(this.state.pos);
  7294. let val;
  7295. if (code === 95) {
  7296. const prev = this.input.charCodeAt(this.state.pos - 1);
  7297. const next = this.input.charCodeAt(this.state.pos + 1);
  7298. if (allowedSiblings.indexOf(next) === -1) {
  7299. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7300. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  7301. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7302. }
  7303. if (!allowNumSeparator) {
  7304. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  7305. }
  7306. ++this.state.pos;
  7307. continue;
  7308. }
  7309. if (code >= 97) {
  7310. val = code - 97 + 10;
  7311. } else if (code >= 65) {
  7312. val = code - 65 + 10;
  7313. } else if (_isDigit(code)) {
  7314. val = code - 48;
  7315. } else {
  7316. val = Infinity;
  7317. }
  7318. if (val >= radix) {
  7319. if (this.options.errorRecovery && val <= 9) {
  7320. val = 0;
  7321. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  7322. } else if (forceLen) {
  7323. val = 0;
  7324. invalid = true;
  7325. } else {
  7326. break;
  7327. }
  7328. }
  7329. ++this.state.pos;
  7330. total = total * radix + val;
  7331. }
  7332. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  7333. return null;
  7334. }
  7335. return total;
  7336. }
  7337. readRadixNumber(radix) {
  7338. const start = this.state.pos;
  7339. let isBigInt = false;
  7340. this.state.pos += 2;
  7341. const val = this.readInt(radix);
  7342. if (val == null) {
  7343. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  7344. }
  7345. const next = this.input.charCodeAt(this.state.pos);
  7346. if (next === 110) {
  7347. ++this.state.pos;
  7348. isBigInt = true;
  7349. } else if (next === 109) {
  7350. throw this.raise(start, ErrorMessages.InvalidDecimal);
  7351. }
  7352. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7353. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7354. }
  7355. if (isBigInt) {
  7356. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  7357. this.finishToken(types.bigint, str);
  7358. return;
  7359. }
  7360. this.finishToken(types.num, val);
  7361. }
  7362. readNumber(startsWithDot) {
  7363. const start = this.state.pos;
  7364. let isFloat = false;
  7365. let isBigInt = false;
  7366. let isDecimal = false;
  7367. let hasExponent = false;
  7368. let isOctal = false;
  7369. if (!startsWithDot && this.readInt(10) === null) {
  7370. this.raise(start, ErrorMessages.InvalidNumber);
  7371. }
  7372. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  7373. if (hasLeadingZero) {
  7374. const integer = this.input.slice(start, this.state.pos);
  7375. this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
  7376. if (!this.state.strict) {
  7377. const underscorePos = integer.indexOf("_");
  7378. if (underscorePos > 0) {
  7379. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  7380. }
  7381. }
  7382. isOctal = hasLeadingZero && !/[89]/.test(integer);
  7383. }
  7384. let next = this.input.charCodeAt(this.state.pos);
  7385. if (next === 46 && !isOctal) {
  7386. ++this.state.pos;
  7387. this.readInt(10);
  7388. isFloat = true;
  7389. next = this.input.charCodeAt(this.state.pos);
  7390. }
  7391. if ((next === 69 || next === 101) && !isOctal) {
  7392. next = this.input.charCodeAt(++this.state.pos);
  7393. if (next === 43 || next === 45) {
  7394. ++this.state.pos;
  7395. }
  7396. if (this.readInt(10) === null) {
  7397. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  7398. }
  7399. isFloat = true;
  7400. hasExponent = true;
  7401. next = this.input.charCodeAt(this.state.pos);
  7402. }
  7403. if (next === 110) {
  7404. if (isFloat || hasLeadingZero) {
  7405. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  7406. }
  7407. ++this.state.pos;
  7408. isBigInt = true;
  7409. }
  7410. if (next === 109) {
  7411. this.expectPlugin("decimal", this.state.pos);
  7412. if (hasExponent || hasLeadingZero) {
  7413. this.raise(start, ErrorMessages.InvalidDecimal);
  7414. }
  7415. ++this.state.pos;
  7416. isDecimal = true;
  7417. }
  7418. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7419. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7420. }
  7421. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  7422. if (isBigInt) {
  7423. this.finishToken(types.bigint, str);
  7424. return;
  7425. }
  7426. if (isDecimal) {
  7427. this.finishToken(types.decimal, str);
  7428. return;
  7429. }
  7430. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  7431. this.finishToken(types.num, val);
  7432. }
  7433. readCodePoint(throwOnInvalid) {
  7434. const ch = this.input.charCodeAt(this.state.pos);
  7435. let code;
  7436. if (ch === 123) {
  7437. const codePos = ++this.state.pos;
  7438. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  7439. ++this.state.pos;
  7440. if (code !== null && code > 0x10ffff) {
  7441. if (throwOnInvalid) {
  7442. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  7443. } else {
  7444. return null;
  7445. }
  7446. }
  7447. } else {
  7448. code = this.readHexChar(4, false, throwOnInvalid);
  7449. }
  7450. return code;
  7451. }
  7452. readString(quote) {
  7453. let out = "",
  7454. chunkStart = ++this.state.pos;
  7455. for (;;) {
  7456. if (this.state.pos >= this.length) {
  7457. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7458. }
  7459. const ch = this.input.charCodeAt(this.state.pos);
  7460. if (ch === quote) break;
  7461. if (ch === 92) {
  7462. out += this.input.slice(chunkStart, this.state.pos);
  7463. out += this.readEscapedChar(false);
  7464. chunkStart = this.state.pos;
  7465. } else if (ch === 8232 || ch === 8233) {
  7466. ++this.state.pos;
  7467. ++this.state.curLine;
  7468. this.state.lineStart = this.state.pos;
  7469. } else if (isNewLine(ch)) {
  7470. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7471. } else {
  7472. ++this.state.pos;
  7473. }
  7474. }
  7475. out += this.input.slice(chunkStart, this.state.pos++);
  7476. this.finishToken(types.string, out);
  7477. }
  7478. readTmplToken() {
  7479. let out = "",
  7480. chunkStart = this.state.pos,
  7481. containsInvalid = false;
  7482. for (;;) {
  7483. if (this.state.pos >= this.length) {
  7484. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  7485. }
  7486. const ch = this.input.charCodeAt(this.state.pos);
  7487. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  7488. if (this.state.pos === this.state.start && this.match(types.template)) {
  7489. if (ch === 36) {
  7490. this.state.pos += 2;
  7491. this.finishToken(types.dollarBraceL);
  7492. return;
  7493. } else {
  7494. ++this.state.pos;
  7495. this.finishToken(types.backQuote);
  7496. return;
  7497. }
  7498. }
  7499. out += this.input.slice(chunkStart, this.state.pos);
  7500. this.finishToken(types.template, containsInvalid ? null : out);
  7501. return;
  7502. }
  7503. if (ch === 92) {
  7504. out += this.input.slice(chunkStart, this.state.pos);
  7505. const escaped = this.readEscapedChar(true);
  7506. if (escaped === null) {
  7507. containsInvalid = true;
  7508. } else {
  7509. out += escaped;
  7510. }
  7511. chunkStart = this.state.pos;
  7512. } else if (isNewLine(ch)) {
  7513. out += this.input.slice(chunkStart, this.state.pos);
  7514. ++this.state.pos;
  7515. switch (ch) {
  7516. case 13:
  7517. if (this.input.charCodeAt(this.state.pos) === 10) {
  7518. ++this.state.pos;
  7519. }
  7520. case 10:
  7521. out += "\n";
  7522. break;
  7523. default:
  7524. out += String.fromCharCode(ch);
  7525. break;
  7526. }
  7527. ++this.state.curLine;
  7528. this.state.lineStart = this.state.pos;
  7529. chunkStart = this.state.pos;
  7530. } else {
  7531. ++this.state.pos;
  7532. }
  7533. }
  7534. }
  7535. recordStrictModeErrors(pos, message) {
  7536. if (this.state.strict && !this.state.strictErrors.has(pos)) {
  7537. this.raise(pos, message);
  7538. } else {
  7539. this.state.strictErrors.set(pos, message);
  7540. }
  7541. }
  7542. readEscapedChar(inTemplate) {
  7543. const throwOnInvalid = !inTemplate;
  7544. const ch = this.input.charCodeAt(++this.state.pos);
  7545. ++this.state.pos;
  7546. switch (ch) {
  7547. case 110:
  7548. return "\n";
  7549. case 114:
  7550. return "\r";
  7551. case 120:
  7552. {
  7553. const code = this.readHexChar(2, false, throwOnInvalid);
  7554. return code === null ? null : String.fromCharCode(code);
  7555. }
  7556. case 117:
  7557. {
  7558. const code = this.readCodePoint(throwOnInvalid);
  7559. return code === null ? null : String.fromCodePoint(code);
  7560. }
  7561. case 116:
  7562. return "\t";
  7563. case 98:
  7564. return "\b";
  7565. case 118:
  7566. return "\u000b";
  7567. case 102:
  7568. return "\f";
  7569. case 13:
  7570. if (this.input.charCodeAt(this.state.pos) === 10) {
  7571. ++this.state.pos;
  7572. }
  7573. case 10:
  7574. this.state.lineStart = this.state.pos;
  7575. ++this.state.curLine;
  7576. case 8232:
  7577. case 8233:
  7578. return "";
  7579. case 56:
  7580. case 57:
  7581. if (inTemplate) {
  7582. return null;
  7583. } else {
  7584. this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  7585. }
  7586. default:
  7587. if (ch >= 48 && ch <= 55) {
  7588. const codePos = this.state.pos - 1;
  7589. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  7590. let octalStr = match[0];
  7591. let octal = parseInt(octalStr, 8);
  7592. if (octal > 255) {
  7593. octalStr = octalStr.slice(0, -1);
  7594. octal = parseInt(octalStr, 8);
  7595. }
  7596. this.state.pos += octalStr.length - 1;
  7597. const next = this.input.charCodeAt(this.state.pos);
  7598. if (octalStr !== "0" || next === 56 || next === 57) {
  7599. if (inTemplate) {
  7600. return null;
  7601. } else {
  7602. this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
  7603. }
  7604. }
  7605. return String.fromCharCode(octal);
  7606. }
  7607. return String.fromCharCode(ch);
  7608. }
  7609. }
  7610. readHexChar(len, forceLen, throwOnInvalid) {
  7611. const codePos = this.state.pos;
  7612. const n = this.readInt(16, len, forceLen, false);
  7613. if (n === null) {
  7614. if (throwOnInvalid) {
  7615. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  7616. } else {
  7617. this.state.pos = codePos - 1;
  7618. }
  7619. }
  7620. return n;
  7621. }
  7622. readWord1() {
  7623. let word = "";
  7624. this.state.containsEsc = false;
  7625. const start = this.state.pos;
  7626. let chunkStart = this.state.pos;
  7627. while (this.state.pos < this.length) {
  7628. const ch = this.input.codePointAt(this.state.pos);
  7629. if (isIdentifierChar(ch)) {
  7630. this.state.pos += ch <= 0xffff ? 1 : 2;
  7631. } else if (this.state.isIterator && ch === 64) {
  7632. ++this.state.pos;
  7633. } else if (ch === 92) {
  7634. this.state.containsEsc = true;
  7635. word += this.input.slice(chunkStart, this.state.pos);
  7636. const escStart = this.state.pos;
  7637. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  7638. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  7639. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  7640. continue;
  7641. }
  7642. ++this.state.pos;
  7643. const esc = this.readCodePoint(true);
  7644. if (esc !== null) {
  7645. if (!identifierCheck(esc)) {
  7646. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  7647. }
  7648. word += String.fromCodePoint(esc);
  7649. }
  7650. chunkStart = this.state.pos;
  7651. } else {
  7652. break;
  7653. }
  7654. }
  7655. return word + this.input.slice(chunkStart, this.state.pos);
  7656. }
  7657. isIterator(word) {
  7658. return word === "@@iterator" || word === "@@asyncIterator";
  7659. }
  7660. readWord() {
  7661. const word = this.readWord1();
  7662. const type = keywords.get(word) || types.name;
  7663. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  7664. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word);
  7665. }
  7666. this.finishToken(type, word);
  7667. }
  7668. checkKeywordEscapes() {
  7669. const kw = this.state.type.keyword;
  7670. if (kw && this.state.containsEsc) {
  7671. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
  7672. }
  7673. }
  7674. braceIsBlock(prevType) {
  7675. const parent = this.curContext();
  7676. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  7677. return true;
  7678. }
  7679. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  7680. return !parent.isExpr;
  7681. }
  7682. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  7683. return this.hasPrecedingLineBreak();
  7684. }
  7685. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  7686. return true;
  7687. }
  7688. if (prevType === types.braceL) {
  7689. return parent === types$1.braceStatement;
  7690. }
  7691. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  7692. return false;
  7693. }
  7694. if (prevType === types.relational) {
  7695. return true;
  7696. }
  7697. return !this.state.exprAllowed;
  7698. }
  7699. updateContext(prevType) {
  7700. const type = this.state.type;
  7701. let update;
  7702. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  7703. this.state.exprAllowed = false;
  7704. } else if (update = type.updateContext) {
  7705. update.call(this, prevType);
  7706. } else {
  7707. this.state.exprAllowed = type.beforeExpr;
  7708. }
  7709. }
  7710. }
  7711. class ClassScope {
  7712. constructor() {
  7713. this.privateNames = new Set();
  7714. this.loneAccessors = new Map();
  7715. this.undefinedPrivateNames = new Map();
  7716. }
  7717. }
  7718. class ClassScopeHandler {
  7719. constructor(raise) {
  7720. this.stack = [];
  7721. this.undefinedPrivateNames = new Map();
  7722. this.raise = raise;
  7723. }
  7724. current() {
  7725. return this.stack[this.stack.length - 1];
  7726. }
  7727. enter() {
  7728. this.stack.push(new ClassScope());
  7729. }
  7730. exit() {
  7731. const oldClassScope = this.stack.pop();
  7732. const current = this.current();
  7733. for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) {
  7734. if (current) {
  7735. if (!current.undefinedPrivateNames.has(name)) {
  7736. current.undefinedPrivateNames.set(name, pos);
  7737. }
  7738. } else {
  7739. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  7740. }
  7741. }
  7742. }
  7743. declarePrivateName(name, elementType, pos) {
  7744. const classScope = this.current();
  7745. let redefined = classScope.privateNames.has(name);
  7746. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  7747. const accessor = redefined && classScope.loneAccessors.get(name);
  7748. if (accessor) {
  7749. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  7750. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  7751. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  7752. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  7753. redefined = oldKind === newKind || oldStatic !== newStatic;
  7754. if (!redefined) classScope.loneAccessors.delete(name);
  7755. } else if (!redefined) {
  7756. classScope.loneAccessors.set(name, elementType);
  7757. }
  7758. }
  7759. if (redefined) {
  7760. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  7761. }
  7762. classScope.privateNames.add(name);
  7763. classScope.undefinedPrivateNames.delete(name);
  7764. }
  7765. usePrivateName(name, pos) {
  7766. let classScope;
  7767. for (classScope of this.stack) {
  7768. if (classScope.privateNames.has(name)) return;
  7769. }
  7770. if (classScope) {
  7771. classScope.undefinedPrivateNames.set(name, pos);
  7772. } else {
  7773. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  7774. }
  7775. }
  7776. }
  7777. const kExpression = 0,
  7778. kMaybeArrowParameterDeclaration = 1,
  7779. kMaybeAsyncArrowParameterDeclaration = 2,
  7780. kParameterDeclaration = 3;
  7781. class ExpressionScope {
  7782. constructor(type = kExpression) {
  7783. this.type = void 0;
  7784. this.type = type;
  7785. }
  7786. canBeArrowParameterDeclaration() {
  7787. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  7788. }
  7789. isCertainlyParameterDeclaration() {
  7790. return this.type === kParameterDeclaration;
  7791. }
  7792. }
  7793. class ArrowHeadParsingScope extends ExpressionScope {
  7794. constructor(type) {
  7795. super(type);
  7796. this.errors = new Map();
  7797. }
  7798. recordDeclarationError(pos, message) {
  7799. this.errors.set(pos, message);
  7800. }
  7801. clearDeclarationError(pos) {
  7802. this.errors.delete(pos);
  7803. }
  7804. iterateErrors(iterator) {
  7805. this.errors.forEach(iterator);
  7806. }
  7807. }
  7808. class ExpressionScopeHandler {
  7809. constructor(raise) {
  7810. this.stack = [new ExpressionScope()];
  7811. this.raise = raise;
  7812. }
  7813. enter(scope) {
  7814. this.stack.push(scope);
  7815. }
  7816. exit() {
  7817. this.stack.pop();
  7818. }
  7819. recordParameterInitializerError(pos, message) {
  7820. const {
  7821. stack
  7822. } = this;
  7823. let i = stack.length - 1;
  7824. let scope = stack[i];
  7825. while (!scope.isCertainlyParameterDeclaration()) {
  7826. if (scope.canBeArrowParameterDeclaration()) {
  7827. scope.recordDeclarationError(pos, message);
  7828. } else {
  7829. return;
  7830. }
  7831. scope = stack[--i];
  7832. }
  7833. this.raise(pos, message);
  7834. }
  7835. recordParenthesizedIdentifierError(pos, message) {
  7836. const {
  7837. stack
  7838. } = this;
  7839. const scope = stack[stack.length - 1];
  7840. if (scope.isCertainlyParameterDeclaration()) {
  7841. this.raise(pos, message);
  7842. } else if (scope.canBeArrowParameterDeclaration()) {
  7843. scope.recordDeclarationError(pos, message);
  7844. } else {
  7845. return;
  7846. }
  7847. }
  7848. recordAsyncArrowParametersError(pos, message) {
  7849. const {
  7850. stack
  7851. } = this;
  7852. let i = stack.length - 1;
  7853. let scope = stack[i];
  7854. while (scope.canBeArrowParameterDeclaration()) {
  7855. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  7856. scope.recordDeclarationError(pos, message);
  7857. }
  7858. scope = stack[--i];
  7859. }
  7860. }
  7861. validateAsPattern() {
  7862. const {
  7863. stack
  7864. } = this;
  7865. const currentScope = stack[stack.length - 1];
  7866. if (!currentScope.canBeArrowParameterDeclaration()) return;
  7867. currentScope.iterateErrors((message, pos) => {
  7868. this.raise(pos, message);
  7869. let i = stack.length - 2;
  7870. let scope = stack[i];
  7871. while (scope.canBeArrowParameterDeclaration()) {
  7872. scope.clearDeclarationError(pos);
  7873. scope = stack[--i];
  7874. }
  7875. });
  7876. }
  7877. }
  7878. function newParameterDeclarationScope() {
  7879. return new ExpressionScope(kParameterDeclaration);
  7880. }
  7881. function newArrowHeadScope() {
  7882. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  7883. }
  7884. function newAsyncArrowScope() {
  7885. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  7886. }
  7887. function newExpressionScope() {
  7888. return new ExpressionScope();
  7889. }
  7890. class UtilParser extends Tokenizer {
  7891. addExtra(node, key, val) {
  7892. if (!node) return;
  7893. const extra = node.extra = node.extra || {};
  7894. extra[key] = val;
  7895. }
  7896. isRelational(op) {
  7897. return this.match(types.relational) && this.state.value === op;
  7898. }
  7899. expectRelational(op) {
  7900. if (this.isRelational(op)) {
  7901. this.next();
  7902. } else {
  7903. this.unexpected(null, types.relational);
  7904. }
  7905. }
  7906. isContextual(name) {
  7907. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  7908. }
  7909. isUnparsedContextual(nameStart, name) {
  7910. const nameEnd = nameStart + name.length;
  7911. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  7912. }
  7913. isLookaheadContextual(name) {
  7914. const next = this.nextTokenStart();
  7915. return this.isUnparsedContextual(next, name);
  7916. }
  7917. eatContextual(name) {
  7918. return this.isContextual(name) && this.eat(types.name);
  7919. }
  7920. expectContextual(name, message) {
  7921. if (!this.eatContextual(name)) this.unexpected(null, message);
  7922. }
  7923. canInsertSemicolon() {
  7924. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  7925. }
  7926. hasPrecedingLineBreak() {
  7927. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7928. }
  7929. hasFollowingLineBreak() {
  7930. return lineBreak.test(this.input.slice(this.state.end, this.nextTokenStart()));
  7931. }
  7932. isLineTerminator() {
  7933. return this.eat(types.semi) || this.canInsertSemicolon();
  7934. }
  7935. semicolon(allowAsi = true) {
  7936. if (allowAsi ? this.isLineTerminator() : this.eat(types.semi)) return;
  7937. this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon);
  7938. }
  7939. expect(type, pos) {
  7940. this.eat(type) || this.unexpected(pos, type);
  7941. }
  7942. assertNoSpace(message = "Unexpected space.") {
  7943. if (this.state.start > this.state.lastTokEnd) {
  7944. this.raise(this.state.lastTokEnd, message);
  7945. }
  7946. }
  7947. unexpected(pos, messageOrType = "Unexpected token") {
  7948. if (typeof messageOrType !== "string") {
  7949. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  7950. }
  7951. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  7952. }
  7953. expectPlugin(name, pos) {
  7954. if (!this.hasPlugin(name)) {
  7955. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7956. missingPlugin: [name]
  7957. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  7958. }
  7959. return true;
  7960. }
  7961. expectOnePlugin(names, pos) {
  7962. if (!names.some(n => this.hasPlugin(n))) {
  7963. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7964. missingPlugin: names
  7965. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  7966. }
  7967. }
  7968. tryParse(fn, oldState = this.state.clone()) {
  7969. const abortSignal = {
  7970. node: null
  7971. };
  7972. try {
  7973. const node = fn((node = null) => {
  7974. abortSignal.node = node;
  7975. throw abortSignal;
  7976. });
  7977. if (this.state.errors.length > oldState.errors.length) {
  7978. const failState = this.state;
  7979. this.state = oldState;
  7980. return {
  7981. node,
  7982. error: failState.errors[oldState.errors.length],
  7983. thrown: false,
  7984. aborted: false,
  7985. failState
  7986. };
  7987. }
  7988. return {
  7989. node,
  7990. error: null,
  7991. thrown: false,
  7992. aborted: false,
  7993. failState: null
  7994. };
  7995. } catch (error) {
  7996. const failState = this.state;
  7997. this.state = oldState;
  7998. if (error instanceof SyntaxError) {
  7999. return {
  8000. node: null,
  8001. error,
  8002. thrown: true,
  8003. aborted: false,
  8004. failState
  8005. };
  8006. }
  8007. if (error === abortSignal) {
  8008. return {
  8009. node: abortSignal.node,
  8010. error: null,
  8011. thrown: false,
  8012. aborted: true,
  8013. failState
  8014. };
  8015. }
  8016. throw error;
  8017. }
  8018. }
  8019. checkExpressionErrors(refExpressionErrors, andThrow) {
  8020. if (!refExpressionErrors) return false;
  8021. const {
  8022. shorthandAssign,
  8023. doubleProto
  8024. } = refExpressionErrors;
  8025. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  8026. if (shorthandAssign >= 0) {
  8027. this.unexpected(shorthandAssign);
  8028. }
  8029. if (doubleProto >= 0) {
  8030. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  8031. }
  8032. }
  8033. isLiteralPropertyName() {
  8034. return this.match(types.name) || !!this.state.type.keyword || this.match(types.string) || this.match(types.num) || this.match(types.bigint) || this.match(types.decimal);
  8035. }
  8036. isPrivateName(node) {
  8037. return node.type === "PrivateName";
  8038. }
  8039. getPrivateNameSV(node) {
  8040. return node.id.name;
  8041. }
  8042. hasPropertyAsPrivateName(node) {
  8043. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  8044. }
  8045. isOptionalChain(node) {
  8046. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  8047. }
  8048. isObjectProperty(node) {
  8049. return node.type === "ObjectProperty";
  8050. }
  8051. isObjectMethod(node) {
  8052. return node.type === "ObjectMethod";
  8053. }
  8054. initializeScopes(inModule = this.options.sourceType === "module") {
  8055. const oldLabels = this.state.labels;
  8056. this.state.labels = [];
  8057. const oldExportedIdentifiers = this.state.exportedIdentifiers;
  8058. this.state.exportedIdentifiers = [];
  8059. const oldInModule = this.inModule;
  8060. this.inModule = inModule;
  8061. const oldScope = this.scope;
  8062. const ScopeHandler = this.getScopeHandler();
  8063. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  8064. const oldProdParam = this.prodParam;
  8065. this.prodParam = new ProductionParameterHandler();
  8066. const oldClassScope = this.classScope;
  8067. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  8068. const oldExpressionScope = this.expressionScope;
  8069. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  8070. return () => {
  8071. this.state.labels = oldLabels;
  8072. this.state.exportedIdentifiers = oldExportedIdentifiers;
  8073. this.inModule = oldInModule;
  8074. this.scope = oldScope;
  8075. this.prodParam = oldProdParam;
  8076. this.classScope = oldClassScope;
  8077. this.expressionScope = oldExpressionScope;
  8078. };
  8079. }
  8080. enterInitialScopes() {
  8081. let paramFlags = PARAM;
  8082. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  8083. paramFlags |= PARAM_AWAIT;
  8084. }
  8085. this.scope.enter(SCOPE_PROGRAM);
  8086. this.prodParam.enter(paramFlags);
  8087. }
  8088. }
  8089. class ExpressionErrors {
  8090. constructor() {
  8091. this.shorthandAssign = -1;
  8092. this.doubleProto = -1;
  8093. }
  8094. }
  8095. class Node {
  8096. constructor(parser, pos, loc) {
  8097. this.type = void 0;
  8098. this.start = void 0;
  8099. this.end = void 0;
  8100. this.loc = void 0;
  8101. this.range = void 0;
  8102. this.leadingComments = void 0;
  8103. this.trailingComments = void 0;
  8104. this.innerComments = void 0;
  8105. this.extra = void 0;
  8106. this.type = "";
  8107. this.start = pos;
  8108. this.end = 0;
  8109. this.loc = new SourceLocation(loc);
  8110. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  8111. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  8112. }
  8113. __clone() {
  8114. const newNode = new Node();
  8115. const keys = Object.keys(this);
  8116. for (let i = 0, length = keys.length; i < length; i++) {
  8117. const key = keys[i];
  8118. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  8119. newNode[key] = this[key];
  8120. }
  8121. }
  8122. return newNode;
  8123. }
  8124. }
  8125. class NodeUtils extends UtilParser {
  8126. startNode() {
  8127. return new Node(this, this.state.start, this.state.startLoc);
  8128. }
  8129. startNodeAt(pos, loc) {
  8130. return new Node(this, pos, loc);
  8131. }
  8132. startNodeAtNode(type) {
  8133. return this.startNodeAt(type.start, type.loc.start);
  8134. }
  8135. finishNode(node, type) {
  8136. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  8137. }
  8138. finishNodeAt(node, type, pos, loc) {
  8139. node.type = type;
  8140. node.end = pos;
  8141. node.loc.end = loc;
  8142. if (this.options.ranges) node.range[1] = pos;
  8143. this.processComment(node);
  8144. return node;
  8145. }
  8146. resetStartLocation(node, start, startLoc) {
  8147. node.start = start;
  8148. node.loc.start = startLoc;
  8149. if (this.options.ranges) node.range[0] = start;
  8150. }
  8151. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  8152. node.end = end;
  8153. node.loc.end = endLoc;
  8154. if (this.options.ranges) node.range[1] = end;
  8155. }
  8156. resetStartLocationFromNode(node, locationNode) {
  8157. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  8158. }
  8159. }
  8160. const unwrapParenthesizedExpression = node => {
  8161. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  8162. };
  8163. class LValParser extends NodeUtils {
  8164. toAssignable(node, isLHS = false) {
  8165. var _node$extra, _node$extra3;
  8166. let parenthesized = undefined;
  8167. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  8168. parenthesized = unwrapParenthesizedExpression(node);
  8169. if (isLHS) {
  8170. if (parenthesized.type === "Identifier") {
  8171. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  8172. } else if (parenthesized.type !== "MemberExpression") {
  8173. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  8174. }
  8175. } else {
  8176. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  8177. }
  8178. }
  8179. switch (node.type) {
  8180. case "Identifier":
  8181. case "ObjectPattern":
  8182. case "ArrayPattern":
  8183. case "AssignmentPattern":
  8184. break;
  8185. case "ObjectExpression":
  8186. node.type = "ObjectPattern";
  8187. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  8188. var _node$extra2;
  8189. const prop = node.properties[i];
  8190. const isLast = i === last;
  8191. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  8192. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) {
  8193. this.raiseRestNotLast(node.extra.trailingComma);
  8194. }
  8195. }
  8196. break;
  8197. case "ObjectProperty":
  8198. this.toAssignable(node.value, isLHS);
  8199. break;
  8200. case "SpreadElement":
  8201. {
  8202. this.checkToRestConversion(node);
  8203. node.type = "RestElement";
  8204. const arg = node.argument;
  8205. this.toAssignable(arg, isLHS);
  8206. break;
  8207. }
  8208. case "ArrayExpression":
  8209. node.type = "ArrayPattern";
  8210. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  8211. break;
  8212. case "AssignmentExpression":
  8213. if (node.operator !== "=") {
  8214. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  8215. }
  8216. node.type = "AssignmentPattern";
  8217. delete node.operator;
  8218. this.toAssignable(node.left, isLHS);
  8219. break;
  8220. case "ParenthesizedExpression":
  8221. this.toAssignable(parenthesized, isLHS);
  8222. break;
  8223. }
  8224. return node;
  8225. }
  8226. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  8227. if (prop.type === "ObjectMethod") {
  8228. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  8229. this.raise(prop.key.start, error);
  8230. } else if (prop.type === "SpreadElement" && !isLast) {
  8231. this.raiseRestNotLast(prop.start);
  8232. } else {
  8233. this.toAssignable(prop, isLHS);
  8234. }
  8235. }
  8236. toAssignableList(exprList, trailingCommaPos, isLHS) {
  8237. let end = exprList.length;
  8238. if (end) {
  8239. const last = exprList[end - 1];
  8240. if ((last == null ? void 0 : last.type) === "RestElement") {
  8241. --end;
  8242. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  8243. last.type = "RestElement";
  8244. let arg = last.argument;
  8245. this.toAssignable(arg, isLHS);
  8246. arg = unwrapParenthesizedExpression(arg);
  8247. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  8248. this.unexpected(arg.start);
  8249. }
  8250. if (trailingCommaPos) {
  8251. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  8252. }
  8253. --end;
  8254. }
  8255. }
  8256. for (let i = 0; i < end; i++) {
  8257. const elt = exprList[i];
  8258. if (elt) {
  8259. this.toAssignable(elt, isLHS);
  8260. if (elt.type === "RestElement") {
  8261. this.raiseRestNotLast(elt.start);
  8262. }
  8263. }
  8264. }
  8265. return exprList;
  8266. }
  8267. toReferencedList(exprList, isParenthesizedExpr) {
  8268. return exprList;
  8269. }
  8270. toReferencedListDeep(exprList, isParenthesizedExpr) {
  8271. this.toReferencedList(exprList, isParenthesizedExpr);
  8272. for (const expr of exprList) {
  8273. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  8274. this.toReferencedListDeep(expr.elements);
  8275. }
  8276. }
  8277. }
  8278. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  8279. const node = this.startNode();
  8280. this.next();
  8281. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  8282. return this.finishNode(node, "SpreadElement");
  8283. }
  8284. parseRestBinding() {
  8285. const node = this.startNode();
  8286. this.next();
  8287. node.argument = this.parseBindingAtom();
  8288. return this.finishNode(node, "RestElement");
  8289. }
  8290. parseBindingAtom() {
  8291. switch (this.state.type) {
  8292. case types.bracketL:
  8293. {
  8294. const node = this.startNode();
  8295. this.next();
  8296. node.elements = this.parseBindingList(types.bracketR, 93, true);
  8297. return this.finishNode(node, "ArrayPattern");
  8298. }
  8299. case types.braceL:
  8300. return this.parseObjectLike(types.braceR, true);
  8301. }
  8302. return this.parseIdentifier();
  8303. }
  8304. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  8305. const elts = [];
  8306. let first = true;
  8307. while (!this.eat(close)) {
  8308. if (first) {
  8309. first = false;
  8310. } else {
  8311. this.expect(types.comma);
  8312. }
  8313. if (allowEmpty && this.match(types.comma)) {
  8314. elts.push(null);
  8315. } else if (this.eat(close)) {
  8316. break;
  8317. } else if (this.match(types.ellipsis)) {
  8318. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  8319. this.checkCommaAfterRest(closeCharCode);
  8320. this.expect(close);
  8321. break;
  8322. } else {
  8323. const decorators = [];
  8324. if (this.match(types.at) && this.hasPlugin("decorators")) {
  8325. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  8326. }
  8327. while (this.match(types.at)) {
  8328. decorators.push(this.parseDecorator());
  8329. }
  8330. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  8331. }
  8332. }
  8333. return elts;
  8334. }
  8335. parseAssignableListItem(allowModifiers, decorators) {
  8336. const left = this.parseMaybeDefault();
  8337. this.parseAssignableListItemTypes(left);
  8338. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  8339. if (decorators.length) {
  8340. left.decorators = decorators;
  8341. }
  8342. return elt;
  8343. }
  8344. parseAssignableListItemTypes(param) {
  8345. return param;
  8346. }
  8347. parseMaybeDefault(startPos, startLoc, left) {
  8348. var _startLoc, _startPos, _left;
  8349. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  8350. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  8351. left = (_left = left) != null ? _left : this.parseBindingAtom();
  8352. if (!this.eat(types.eq)) return left;
  8353. const node = this.startNodeAt(startPos, startLoc);
  8354. node.left = left;
  8355. node.right = this.parseMaybeAssignAllowIn();
  8356. return this.finishNode(node, "AssignmentPattern");
  8357. }
  8358. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  8359. switch (expr.type) {
  8360. case "Identifier":
  8361. {
  8362. const {
  8363. name
  8364. } = expr;
  8365. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  8366. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  8367. }
  8368. if (checkClashes) {
  8369. if (checkClashes.has(name)) {
  8370. this.raise(expr.start, ErrorMessages.ParamDupe);
  8371. } else {
  8372. checkClashes.add(name);
  8373. }
  8374. }
  8375. if (disallowLetBinding && name === "let") {
  8376. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  8377. }
  8378. if (!(bindingType & BIND_NONE)) {
  8379. this.scope.declareName(name, bindingType, expr.start);
  8380. }
  8381. break;
  8382. }
  8383. case "MemberExpression":
  8384. if (bindingType !== BIND_NONE) {
  8385. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  8386. }
  8387. break;
  8388. case "ObjectPattern":
  8389. for (let prop of expr.properties) {
  8390. if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
  8391. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  8392. }
  8393. break;
  8394. case "ArrayPattern":
  8395. for (const elem of expr.elements) {
  8396. if (elem) {
  8397. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  8398. }
  8399. }
  8400. break;
  8401. case "AssignmentPattern":
  8402. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  8403. break;
  8404. case "RestElement":
  8405. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  8406. break;
  8407. case "ParenthesizedExpression":
  8408. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  8409. break;
  8410. default:
  8411. {
  8412. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  8413. }
  8414. }
  8415. }
  8416. checkToRestConversion(node) {
  8417. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  8418. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  8419. }
  8420. }
  8421. checkCommaAfterRest(close) {
  8422. if (this.match(types.comma)) {
  8423. if (this.lookaheadCharCode() === close) {
  8424. this.raiseTrailingCommaAfterRest(this.state.start);
  8425. } else {
  8426. this.raiseRestNotLast(this.state.start);
  8427. }
  8428. }
  8429. }
  8430. raiseRestNotLast(pos) {
  8431. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  8432. }
  8433. raiseTrailingCommaAfterRest(pos) {
  8434. this.raise(pos, ErrorMessages.RestTrailingComma);
  8435. }
  8436. }
  8437. class ExpressionParser extends LValParser {
  8438. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  8439. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  8440. return;
  8441. }
  8442. const key = prop.key;
  8443. const name = key.type === "Identifier" ? key.name : key.value;
  8444. if (name === "__proto__") {
  8445. if (isRecord) {
  8446. this.raise(key.start, ErrorMessages.RecordNoProto);
  8447. return;
  8448. }
  8449. if (protoRef.used) {
  8450. if (refExpressionErrors) {
  8451. if (refExpressionErrors.doubleProto === -1) {
  8452. refExpressionErrors.doubleProto = key.start;
  8453. }
  8454. } else {
  8455. this.raise(key.start, ErrorMessages.DuplicateProto);
  8456. }
  8457. }
  8458. protoRef.used = true;
  8459. }
  8460. }
  8461. shouldExitDescending(expr, potentialArrowAt) {
  8462. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  8463. }
  8464. getExpression() {
  8465. let paramFlags = PARAM;
  8466. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  8467. paramFlags |= PARAM_AWAIT;
  8468. }
  8469. this.scope.enter(SCOPE_PROGRAM);
  8470. this.prodParam.enter(paramFlags);
  8471. this.nextToken();
  8472. const expr = this.parseExpression();
  8473. if (!this.match(types.eof)) {
  8474. this.unexpected();
  8475. }
  8476. expr.comments = this.state.comments;
  8477. expr.errors = this.state.errors;
  8478. if (this.options.tokens) {
  8479. expr.tokens = this.tokens;
  8480. }
  8481. return expr;
  8482. }
  8483. parseExpression(disallowIn, refExpressionErrors) {
  8484. if (disallowIn) {
  8485. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8486. }
  8487. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8488. }
  8489. parseExpressionBase(refExpressionErrors) {
  8490. const startPos = this.state.start;
  8491. const startLoc = this.state.startLoc;
  8492. const expr = this.parseMaybeAssign(refExpressionErrors);
  8493. if (this.match(types.comma)) {
  8494. const node = this.startNodeAt(startPos, startLoc);
  8495. node.expressions = [expr];
  8496. while (this.eat(types.comma)) {
  8497. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  8498. }
  8499. this.toReferencedList(node.expressions);
  8500. return this.finishNode(node, "SequenceExpression");
  8501. }
  8502. return expr;
  8503. }
  8504. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8505. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8506. }
  8507. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8508. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8509. }
  8510. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8511. const startPos = this.state.start;
  8512. const startLoc = this.state.startLoc;
  8513. if (this.isContextual("yield")) {
  8514. if (this.prodParam.hasYield) {
  8515. this.state.exprAllowed = true;
  8516. let left = this.parseYield();
  8517. if (afterLeftParse) {
  8518. left = afterLeftParse.call(this, left, startPos, startLoc);
  8519. }
  8520. return left;
  8521. }
  8522. }
  8523. let ownExpressionErrors;
  8524. if (refExpressionErrors) {
  8525. ownExpressionErrors = false;
  8526. } else {
  8527. refExpressionErrors = new ExpressionErrors();
  8528. ownExpressionErrors = true;
  8529. }
  8530. if (this.match(types.parenL) || this.match(types.name)) {
  8531. this.state.potentialArrowAt = this.state.start;
  8532. }
  8533. let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
  8534. if (afterLeftParse) {
  8535. left = afterLeftParse.call(this, left, startPos, startLoc);
  8536. }
  8537. if (this.state.type.isAssign) {
  8538. const node = this.startNodeAt(startPos, startLoc);
  8539. const operator = this.state.value;
  8540. node.operator = operator;
  8541. if (this.match(types.eq)) {
  8542. node.left = this.toAssignable(left, true);
  8543. refExpressionErrors.doubleProto = -1;
  8544. } else {
  8545. node.left = left;
  8546. }
  8547. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  8548. refExpressionErrors.shorthandAssign = -1;
  8549. }
  8550. this.checkLVal(left, "assignment expression");
  8551. this.next();
  8552. node.right = this.parseMaybeAssign();
  8553. return this.finishNode(node, "AssignmentExpression");
  8554. } else if (ownExpressionErrors) {
  8555. this.checkExpressionErrors(refExpressionErrors, true);
  8556. }
  8557. return left;
  8558. }
  8559. parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
  8560. const startPos = this.state.start;
  8561. const startLoc = this.state.startLoc;
  8562. const potentialArrowAt = this.state.potentialArrowAt;
  8563. const expr = this.parseExprOps(refExpressionErrors);
  8564. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8565. return expr;
  8566. }
  8567. return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  8568. }
  8569. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  8570. if (this.eat(types.question)) {
  8571. const node = this.startNodeAt(startPos, startLoc);
  8572. node.test = expr;
  8573. node.consequent = this.parseMaybeAssignAllowIn();
  8574. this.expect(types.colon);
  8575. node.alternate = this.parseMaybeAssign();
  8576. return this.finishNode(node, "ConditionalExpression");
  8577. }
  8578. return expr;
  8579. }
  8580. parseExprOps(refExpressionErrors) {
  8581. const startPos = this.state.start;
  8582. const startLoc = this.state.startLoc;
  8583. const potentialArrowAt = this.state.potentialArrowAt;
  8584. const expr = this.parseMaybeUnary(refExpressionErrors);
  8585. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8586. return expr;
  8587. }
  8588. return this.parseExprOp(expr, startPos, startLoc, -1);
  8589. }
  8590. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8591. let prec = this.state.type.binop;
  8592. if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
  8593. if (prec > minPrec) {
  8594. const op = this.state.type;
  8595. if (op === types.pipeline) {
  8596. this.expectPlugin("pipelineOperator");
  8597. if (this.state.inFSharpPipelineDirectBody) {
  8598. return left;
  8599. }
  8600. this.state.inPipeline = true;
  8601. this.checkPipelineAtInfixOperator(left, leftStartPos);
  8602. }
  8603. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8604. node.left = left;
  8605. node.operator = this.state.value;
  8606. if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  8607. this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  8608. }
  8609. const logical = op === types.logicalOR || op === types.logicalAND;
  8610. const coalesce = op === types.nullishCoalescing;
  8611. if (coalesce) {
  8612. prec = types.logicalAND.binop;
  8613. }
  8614. this.next();
  8615. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  8616. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  8617. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  8618. }
  8619. }
  8620. node.right = this.parseExprOpRightExpr(op, prec);
  8621. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  8622. const nextOp = this.state.type;
  8623. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  8624. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  8625. }
  8626. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8627. }
  8628. }
  8629. return left;
  8630. }
  8631. parseExprOpRightExpr(op, prec) {
  8632. const startPos = this.state.start;
  8633. const startLoc = this.state.startLoc;
  8634. switch (op) {
  8635. case types.pipeline:
  8636. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  8637. case "smart":
  8638. return this.withTopicPermittingContext(() => {
  8639. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  8640. });
  8641. case "fsharp":
  8642. return this.withSoloAwaitPermittingContext(() => {
  8643. return this.parseFSharpPipelineBody(prec);
  8644. });
  8645. }
  8646. default:
  8647. return this.parseExprOpBaseRightExpr(op, prec);
  8648. }
  8649. }
  8650. parseExprOpBaseRightExpr(op, prec) {
  8651. const startPos = this.state.start;
  8652. const startLoc = this.state.startLoc;
  8653. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
  8654. }
  8655. parseMaybeUnary(refExpressionErrors) {
  8656. const startPos = this.state.start;
  8657. const startLoc = this.state.startLoc;
  8658. const isAwait = this.isContextual("await");
  8659. if (isAwait && this.isAwaitAllowed()) {
  8660. this.next();
  8661. return this.parseAwait(startPos, startLoc);
  8662. }
  8663. if (this.isContextual("module") && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
  8664. return this.parseModuleExpression();
  8665. }
  8666. const update = this.match(types.incDec);
  8667. const node = this.startNode();
  8668. if (this.state.type.prefix) {
  8669. node.operator = this.state.value;
  8670. node.prefix = true;
  8671. if (this.match(types._throw)) {
  8672. this.expectPlugin("throwExpressions");
  8673. }
  8674. const isDelete = this.match(types._delete);
  8675. this.next();
  8676. node.argument = this.parseMaybeUnary();
  8677. this.checkExpressionErrors(refExpressionErrors, true);
  8678. if (this.state.strict && isDelete) {
  8679. const arg = node.argument;
  8680. if (arg.type === "Identifier") {
  8681. this.raise(node.start, ErrorMessages.StrictDelete);
  8682. } else if (this.hasPropertyAsPrivateName(arg)) {
  8683. this.raise(node.start, ErrorMessages.DeletePrivateField);
  8684. }
  8685. }
  8686. if (!update) {
  8687. return this.finishNode(node, "UnaryExpression");
  8688. }
  8689. }
  8690. const expr = this.parseUpdate(node, update, refExpressionErrors);
  8691. if (isAwait) {
  8692. const startsExpr = this.hasPlugin("v8intrinsic") ? this.state.type.startsExpr : this.state.type.startsExpr && !this.match(types.modulo);
  8693. if (startsExpr && !this.isAmbiguousAwait()) {
  8694. this.raiseOverwrite(startPos, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction);
  8695. return this.parseAwait(startPos, startLoc);
  8696. }
  8697. }
  8698. return expr;
  8699. }
  8700. parseUpdate(node, update, refExpressionErrors) {
  8701. if (update) {
  8702. this.checkLVal(node.argument, "prefix operation");
  8703. return this.finishNode(node, "UpdateExpression");
  8704. }
  8705. const startPos = this.state.start;
  8706. const startLoc = this.state.startLoc;
  8707. let expr = this.parseExprSubscripts(refExpressionErrors);
  8708. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  8709. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  8710. const node = this.startNodeAt(startPos, startLoc);
  8711. node.operator = this.state.value;
  8712. node.prefix = false;
  8713. node.argument = expr;
  8714. this.checkLVal(expr, "postfix operation");
  8715. this.next();
  8716. expr = this.finishNode(node, "UpdateExpression");
  8717. }
  8718. return expr;
  8719. }
  8720. parseExprSubscripts(refExpressionErrors) {
  8721. const startPos = this.state.start;
  8722. const startLoc = this.state.startLoc;
  8723. const potentialArrowAt = this.state.potentialArrowAt;
  8724. const expr = this.parseExprAtom(refExpressionErrors);
  8725. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8726. return expr;
  8727. }
  8728. return this.parseSubscripts(expr, startPos, startLoc);
  8729. }
  8730. parseSubscripts(base, startPos, startLoc, noCalls) {
  8731. const state = {
  8732. optionalChainMember: false,
  8733. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  8734. stop: false
  8735. };
  8736. do {
  8737. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  8738. state.maybeAsyncArrow = false;
  8739. } while (!state.stop);
  8740. return base;
  8741. }
  8742. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8743. if (!noCalls && this.eat(types.doubleColon)) {
  8744. return this.parseBind(base, startPos, startLoc, noCalls, state);
  8745. } else if (this.match(types.backQuote)) {
  8746. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8747. }
  8748. let optional = false;
  8749. if (this.match(types.questionDot)) {
  8750. if (noCalls && this.lookaheadCharCode() === 40) {
  8751. state.stop = true;
  8752. return base;
  8753. }
  8754. state.optionalChainMember = optional = true;
  8755. this.next();
  8756. }
  8757. if (!noCalls && this.match(types.parenL)) {
  8758. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  8759. } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
  8760. return this.parseMember(base, startPos, startLoc, state, optional);
  8761. } else {
  8762. state.stop = true;
  8763. return base;
  8764. }
  8765. }
  8766. parseMember(base, startPos, startLoc, state, optional) {
  8767. const node = this.startNodeAt(startPos, startLoc);
  8768. const computed = this.eat(types.bracketL);
  8769. node.object = base;
  8770. node.computed = computed;
  8771. const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
  8772. if (this.isPrivateName(property)) {
  8773. if (node.object.type === "Super") {
  8774. this.raise(startPos, ErrorMessages.SuperPrivateField);
  8775. }
  8776. this.classScope.usePrivateName(this.getPrivateNameSV(property), property.start);
  8777. }
  8778. node.property = property;
  8779. if (computed) {
  8780. this.expect(types.bracketR);
  8781. }
  8782. if (state.optionalChainMember) {
  8783. node.optional = optional;
  8784. return this.finishNode(node, "OptionalMemberExpression");
  8785. } else {
  8786. return this.finishNode(node, "MemberExpression");
  8787. }
  8788. }
  8789. parseBind(base, startPos, startLoc, noCalls, state) {
  8790. const node = this.startNodeAt(startPos, startLoc);
  8791. node.object = base;
  8792. node.callee = this.parseNoCallExpr();
  8793. state.stop = true;
  8794. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  8795. }
  8796. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  8797. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8798. this.state.maybeInArrowParameters = true;
  8799. this.next();
  8800. let node = this.startNodeAt(startPos, startLoc);
  8801. node.callee = base;
  8802. if (state.maybeAsyncArrow) {
  8803. this.expressionScope.enter(newAsyncArrowScope());
  8804. }
  8805. if (state.optionalChainMember) {
  8806. node.optional = optional;
  8807. }
  8808. if (optional) {
  8809. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8810. } else {
  8811. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  8812. }
  8813. this.finishCallExpression(node, state.optionalChainMember);
  8814. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  8815. state.stop = true;
  8816. this.expressionScope.validateAsPattern();
  8817. this.expressionScope.exit();
  8818. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  8819. } else {
  8820. if (state.maybeAsyncArrow) {
  8821. this.expressionScope.exit();
  8822. }
  8823. this.toReferencedArguments(node);
  8824. }
  8825. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8826. return node;
  8827. }
  8828. toReferencedArguments(node, isParenthesizedExpr) {
  8829. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  8830. }
  8831. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  8832. const node = this.startNodeAt(startPos, startLoc);
  8833. node.tag = base;
  8834. node.quasi = this.parseTemplate(true);
  8835. if (state.optionalChainMember) {
  8836. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  8837. }
  8838. return this.finishNode(node, "TaggedTemplateExpression");
  8839. }
  8840. atPossibleAsyncArrow(base) {
  8841. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  8842. }
  8843. finishCallExpression(node, optional) {
  8844. if (node.callee.type === "Import") {
  8845. if (node.arguments.length === 2) {
  8846. if (!this.hasPlugin("moduleAttributes")) {
  8847. this.expectPlugin("importAssertions");
  8848. }
  8849. }
  8850. if (node.arguments.length === 0 || node.arguments.length > 2) {
  8851. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  8852. } else {
  8853. for (const arg of node.arguments) {
  8854. if (arg.type === "SpreadElement") {
  8855. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  8856. }
  8857. }
  8858. }
  8859. }
  8860. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  8861. }
  8862. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  8863. const elts = [];
  8864. let first = true;
  8865. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8866. this.state.inFSharpPipelineDirectBody = false;
  8867. while (!this.eat(close)) {
  8868. if (first) {
  8869. first = false;
  8870. } else {
  8871. this.expect(types.comma);
  8872. if (this.match(close)) {
  8873. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  8874. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  8875. }
  8876. if (nodeForExtra) {
  8877. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8878. }
  8879. this.next();
  8880. break;
  8881. }
  8882. }
  8883. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8884. start: 0
  8885. } : undefined, allowPlaceholder));
  8886. }
  8887. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8888. return elts;
  8889. }
  8890. shouldParseAsyncArrow() {
  8891. return this.match(types.arrow) && !this.canInsertSemicolon();
  8892. }
  8893. parseAsyncArrowFromCallExpression(node, call) {
  8894. var _call$extra;
  8895. this.expect(types.arrow);
  8896. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8897. return node;
  8898. }
  8899. parseNoCallExpr() {
  8900. const startPos = this.state.start;
  8901. const startLoc = this.state.startLoc;
  8902. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8903. }
  8904. parseExprAtom(refExpressionErrors) {
  8905. if (this.state.type === types.slash) this.readRegexp();
  8906. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8907. let node;
  8908. switch (this.state.type) {
  8909. case types._super:
  8910. return this.parseSuper();
  8911. case types._import:
  8912. node = this.startNode();
  8913. this.next();
  8914. if (this.match(types.dot)) {
  8915. return this.parseImportMetaProperty(node);
  8916. }
  8917. if (!this.match(types.parenL)) {
  8918. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  8919. }
  8920. return this.finishNode(node, "Import");
  8921. case types._this:
  8922. node = this.startNode();
  8923. this.next();
  8924. return this.finishNode(node, "ThisExpression");
  8925. case types.name:
  8926. {
  8927. const containsEsc = this.state.containsEsc;
  8928. const id = this.parseIdentifier();
  8929. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  8930. if (this.match(types._function)) {
  8931. const last = this.state.context.length - 1;
  8932. if (this.state.context[last] !== types$1.functionStatement) {
  8933. throw new Error("Internal error");
  8934. }
  8935. this.state.context[last] = types$1.functionExpression;
  8936. this.next();
  8937. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  8938. } else if (this.match(types.name)) {
  8939. return this.parseAsyncArrowUnaryFunction(id);
  8940. }
  8941. }
  8942. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8943. this.next();
  8944. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  8945. }
  8946. return id;
  8947. }
  8948. case types._do:
  8949. {
  8950. return this.parseDo();
  8951. }
  8952. case types.regexp:
  8953. {
  8954. const value = this.state.value;
  8955. node = this.parseLiteral(value.value, "RegExpLiteral");
  8956. node.pattern = value.pattern;
  8957. node.flags = value.flags;
  8958. return node;
  8959. }
  8960. case types.num:
  8961. return this.parseLiteral(this.state.value, "NumericLiteral");
  8962. case types.bigint:
  8963. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8964. case types.decimal:
  8965. return this.parseLiteral(this.state.value, "DecimalLiteral");
  8966. case types.string:
  8967. return this.parseLiteral(this.state.value, "StringLiteral");
  8968. case types._null:
  8969. node = this.startNode();
  8970. this.next();
  8971. return this.finishNode(node, "NullLiteral");
  8972. case types._true:
  8973. case types._false:
  8974. return this.parseBooleanLiteral();
  8975. case types.parenL:
  8976. return this.parseParenAndDistinguishExpression(canBeArrow);
  8977. case types.bracketBarL:
  8978. case types.bracketHashL:
  8979. {
  8980. return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
  8981. }
  8982. case types.bracketL:
  8983. {
  8984. return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
  8985. }
  8986. case types.braceBarL:
  8987. case types.braceHashL:
  8988. {
  8989. return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
  8990. }
  8991. case types.braceL:
  8992. {
  8993. return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
  8994. }
  8995. case types._function:
  8996. return this.parseFunctionOrFunctionSent();
  8997. case types.at:
  8998. this.parseDecorators();
  8999. case types._class:
  9000. node = this.startNode();
  9001. this.takeDecorators(node);
  9002. return this.parseClass(node, false);
  9003. case types._new:
  9004. return this.parseNewOrNewTarget();
  9005. case types.backQuote:
  9006. return this.parseTemplate(false);
  9007. case types.doubleColon:
  9008. {
  9009. node = this.startNode();
  9010. this.next();
  9011. node.object = null;
  9012. const callee = node.callee = this.parseNoCallExpr();
  9013. if (callee.type === "MemberExpression") {
  9014. return this.finishNode(node, "BindExpression");
  9015. } else {
  9016. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  9017. }
  9018. }
  9019. case types.hash:
  9020. {
  9021. if (this.state.inPipeline) {
  9022. node = this.startNode();
  9023. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  9024. this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
  9025. }
  9026. this.next();
  9027. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  9028. this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
  9029. }
  9030. this.registerTopicReference();
  9031. return this.finishNode(node, "PipelinePrimaryTopicReference");
  9032. }
  9033. const nextCh = this.input.codePointAt(this.state.end);
  9034. if (isIdentifierStart(nextCh) || nextCh === 92) {
  9035. const start = this.state.start;
  9036. node = this.parseMaybePrivateName(true);
  9037. if (this.match(types._in)) {
  9038. this.expectPlugin("privateIn");
  9039. this.classScope.usePrivateName(this.getPrivateNameSV(node), node.start);
  9040. } else if (this.hasPlugin("privateIn")) {
  9041. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, this.getPrivateNameSV(node));
  9042. } else {
  9043. throw this.unexpected(start);
  9044. }
  9045. return node;
  9046. }
  9047. }
  9048. case types.relational:
  9049. {
  9050. if (this.state.value === "<") {
  9051. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  9052. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  9053. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  9054. }
  9055. }
  9056. }
  9057. default:
  9058. throw this.unexpected();
  9059. }
  9060. }
  9061. parseAsyncArrowUnaryFunction(id) {
  9062. const node = this.startNodeAtNode(id);
  9063. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  9064. const params = [this.parseIdentifier()];
  9065. this.prodParam.exit();
  9066. if (this.hasPrecedingLineBreak()) {
  9067. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  9068. }
  9069. this.expect(types.arrow);
  9070. this.parseArrowExpression(node, params, true);
  9071. return node;
  9072. }
  9073. parseDo() {
  9074. this.expectPlugin("doExpressions");
  9075. const node = this.startNode();
  9076. this.next();
  9077. const oldLabels = this.state.labels;
  9078. this.state.labels = [];
  9079. node.body = this.parseBlock();
  9080. this.state.labels = oldLabels;
  9081. return this.finishNode(node, "DoExpression");
  9082. }
  9083. parseSuper() {
  9084. const node = this.startNode();
  9085. this.next();
  9086. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  9087. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  9088. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  9089. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  9090. }
  9091. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  9092. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  9093. }
  9094. return this.finishNode(node, "Super");
  9095. }
  9096. parseBooleanLiteral() {
  9097. const node = this.startNode();
  9098. node.value = this.match(types._true);
  9099. this.next();
  9100. return this.finishNode(node, "BooleanLiteral");
  9101. }
  9102. parseMaybePrivateName(isPrivateNameAllowed) {
  9103. const isPrivate = this.match(types.hash);
  9104. if (isPrivate) {
  9105. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  9106. if (!isPrivateNameAllowed) {
  9107. this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
  9108. }
  9109. const node = this.startNode();
  9110. this.next();
  9111. this.assertNoSpace("Unexpected space between # and identifier");
  9112. node.id = this.parseIdentifier(true);
  9113. return this.finishNode(node, "PrivateName");
  9114. } else {
  9115. return this.parseIdentifier(true);
  9116. }
  9117. }
  9118. parseFunctionOrFunctionSent() {
  9119. const node = this.startNode();
  9120. this.next();
  9121. if (this.prodParam.hasYield && this.match(types.dot)) {
  9122. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  9123. this.next();
  9124. return this.parseMetaProperty(node, meta, "sent");
  9125. }
  9126. return this.parseFunction(node);
  9127. }
  9128. parseMetaProperty(node, meta, propertyName) {
  9129. node.meta = meta;
  9130. if (meta.name === "function" && propertyName === "sent") {
  9131. if (this.isContextual(propertyName)) {
  9132. this.expectPlugin("functionSent");
  9133. } else if (!this.hasPlugin("functionSent")) {
  9134. this.unexpected();
  9135. }
  9136. }
  9137. const containsEsc = this.state.containsEsc;
  9138. node.property = this.parseIdentifier(true);
  9139. if (node.property.name !== propertyName || containsEsc) {
  9140. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  9141. }
  9142. return this.finishNode(node, "MetaProperty");
  9143. }
  9144. parseImportMetaProperty(node) {
  9145. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  9146. this.next();
  9147. if (this.isContextual("meta")) {
  9148. if (!this.inModule) {
  9149. this.raiseWithData(id.start, {
  9150. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9151. }, ErrorMessages.ImportMetaOutsideModule);
  9152. }
  9153. this.sawUnambiguousESM = true;
  9154. }
  9155. return this.parseMetaProperty(node, id, "meta");
  9156. }
  9157. parseLiteral(value, type, startPos, startLoc) {
  9158. startPos = startPos || this.state.start;
  9159. startLoc = startLoc || this.state.startLoc;
  9160. const node = this.startNodeAt(startPos, startLoc);
  9161. this.addExtra(node, "rawValue", value);
  9162. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  9163. node.value = value;
  9164. this.next();
  9165. return this.finishNode(node, type);
  9166. }
  9167. parseParenAndDistinguishExpression(canBeArrow) {
  9168. const startPos = this.state.start;
  9169. const startLoc = this.state.startLoc;
  9170. let val;
  9171. this.next();
  9172. this.expressionScope.enter(newArrowHeadScope());
  9173. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9174. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9175. this.state.maybeInArrowParameters = true;
  9176. this.state.inFSharpPipelineDirectBody = false;
  9177. const innerStartPos = this.state.start;
  9178. const innerStartLoc = this.state.startLoc;
  9179. const exprList = [];
  9180. const refExpressionErrors = new ExpressionErrors();
  9181. const refNeedsArrowPos = {
  9182. start: 0
  9183. };
  9184. let first = true;
  9185. let spreadStart;
  9186. let optionalCommaStart;
  9187. while (!this.match(types.parenR)) {
  9188. if (first) {
  9189. first = false;
  9190. } else {
  9191. this.expect(types.comma, refNeedsArrowPos.start || null);
  9192. if (this.match(types.parenR)) {
  9193. optionalCommaStart = this.state.start;
  9194. break;
  9195. }
  9196. }
  9197. if (this.match(types.ellipsis)) {
  9198. const spreadNodeStartPos = this.state.start;
  9199. const spreadNodeStartLoc = this.state.startLoc;
  9200. spreadStart = this.state.start;
  9201. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  9202. this.checkCommaAfterRest(41);
  9203. break;
  9204. } else {
  9205. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  9206. }
  9207. }
  9208. const innerEndPos = this.state.lastTokEnd;
  9209. const innerEndLoc = this.state.lastTokEndLoc;
  9210. this.expect(types.parenR);
  9211. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9212. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9213. let arrowNode = this.startNodeAt(startPos, startLoc);
  9214. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  9215. this.expressionScope.validateAsPattern();
  9216. this.expressionScope.exit();
  9217. this.parseArrowExpression(arrowNode, exprList, false);
  9218. return arrowNode;
  9219. }
  9220. this.expressionScope.exit();
  9221. if (!exprList.length) {
  9222. this.unexpected(this.state.lastTokStart);
  9223. }
  9224. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  9225. if (spreadStart) this.unexpected(spreadStart);
  9226. this.checkExpressionErrors(refExpressionErrors, true);
  9227. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  9228. this.toReferencedListDeep(exprList, true);
  9229. if (exprList.length > 1) {
  9230. val = this.startNodeAt(innerStartPos, innerStartLoc);
  9231. val.expressions = exprList;
  9232. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  9233. } else {
  9234. val = exprList[0];
  9235. }
  9236. if (!this.options.createParenthesizedExpressions) {
  9237. this.addExtra(val, "parenthesized", true);
  9238. this.addExtra(val, "parenStart", startPos);
  9239. return val;
  9240. }
  9241. const parenExpression = this.startNodeAt(startPos, startLoc);
  9242. parenExpression.expression = val;
  9243. this.finishNode(parenExpression, "ParenthesizedExpression");
  9244. return parenExpression;
  9245. }
  9246. shouldParseArrow() {
  9247. return !this.canInsertSemicolon();
  9248. }
  9249. parseArrow(node) {
  9250. if (this.eat(types.arrow)) {
  9251. return node;
  9252. }
  9253. }
  9254. parseParenItem(node, startPos, startLoc) {
  9255. return node;
  9256. }
  9257. parseNewOrNewTarget() {
  9258. const node = this.startNode();
  9259. this.next();
  9260. if (this.match(types.dot)) {
  9261. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  9262. this.next();
  9263. const metaProp = this.parseMetaProperty(node, meta, "target");
  9264. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  9265. let error = ErrorMessages.UnexpectedNewTarget;
  9266. if (this.hasPlugin("classProperties")) {
  9267. error += " or class properties";
  9268. }
  9269. this.raise(metaProp.start, error);
  9270. }
  9271. return metaProp;
  9272. }
  9273. return this.parseNew(node);
  9274. }
  9275. parseNew(node) {
  9276. node.callee = this.parseNoCallExpr();
  9277. if (node.callee.type === "Import") {
  9278. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  9279. } else if (this.isOptionalChain(node.callee)) {
  9280. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  9281. } else if (this.eat(types.questionDot)) {
  9282. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  9283. }
  9284. this.parseNewArguments(node);
  9285. return this.finishNode(node, "NewExpression");
  9286. }
  9287. parseNewArguments(node) {
  9288. if (this.eat(types.parenL)) {
  9289. const args = this.parseExprList(types.parenR);
  9290. this.toReferencedList(args);
  9291. node.arguments = args;
  9292. } else {
  9293. node.arguments = [];
  9294. }
  9295. }
  9296. parseTemplateElement(isTagged) {
  9297. const elem = this.startNode();
  9298. if (this.state.value === null) {
  9299. if (!isTagged) {
  9300. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  9301. }
  9302. }
  9303. elem.value = {
  9304. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  9305. cooked: this.state.value
  9306. };
  9307. this.next();
  9308. elem.tail = this.match(types.backQuote);
  9309. return this.finishNode(elem, "TemplateElement");
  9310. }
  9311. parseTemplate(isTagged) {
  9312. const node = this.startNode();
  9313. this.next();
  9314. node.expressions = [];
  9315. let curElt = this.parseTemplateElement(isTagged);
  9316. node.quasis = [curElt];
  9317. while (!curElt.tail) {
  9318. this.expect(types.dollarBraceL);
  9319. node.expressions.push(this.parseTemplateSubstitution());
  9320. this.expect(types.braceR);
  9321. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  9322. }
  9323. this.next();
  9324. return this.finishNode(node, "TemplateLiteral");
  9325. }
  9326. parseTemplateSubstitution() {
  9327. return this.parseExpression();
  9328. }
  9329. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  9330. if (isRecord) {
  9331. this.expectPlugin("recordAndTuple");
  9332. }
  9333. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9334. this.state.inFSharpPipelineDirectBody = false;
  9335. const propHash = Object.create(null);
  9336. let first = true;
  9337. const node = this.startNode();
  9338. node.properties = [];
  9339. this.next();
  9340. while (!this.match(close)) {
  9341. if (first) {
  9342. first = false;
  9343. } else {
  9344. this.expect(types.comma);
  9345. if (this.match(close)) {
  9346. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  9347. break;
  9348. }
  9349. }
  9350. const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
  9351. if (!isPattern) {
  9352. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  9353. }
  9354. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  9355. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  9356. }
  9357. if (prop.shorthand) {
  9358. this.addExtra(prop, "shorthand", true);
  9359. }
  9360. node.properties.push(prop);
  9361. }
  9362. this.state.exprAllowed = false;
  9363. this.next();
  9364. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9365. let type = "ObjectExpression";
  9366. if (isPattern) {
  9367. type = "ObjectPattern";
  9368. } else if (isRecord) {
  9369. type = "RecordExpression";
  9370. }
  9371. return this.finishNode(node, type);
  9372. }
  9373. maybeAsyncOrAccessorProp(prop) {
  9374. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
  9375. }
  9376. parsePropertyDefinition(isPattern, refExpressionErrors) {
  9377. let decorators = [];
  9378. if (this.match(types.at)) {
  9379. if (this.hasPlugin("decorators")) {
  9380. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  9381. }
  9382. while (this.match(types.at)) {
  9383. decorators.push(this.parseDecorator());
  9384. }
  9385. }
  9386. const prop = this.startNode();
  9387. let isGenerator = false;
  9388. let isAsync = false;
  9389. let isAccessor = false;
  9390. let startPos;
  9391. let startLoc;
  9392. if (this.match(types.ellipsis)) {
  9393. if (decorators.length) this.unexpected();
  9394. if (isPattern) {
  9395. this.next();
  9396. prop.argument = this.parseIdentifier();
  9397. this.checkCommaAfterRest(125);
  9398. return this.finishNode(prop, "RestElement");
  9399. }
  9400. return this.parseSpread();
  9401. }
  9402. if (decorators.length) {
  9403. prop.decorators = decorators;
  9404. decorators = [];
  9405. }
  9406. prop.method = false;
  9407. if (isPattern || refExpressionErrors) {
  9408. startPos = this.state.start;
  9409. startLoc = this.state.startLoc;
  9410. }
  9411. if (!isPattern) {
  9412. isGenerator = this.eat(types.star);
  9413. }
  9414. const containsEsc = this.state.containsEsc;
  9415. const key = this.parsePropertyName(prop, false);
  9416. if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  9417. const keyName = key.name;
  9418. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  9419. isAsync = true;
  9420. isGenerator = this.eat(types.star);
  9421. this.parsePropertyName(prop, false);
  9422. }
  9423. if (keyName === "get" || keyName === "set") {
  9424. isAccessor = true;
  9425. prop.kind = keyName;
  9426. if (this.match(types.star)) {
  9427. isGenerator = true;
  9428. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  9429. this.next();
  9430. }
  9431. this.parsePropertyName(prop, false);
  9432. }
  9433. }
  9434. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  9435. return prop;
  9436. }
  9437. getGetterSetterExpectedParamCount(method) {
  9438. return method.kind === "get" ? 0 : 1;
  9439. }
  9440. getObjectOrClassMethodParams(method) {
  9441. return method.params;
  9442. }
  9443. checkGetterSetterParams(method) {
  9444. var _params;
  9445. const paramCount = this.getGetterSetterExpectedParamCount(method);
  9446. const params = this.getObjectOrClassMethodParams(method);
  9447. const start = method.start;
  9448. if (params.length !== paramCount) {
  9449. if (method.kind === "get") {
  9450. this.raise(start, ErrorMessages.BadGetterArity);
  9451. } else {
  9452. this.raise(start, ErrorMessages.BadSetterArity);
  9453. }
  9454. }
  9455. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  9456. this.raise(start, ErrorMessages.BadSetterRestParameter);
  9457. }
  9458. }
  9459. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  9460. if (isAccessor) {
  9461. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  9462. this.checkGetterSetterParams(prop);
  9463. return prop;
  9464. }
  9465. if (isAsync || isGenerator || this.match(types.parenL)) {
  9466. if (isPattern) this.unexpected();
  9467. prop.kind = "method";
  9468. prop.method = true;
  9469. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  9470. }
  9471. }
  9472. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  9473. prop.shorthand = false;
  9474. if (this.eat(types.colon)) {
  9475. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  9476. return this.finishNode(prop, "ObjectProperty");
  9477. }
  9478. if (!prop.computed && prop.key.type === "Identifier") {
  9479. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  9480. if (isPattern) {
  9481. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9482. } else if (this.match(types.eq) && refExpressionErrors) {
  9483. if (refExpressionErrors.shorthandAssign === -1) {
  9484. refExpressionErrors.shorthandAssign = this.state.start;
  9485. }
  9486. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9487. } else {
  9488. prop.value = prop.key.__clone();
  9489. }
  9490. prop.shorthand = true;
  9491. return this.finishNode(prop, "ObjectProperty");
  9492. }
  9493. }
  9494. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9495. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  9496. if (!node) this.unexpected();
  9497. return node;
  9498. }
  9499. parsePropertyName(prop, isPrivateNameAllowed) {
  9500. if (this.eat(types.bracketL)) {
  9501. prop.computed = true;
  9502. prop.key = this.parseMaybeAssignAllowIn();
  9503. this.expect(types.bracketR);
  9504. } else {
  9505. const oldInPropertyName = this.state.inPropertyName;
  9506. this.state.inPropertyName = true;
  9507. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  9508. if (!this.isPrivateName(prop.key)) {
  9509. prop.computed = false;
  9510. }
  9511. this.state.inPropertyName = oldInPropertyName;
  9512. }
  9513. return prop.key;
  9514. }
  9515. initFunction(node, isAsync) {
  9516. node.id = null;
  9517. node.generator = false;
  9518. node.async = !!isAsync;
  9519. }
  9520. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  9521. this.initFunction(node, isAsync);
  9522. node.generator = !!isGenerator;
  9523. const allowModifiers = isConstructor;
  9524. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  9525. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9526. this.parseFunctionParams(node, allowModifiers);
  9527. this.parseFunctionBodyAndFinish(node, type, true);
  9528. this.prodParam.exit();
  9529. this.scope.exit();
  9530. return node;
  9531. }
  9532. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  9533. if (isTuple) {
  9534. this.expectPlugin("recordAndTuple");
  9535. }
  9536. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9537. this.state.inFSharpPipelineDirectBody = false;
  9538. const node = this.startNode();
  9539. this.next();
  9540. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  9541. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9542. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  9543. }
  9544. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  9545. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  9546. let flags = functionFlags(isAsync, false);
  9547. if (!this.match(types.bracketL) && this.prodParam.hasIn) {
  9548. flags |= PARAM_IN;
  9549. }
  9550. this.prodParam.enter(flags);
  9551. this.initFunction(node, isAsync);
  9552. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9553. if (params) {
  9554. this.state.maybeInArrowParameters = true;
  9555. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  9556. }
  9557. this.state.maybeInArrowParameters = false;
  9558. this.parseFunctionBody(node, true);
  9559. this.prodParam.exit();
  9560. this.scope.exit();
  9561. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9562. return this.finishNode(node, "ArrowFunctionExpression");
  9563. }
  9564. setArrowFunctionParameters(node, params, trailingCommaPos) {
  9565. node.params = this.toAssignableList(params, trailingCommaPos, false);
  9566. }
  9567. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  9568. this.parseFunctionBody(node, false, isMethod);
  9569. this.finishNode(node, type);
  9570. }
  9571. parseFunctionBody(node, allowExpression, isMethod = false) {
  9572. const isExpression = allowExpression && !this.match(types.braceL);
  9573. this.expressionScope.enter(newExpressionScope());
  9574. if (isExpression) {
  9575. node.body = this.parseMaybeAssign();
  9576. this.checkParams(node, false, allowExpression, false);
  9577. } else {
  9578. const oldStrict = this.state.strict;
  9579. const oldLabels = this.state.labels;
  9580. this.state.labels = [];
  9581. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  9582. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  9583. const nonSimple = !this.isSimpleParamList(node.params);
  9584. if (hasStrictModeDirective && nonSimple) {
  9585. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  9586. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  9587. }
  9588. const strictModeChanged = !oldStrict && this.state.strict;
  9589. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  9590. if (this.state.strict && node.id) {
  9591. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  9592. }
  9593. });
  9594. this.prodParam.exit();
  9595. this.expressionScope.exit();
  9596. this.state.labels = oldLabels;
  9597. }
  9598. }
  9599. isSimpleParamList(params) {
  9600. for (let i = 0, len = params.length; i < len; i++) {
  9601. if (params[i].type !== "Identifier") return false;
  9602. }
  9603. return true;
  9604. }
  9605. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  9606. const checkClashes = new Set();
  9607. for (const param of node.params) {
  9608. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  9609. }
  9610. }
  9611. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  9612. const elts = [];
  9613. let first = true;
  9614. while (!this.eat(close)) {
  9615. if (first) {
  9616. first = false;
  9617. } else {
  9618. this.expect(types.comma);
  9619. if (this.match(close)) {
  9620. if (nodeForExtra) {
  9621. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  9622. }
  9623. this.next();
  9624. break;
  9625. }
  9626. }
  9627. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  9628. }
  9629. return elts;
  9630. }
  9631. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  9632. let elt;
  9633. if (this.match(types.comma)) {
  9634. if (!allowEmpty) {
  9635. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  9636. }
  9637. elt = null;
  9638. } else if (this.match(types.ellipsis)) {
  9639. const spreadNodeStartPos = this.state.start;
  9640. const spreadNodeStartLoc = this.state.startLoc;
  9641. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  9642. } else if (this.match(types.question)) {
  9643. this.expectPlugin("partialApplication");
  9644. if (!allowPlaceholder) {
  9645. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  9646. }
  9647. const node = this.startNode();
  9648. this.next();
  9649. elt = this.finishNode(node, "ArgumentPlaceholder");
  9650. } else {
  9651. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  9652. }
  9653. return elt;
  9654. }
  9655. parseIdentifier(liberal) {
  9656. const node = this.startNode();
  9657. const name = this.parseIdentifierName(node.start, liberal);
  9658. return this.createIdentifier(node, name);
  9659. }
  9660. createIdentifier(node, name) {
  9661. node.name = name;
  9662. node.loc.identifierName = name;
  9663. return this.finishNode(node, "Identifier");
  9664. }
  9665. parseIdentifierName(pos, liberal) {
  9666. let name;
  9667. const {
  9668. start,
  9669. type
  9670. } = this.state;
  9671. if (type === types.name) {
  9672. name = this.state.value;
  9673. } else if (type.keyword) {
  9674. name = type.keyword;
  9675. const curContext = this.curContext();
  9676. if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
  9677. this.state.context.pop();
  9678. }
  9679. } else {
  9680. throw this.unexpected();
  9681. }
  9682. if (liberal) {
  9683. this.state.type = types.name;
  9684. } else {
  9685. this.checkReservedWord(name, start, !!type.keyword, false);
  9686. }
  9687. this.next();
  9688. return name;
  9689. }
  9690. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9691. if (this.prodParam.hasYield && word === "yield") {
  9692. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  9693. return;
  9694. }
  9695. if (word === "await") {
  9696. if (this.prodParam.hasAwait) {
  9697. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9698. return;
  9699. } else if (this.scope.inStaticBlock && !this.scope.inNonArrowFunction) {
  9700. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock);
  9701. return;
  9702. } else {
  9703. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9704. }
  9705. }
  9706. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  9707. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  9708. return;
  9709. }
  9710. if (checkKeywords && isKeyword(word)) {
  9711. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  9712. return;
  9713. }
  9714. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  9715. if (reservedTest(word, this.inModule)) {
  9716. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  9717. }
  9718. }
  9719. isAwaitAllowed() {
  9720. if (this.prodParam.hasAwait) return true;
  9721. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  9722. return true;
  9723. }
  9724. return false;
  9725. }
  9726. parseAwait(startPos, startLoc) {
  9727. const node = this.startNodeAt(startPos, startLoc);
  9728. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  9729. if (this.eat(types.star)) {
  9730. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  9731. }
  9732. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  9733. if (this.isAmbiguousAwait()) {
  9734. this.ambiguousScriptDifferentAst = true;
  9735. } else {
  9736. this.sawUnambiguousESM = true;
  9737. }
  9738. }
  9739. if (!this.state.soloAwait) {
  9740. node.argument = this.parseMaybeUnary();
  9741. }
  9742. return this.finishNode(node, "AwaitExpression");
  9743. }
  9744. isAmbiguousAwait() {
  9745. return this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo);
  9746. }
  9747. parseYield() {
  9748. const node = this.startNode();
  9749. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  9750. this.next();
  9751. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  9752. node.delegate = false;
  9753. node.argument = null;
  9754. } else {
  9755. node.delegate = this.eat(types.star);
  9756. node.argument = this.parseMaybeAssign();
  9757. }
  9758. return this.finishNode(node, "YieldExpression");
  9759. }
  9760. checkPipelineAtInfixOperator(left, leftStartPos) {
  9761. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  9762. if (left.type === "SequenceExpression") {
  9763. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  9764. }
  9765. }
  9766. }
  9767. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  9768. this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
  9769. return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
  9770. }
  9771. checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
  9772. if (this.match(types.arrow)) {
  9773. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  9774. } else if (childExpression.type === "SequenceExpression") {
  9775. this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
  9776. }
  9777. }
  9778. parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
  9779. const bodyNode = this.startNodeAt(startPos, startLoc);
  9780. const isSimpleReference = this.isSimpleReference(childExpression);
  9781. if (isSimpleReference) {
  9782. bodyNode.callee = childExpression;
  9783. } else {
  9784. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  9785. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  9786. }
  9787. bodyNode.expression = childExpression;
  9788. }
  9789. return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
  9790. }
  9791. isSimpleReference(expression) {
  9792. switch (expression.type) {
  9793. case "MemberExpression":
  9794. return !expression.computed && this.isSimpleReference(expression.object);
  9795. case "Identifier":
  9796. return true;
  9797. default:
  9798. return false;
  9799. }
  9800. }
  9801. withTopicPermittingContext(callback) {
  9802. const outerContextTopicState = this.state.topicContext;
  9803. this.state.topicContext = {
  9804. maxNumOfResolvableTopics: 1,
  9805. maxTopicIndex: null
  9806. };
  9807. try {
  9808. return callback();
  9809. } finally {
  9810. this.state.topicContext = outerContextTopicState;
  9811. }
  9812. }
  9813. withTopicForbiddingContext(callback) {
  9814. const outerContextTopicState = this.state.topicContext;
  9815. this.state.topicContext = {
  9816. maxNumOfResolvableTopics: 0,
  9817. maxTopicIndex: null
  9818. };
  9819. try {
  9820. return callback();
  9821. } finally {
  9822. this.state.topicContext = outerContextTopicState;
  9823. }
  9824. }
  9825. withSoloAwaitPermittingContext(callback) {
  9826. const outerContextSoloAwaitState = this.state.soloAwait;
  9827. this.state.soloAwait = true;
  9828. try {
  9829. return callback();
  9830. } finally {
  9831. this.state.soloAwait = outerContextSoloAwaitState;
  9832. }
  9833. }
  9834. allowInAnd(callback) {
  9835. const flags = this.prodParam.currentFlags();
  9836. const prodParamToSet = PARAM_IN & ~flags;
  9837. if (prodParamToSet) {
  9838. this.prodParam.enter(flags | PARAM_IN);
  9839. try {
  9840. return callback();
  9841. } finally {
  9842. this.prodParam.exit();
  9843. }
  9844. }
  9845. return callback();
  9846. }
  9847. disallowInAnd(callback) {
  9848. const flags = this.prodParam.currentFlags();
  9849. const prodParamToClear = PARAM_IN & flags;
  9850. if (prodParamToClear) {
  9851. this.prodParam.enter(flags & ~PARAM_IN);
  9852. try {
  9853. return callback();
  9854. } finally {
  9855. this.prodParam.exit();
  9856. }
  9857. }
  9858. return callback();
  9859. }
  9860. registerTopicReference() {
  9861. this.state.topicContext.maxTopicIndex = 0;
  9862. }
  9863. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  9864. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  9865. }
  9866. topicReferenceWasUsedInCurrentTopicContext() {
  9867. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  9868. }
  9869. parseFSharpPipelineBody(prec) {
  9870. const startPos = this.state.start;
  9871. const startLoc = this.state.startLoc;
  9872. this.state.potentialArrowAt = this.state.start;
  9873. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9874. this.state.inFSharpPipelineDirectBody = true;
  9875. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
  9876. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9877. return ret;
  9878. }
  9879. parseModuleExpression() {
  9880. this.expectPlugin("moduleBlocks");
  9881. const node = this.startNode();
  9882. this.next();
  9883. this.eat(types.braceL);
  9884. const revertScopes = this.initializeScopes(true);
  9885. this.enterInitialScopes();
  9886. const program = this.startNode();
  9887. try {
  9888. node.body = this.parseProgram(program, types.braceR, "module");
  9889. } finally {
  9890. revertScopes();
  9891. }
  9892. this.eat(types.braceR);
  9893. return this.finishNode(node, "ModuleExpression");
  9894. }
  9895. }
  9896. const loopLabel = {
  9897. kind: "loop"
  9898. },
  9899. switchLabel = {
  9900. kind: "switch"
  9901. };
  9902. const FUNC_NO_FLAGS = 0b000,
  9903. FUNC_STATEMENT = 0b001,
  9904. FUNC_HANGING_STATEMENT = 0b010,
  9905. FUNC_NULLABLE_ID = 0b100;
  9906. const loneSurrogate = /[\uD800-\uDFFF]/u;
  9907. class StatementParser extends ExpressionParser {
  9908. parseTopLevel(file, program) {
  9909. file.program = this.parseProgram(program);
  9910. file.comments = this.state.comments;
  9911. if (this.options.tokens) file.tokens = this.tokens;
  9912. return this.finishNode(file, "File");
  9913. }
  9914. parseProgram(program, end = types.eof, sourceType = this.options.sourceType) {
  9915. program.sourceType = sourceType;
  9916. program.interpreter = this.parseInterpreterDirective();
  9917. this.parseBlockBody(program, true, true, end);
  9918. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9919. for (const [name] of Array.from(this.scope.undefinedExports)) {
  9920. const pos = this.scope.undefinedExports.get(name);
  9921. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  9922. }
  9923. }
  9924. return this.finishNode(program, "Program");
  9925. }
  9926. stmtToDirective(stmt) {
  9927. const expr = stmt.expression;
  9928. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9929. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9930. const raw = this.input.slice(expr.start, expr.end);
  9931. const val = directiveLiteral.value = raw.slice(1, -1);
  9932. this.addExtra(directiveLiteral, "raw", raw);
  9933. this.addExtra(directiveLiteral, "rawValue", val);
  9934. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9935. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9936. }
  9937. parseInterpreterDirective() {
  9938. if (!this.match(types.interpreterDirective)) {
  9939. return null;
  9940. }
  9941. const node = this.startNode();
  9942. node.value = this.state.value;
  9943. this.next();
  9944. return this.finishNode(node, "InterpreterDirective");
  9945. }
  9946. isLet(context) {
  9947. if (!this.isContextual("let")) {
  9948. return false;
  9949. }
  9950. const next = this.nextTokenStart();
  9951. const nextCh = this.input.charCodeAt(next);
  9952. if (nextCh === 91) return true;
  9953. if (context) return false;
  9954. if (nextCh === 123) return true;
  9955. if (isIdentifierStart(nextCh)) {
  9956. let pos = next + 1;
  9957. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9958. ++pos;
  9959. }
  9960. const ident = this.input.slice(next, pos);
  9961. if (!keywordRelationalOperator.test(ident)) return true;
  9962. }
  9963. return false;
  9964. }
  9965. parseStatement(context, topLevel) {
  9966. if (this.match(types.at)) {
  9967. this.parseDecorators(true);
  9968. }
  9969. return this.parseStatementContent(context, topLevel);
  9970. }
  9971. parseStatementContent(context, topLevel) {
  9972. let starttype = this.state.type;
  9973. const node = this.startNode();
  9974. let kind;
  9975. if (this.isLet(context)) {
  9976. starttype = types._var;
  9977. kind = "let";
  9978. }
  9979. switch (starttype) {
  9980. case types._break:
  9981. case types._continue:
  9982. return this.parseBreakContinueStatement(node, starttype.keyword);
  9983. case types._debugger:
  9984. return this.parseDebuggerStatement(node);
  9985. case types._do:
  9986. return this.parseDoStatement(node);
  9987. case types._for:
  9988. return this.parseForStatement(node);
  9989. case types._function:
  9990. if (this.lookaheadCharCode() === 46) break;
  9991. if (context) {
  9992. if (this.state.strict) {
  9993. this.raise(this.state.start, ErrorMessages.StrictFunction);
  9994. } else if (context !== "if" && context !== "label") {
  9995. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  9996. }
  9997. }
  9998. return this.parseFunctionStatement(node, false, !context);
  9999. case types._class:
  10000. if (context) this.unexpected();
  10001. return this.parseClass(node, true);
  10002. case types._if:
  10003. return this.parseIfStatement(node);
  10004. case types._return:
  10005. return this.parseReturnStatement(node);
  10006. case types._switch:
  10007. return this.parseSwitchStatement(node);
  10008. case types._throw:
  10009. return this.parseThrowStatement(node);
  10010. case types._try:
  10011. return this.parseTryStatement(node);
  10012. case types._const:
  10013. case types._var:
  10014. kind = kind || this.state.value;
  10015. if (context && kind !== "var") {
  10016. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  10017. }
  10018. return this.parseVarStatement(node, kind);
  10019. case types._while:
  10020. return this.parseWhileStatement(node);
  10021. case types._with:
  10022. return this.parseWithStatement(node);
  10023. case types.braceL:
  10024. return this.parseBlock();
  10025. case types.semi:
  10026. return this.parseEmptyStatement(node);
  10027. case types._import:
  10028. {
  10029. const nextTokenCharCode = this.lookaheadCharCode();
  10030. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  10031. break;
  10032. }
  10033. }
  10034. case types._export:
  10035. {
  10036. if (!this.options.allowImportExportEverywhere && !topLevel) {
  10037. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  10038. }
  10039. this.next();
  10040. let result;
  10041. if (starttype === types._import) {
  10042. result = this.parseImport(node);
  10043. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  10044. this.sawUnambiguousESM = true;
  10045. }
  10046. } else {
  10047. result = this.parseExport(node);
  10048. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  10049. this.sawUnambiguousESM = true;
  10050. }
  10051. }
  10052. this.assertModuleNodeAllowed(node);
  10053. return result;
  10054. }
  10055. default:
  10056. {
  10057. if (this.isAsyncFunction()) {
  10058. if (context) {
  10059. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  10060. }
  10061. this.next();
  10062. return this.parseFunctionStatement(node, true, !context);
  10063. }
  10064. }
  10065. }
  10066. const maybeName = this.state.value;
  10067. const expr = this.parseExpression();
  10068. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  10069. return this.parseLabeledStatement(node, maybeName, expr, context);
  10070. } else {
  10071. return this.parseExpressionStatement(node, expr);
  10072. }
  10073. }
  10074. assertModuleNodeAllowed(node) {
  10075. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  10076. this.raiseWithData(node.start, {
  10077. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  10078. }, ErrorMessages.ImportOutsideModule);
  10079. }
  10080. }
  10081. takeDecorators(node) {
  10082. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10083. if (decorators.length) {
  10084. node.decorators = decorators;
  10085. this.resetStartLocationFromNode(node, decorators[0]);
  10086. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  10087. }
  10088. }
  10089. canHaveLeadingDecorator() {
  10090. return this.match(types._class);
  10091. }
  10092. parseDecorators(allowExport) {
  10093. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10094. while (this.match(types.at)) {
  10095. const decorator = this.parseDecorator();
  10096. currentContextDecorators.push(decorator);
  10097. }
  10098. if (this.match(types._export)) {
  10099. if (!allowExport) {
  10100. this.unexpected();
  10101. }
  10102. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10103. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  10104. }
  10105. } else if (!this.canHaveLeadingDecorator()) {
  10106. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  10107. }
  10108. }
  10109. parseDecorator() {
  10110. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  10111. const node = this.startNode();
  10112. this.next();
  10113. if (this.hasPlugin("decorators")) {
  10114. this.state.decoratorStack.push([]);
  10115. const startPos = this.state.start;
  10116. const startLoc = this.state.startLoc;
  10117. let expr;
  10118. if (this.eat(types.parenL)) {
  10119. expr = this.parseExpression();
  10120. this.expect(types.parenR);
  10121. } else {
  10122. expr = this.parseIdentifier(false);
  10123. while (this.eat(types.dot)) {
  10124. const node = this.startNodeAt(startPos, startLoc);
  10125. node.object = expr;
  10126. node.property = this.parseIdentifier(true);
  10127. node.computed = false;
  10128. expr = this.finishNode(node, "MemberExpression");
  10129. }
  10130. }
  10131. node.expression = this.parseMaybeDecoratorArguments(expr);
  10132. this.state.decoratorStack.pop();
  10133. } else {
  10134. node.expression = this.parseExprSubscripts();
  10135. }
  10136. return this.finishNode(node, "Decorator");
  10137. }
  10138. parseMaybeDecoratorArguments(expr) {
  10139. if (this.eat(types.parenL)) {
  10140. const node = this.startNodeAtNode(expr);
  10141. node.callee = expr;
  10142. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  10143. this.toReferencedList(node.arguments);
  10144. return this.finishNode(node, "CallExpression");
  10145. }
  10146. return expr;
  10147. }
  10148. parseBreakContinueStatement(node, keyword) {
  10149. const isBreak = keyword === "break";
  10150. this.next();
  10151. if (this.isLineTerminator()) {
  10152. node.label = null;
  10153. } else {
  10154. node.label = this.parseIdentifier();
  10155. this.semicolon();
  10156. }
  10157. this.verifyBreakContinue(node, keyword);
  10158. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  10159. }
  10160. verifyBreakContinue(node, keyword) {
  10161. const isBreak = keyword === "break";
  10162. let i;
  10163. for (i = 0; i < this.state.labels.length; ++i) {
  10164. const lab = this.state.labels[i];
  10165. if (node.label == null || lab.name === node.label.name) {
  10166. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  10167. if (node.label && isBreak) break;
  10168. }
  10169. }
  10170. if (i === this.state.labels.length) {
  10171. this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
  10172. }
  10173. }
  10174. parseDebuggerStatement(node) {
  10175. this.next();
  10176. this.semicolon();
  10177. return this.finishNode(node, "DebuggerStatement");
  10178. }
  10179. parseHeaderExpression() {
  10180. this.expect(types.parenL);
  10181. const val = this.parseExpression();
  10182. this.expect(types.parenR);
  10183. return val;
  10184. }
  10185. parseDoStatement(node) {
  10186. this.next();
  10187. this.state.labels.push(loopLabel);
  10188. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  10189. this.state.labels.pop();
  10190. this.expect(types._while);
  10191. node.test = this.parseHeaderExpression();
  10192. this.eat(types.semi);
  10193. return this.finishNode(node, "DoWhileStatement");
  10194. }
  10195. parseForStatement(node) {
  10196. this.next();
  10197. this.state.labels.push(loopLabel);
  10198. let awaitAt = -1;
  10199. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  10200. awaitAt = this.state.lastTokStart;
  10201. }
  10202. this.scope.enter(SCOPE_OTHER);
  10203. this.expect(types.parenL);
  10204. if (this.match(types.semi)) {
  10205. if (awaitAt > -1) {
  10206. this.unexpected(awaitAt);
  10207. }
  10208. return this.parseFor(node, null);
  10209. }
  10210. const isLet = this.isLet();
  10211. if (this.match(types._var) || this.match(types._const) || isLet) {
  10212. const init = this.startNode();
  10213. const kind = isLet ? "let" : this.state.value;
  10214. this.next();
  10215. this.parseVar(init, true, kind);
  10216. this.finishNode(init, "VariableDeclaration");
  10217. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  10218. return this.parseForIn(node, init, awaitAt);
  10219. }
  10220. if (awaitAt > -1) {
  10221. this.unexpected(awaitAt);
  10222. }
  10223. return this.parseFor(node, init);
  10224. }
  10225. const refExpressionErrors = new ExpressionErrors();
  10226. const init = this.parseExpression(true, refExpressionErrors);
  10227. if (this.match(types._in) || this.isContextual("of")) {
  10228. this.toAssignable(init, true);
  10229. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  10230. this.checkLVal(init, description);
  10231. return this.parseForIn(node, init, awaitAt);
  10232. } else {
  10233. this.checkExpressionErrors(refExpressionErrors, true);
  10234. }
  10235. if (awaitAt > -1) {
  10236. this.unexpected(awaitAt);
  10237. }
  10238. return this.parseFor(node, init);
  10239. }
  10240. parseFunctionStatement(node, isAsync, declarationPosition) {
  10241. this.next();
  10242. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  10243. }
  10244. parseIfStatement(node) {
  10245. this.next();
  10246. node.test = this.parseHeaderExpression();
  10247. node.consequent = this.parseStatement("if");
  10248. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  10249. return this.finishNode(node, "IfStatement");
  10250. }
  10251. parseReturnStatement(node) {
  10252. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  10253. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  10254. }
  10255. this.next();
  10256. if (this.isLineTerminator()) {
  10257. node.argument = null;
  10258. } else {
  10259. node.argument = this.parseExpression();
  10260. this.semicolon();
  10261. }
  10262. return this.finishNode(node, "ReturnStatement");
  10263. }
  10264. parseSwitchStatement(node) {
  10265. this.next();
  10266. node.discriminant = this.parseHeaderExpression();
  10267. const cases = node.cases = [];
  10268. this.expect(types.braceL);
  10269. this.state.labels.push(switchLabel);
  10270. this.scope.enter(SCOPE_OTHER);
  10271. let cur;
  10272. for (let sawDefault; !this.match(types.braceR);) {
  10273. if (this.match(types._case) || this.match(types._default)) {
  10274. const isCase = this.match(types._case);
  10275. if (cur) this.finishNode(cur, "SwitchCase");
  10276. cases.push(cur = this.startNode());
  10277. cur.consequent = [];
  10278. this.next();
  10279. if (isCase) {
  10280. cur.test = this.parseExpression();
  10281. } else {
  10282. if (sawDefault) {
  10283. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  10284. }
  10285. sawDefault = true;
  10286. cur.test = null;
  10287. }
  10288. this.expect(types.colon);
  10289. } else {
  10290. if (cur) {
  10291. cur.consequent.push(this.parseStatement(null));
  10292. } else {
  10293. this.unexpected();
  10294. }
  10295. }
  10296. }
  10297. this.scope.exit();
  10298. if (cur) this.finishNode(cur, "SwitchCase");
  10299. this.next();
  10300. this.state.labels.pop();
  10301. return this.finishNode(node, "SwitchStatement");
  10302. }
  10303. parseThrowStatement(node) {
  10304. this.next();
  10305. if (this.hasPrecedingLineBreak()) {
  10306. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  10307. }
  10308. node.argument = this.parseExpression();
  10309. this.semicolon();
  10310. return this.finishNode(node, "ThrowStatement");
  10311. }
  10312. parseCatchClauseParam() {
  10313. const param = this.parseBindingAtom();
  10314. const simple = param.type === "Identifier";
  10315. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  10316. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  10317. return param;
  10318. }
  10319. parseTryStatement(node) {
  10320. this.next();
  10321. node.block = this.parseBlock();
  10322. node.handler = null;
  10323. if (this.match(types._catch)) {
  10324. const clause = this.startNode();
  10325. this.next();
  10326. if (this.match(types.parenL)) {
  10327. this.expect(types.parenL);
  10328. clause.param = this.parseCatchClauseParam();
  10329. this.expect(types.parenR);
  10330. } else {
  10331. clause.param = null;
  10332. this.scope.enter(SCOPE_OTHER);
  10333. }
  10334. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  10335. this.scope.exit();
  10336. node.handler = this.finishNode(clause, "CatchClause");
  10337. }
  10338. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  10339. if (!node.handler && !node.finalizer) {
  10340. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  10341. }
  10342. return this.finishNode(node, "TryStatement");
  10343. }
  10344. parseVarStatement(node, kind) {
  10345. this.next();
  10346. this.parseVar(node, false, kind);
  10347. this.semicolon();
  10348. return this.finishNode(node, "VariableDeclaration");
  10349. }
  10350. parseWhileStatement(node) {
  10351. this.next();
  10352. node.test = this.parseHeaderExpression();
  10353. this.state.labels.push(loopLabel);
  10354. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  10355. this.state.labels.pop();
  10356. return this.finishNode(node, "WhileStatement");
  10357. }
  10358. parseWithStatement(node) {
  10359. if (this.state.strict) {
  10360. this.raise(this.state.start, ErrorMessages.StrictWith);
  10361. }
  10362. this.next();
  10363. node.object = this.parseHeaderExpression();
  10364. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  10365. return this.finishNode(node, "WithStatement");
  10366. }
  10367. parseEmptyStatement(node) {
  10368. this.next();
  10369. return this.finishNode(node, "EmptyStatement");
  10370. }
  10371. parseLabeledStatement(node, maybeName, expr, context) {
  10372. for (const label of this.state.labels) {
  10373. if (label.name === maybeName) {
  10374. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  10375. }
  10376. }
  10377. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  10378. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  10379. const label = this.state.labels[i];
  10380. if (label.statementStart === node.start) {
  10381. label.statementStart = this.state.start;
  10382. label.kind = kind;
  10383. } else {
  10384. break;
  10385. }
  10386. }
  10387. this.state.labels.push({
  10388. name: maybeName,
  10389. kind: kind,
  10390. statementStart: this.state.start
  10391. });
  10392. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  10393. this.state.labels.pop();
  10394. node.label = expr;
  10395. return this.finishNode(node, "LabeledStatement");
  10396. }
  10397. parseExpressionStatement(node, expr) {
  10398. node.expression = expr;
  10399. this.semicolon();
  10400. return this.finishNode(node, "ExpressionStatement");
  10401. }
  10402. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  10403. const node = this.startNode();
  10404. if (allowDirectives) {
  10405. this.state.strictErrors.clear();
  10406. }
  10407. this.expect(types.braceL);
  10408. if (createNewLexicalScope) {
  10409. this.scope.enter(SCOPE_OTHER);
  10410. }
  10411. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  10412. if (createNewLexicalScope) {
  10413. this.scope.exit();
  10414. }
  10415. return this.finishNode(node, "BlockStatement");
  10416. }
  10417. isValidDirective(stmt) {
  10418. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  10419. }
  10420. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  10421. const body = node.body = [];
  10422. const directives = node.directives = [];
  10423. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  10424. }
  10425. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  10426. const oldStrict = this.state.strict;
  10427. let hasStrictModeDirective = false;
  10428. let parsedNonDirective = false;
  10429. while (!this.match(end)) {
  10430. const stmt = this.parseStatement(null, topLevel);
  10431. if (directives && !parsedNonDirective) {
  10432. if (this.isValidDirective(stmt)) {
  10433. const directive = this.stmtToDirective(stmt);
  10434. directives.push(directive);
  10435. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  10436. hasStrictModeDirective = true;
  10437. this.setStrict(true);
  10438. }
  10439. continue;
  10440. }
  10441. parsedNonDirective = true;
  10442. this.state.strictErrors.clear();
  10443. }
  10444. body.push(stmt);
  10445. }
  10446. if (afterBlockParse) {
  10447. afterBlockParse.call(this, hasStrictModeDirective);
  10448. }
  10449. if (!oldStrict) {
  10450. this.setStrict(false);
  10451. }
  10452. this.next();
  10453. }
  10454. parseFor(node, init) {
  10455. node.init = init;
  10456. this.semicolon(false);
  10457. node.test = this.match(types.semi) ? null : this.parseExpression();
  10458. this.semicolon(false);
  10459. node.update = this.match(types.parenR) ? null : this.parseExpression();
  10460. this.expect(types.parenR);
  10461. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10462. this.scope.exit();
  10463. this.state.labels.pop();
  10464. return this.finishNode(node, "ForStatement");
  10465. }
  10466. parseForIn(node, init, awaitAt) {
  10467. const isForIn = this.match(types._in);
  10468. this.next();
  10469. if (isForIn) {
  10470. if (awaitAt > -1) this.unexpected(awaitAt);
  10471. } else {
  10472. node.await = awaitAt > -1;
  10473. }
  10474. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  10475. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  10476. } else if (init.type === "AssignmentPattern") {
  10477. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  10478. }
  10479. node.left = init;
  10480. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  10481. this.expect(types.parenR);
  10482. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10483. this.scope.exit();
  10484. this.state.labels.pop();
  10485. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  10486. }
  10487. parseVar(node, isFor, kind) {
  10488. const declarations = node.declarations = [];
  10489. const isTypescript = this.hasPlugin("typescript");
  10490. node.kind = kind;
  10491. for (;;) {
  10492. const decl = this.startNode();
  10493. this.parseVarId(decl, kind);
  10494. if (this.eat(types.eq)) {
  10495. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  10496. } else {
  10497. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  10498. if (!isTypescript) {
  10499. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  10500. }
  10501. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  10502. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  10503. }
  10504. decl.init = null;
  10505. }
  10506. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  10507. if (!this.eat(types.comma)) break;
  10508. }
  10509. return node;
  10510. }
  10511. parseVarId(decl, kind) {
  10512. decl.id = this.parseBindingAtom();
  10513. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  10514. }
  10515. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  10516. const isStatement = statement & FUNC_STATEMENT;
  10517. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  10518. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  10519. this.initFunction(node, isAsync);
  10520. if (this.match(types.star) && isHangingStatement) {
  10521. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  10522. }
  10523. node.generator = this.eat(types.star);
  10524. if (isStatement) {
  10525. node.id = this.parseFunctionId(requireId);
  10526. }
  10527. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10528. this.state.maybeInArrowParameters = false;
  10529. this.scope.enter(SCOPE_FUNCTION);
  10530. this.prodParam.enter(functionFlags(isAsync, node.generator));
  10531. if (!isStatement) {
  10532. node.id = this.parseFunctionId();
  10533. }
  10534. this.parseFunctionParams(node, false);
  10535. this.withTopicForbiddingContext(() => {
  10536. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  10537. });
  10538. this.prodParam.exit();
  10539. this.scope.exit();
  10540. if (isStatement && !isHangingStatement) {
  10541. this.registerFunctionStatementId(node);
  10542. }
  10543. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10544. return node;
  10545. }
  10546. parseFunctionId(requireId) {
  10547. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  10548. }
  10549. parseFunctionParams(node, allowModifiers) {
  10550. this.expect(types.parenL);
  10551. this.expressionScope.enter(newParameterDeclarationScope());
  10552. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  10553. this.expressionScope.exit();
  10554. }
  10555. registerFunctionStatementId(node) {
  10556. if (!node.id) return;
  10557. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start);
  10558. }
  10559. parseClass(node, isStatement, optionalId) {
  10560. this.next();
  10561. this.takeDecorators(node);
  10562. const oldStrict = this.state.strict;
  10563. this.state.strict = true;
  10564. this.parseClassId(node, isStatement, optionalId);
  10565. this.parseClassSuper(node);
  10566. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  10567. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  10568. }
  10569. isClassProperty() {
  10570. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  10571. }
  10572. isClassMethod() {
  10573. return this.match(types.parenL);
  10574. }
  10575. isNonstaticConstructor(method) {
  10576. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  10577. }
  10578. parseClassBody(constructorAllowsSuper, oldStrict) {
  10579. this.classScope.enter();
  10580. const state = {
  10581. constructorAllowsSuper,
  10582. hadConstructor: false
  10583. };
  10584. let decorators = [];
  10585. const classBody = this.startNode();
  10586. classBody.body = [];
  10587. this.expect(types.braceL);
  10588. this.withTopicForbiddingContext(() => {
  10589. while (!this.match(types.braceR)) {
  10590. if (this.eat(types.semi)) {
  10591. if (decorators.length > 0) {
  10592. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  10593. }
  10594. continue;
  10595. }
  10596. if (this.match(types.at)) {
  10597. decorators.push(this.parseDecorator());
  10598. continue;
  10599. }
  10600. const member = this.startNode();
  10601. if (decorators.length) {
  10602. member.decorators = decorators;
  10603. this.resetStartLocationFromNode(member, decorators[0]);
  10604. decorators = [];
  10605. }
  10606. this.parseClassMember(classBody, member, state);
  10607. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  10608. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  10609. }
  10610. }
  10611. });
  10612. this.state.strict = oldStrict;
  10613. this.next();
  10614. if (decorators.length) {
  10615. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  10616. }
  10617. this.classScope.exit();
  10618. return this.finishNode(classBody, "ClassBody");
  10619. }
  10620. parseClassMemberFromModifier(classBody, member) {
  10621. const key = this.parseIdentifier(true);
  10622. if (this.isClassMethod()) {
  10623. const method = member;
  10624. method.kind = "method";
  10625. method.computed = false;
  10626. method.key = key;
  10627. method.static = false;
  10628. this.pushClassMethod(classBody, method, false, false, false, false);
  10629. return true;
  10630. } else if (this.isClassProperty()) {
  10631. const prop = member;
  10632. prop.computed = false;
  10633. prop.key = key;
  10634. prop.static = false;
  10635. classBody.body.push(this.parseClassProperty(prop));
  10636. return true;
  10637. }
  10638. return false;
  10639. }
  10640. parseClassMember(classBody, member, state) {
  10641. const isStatic = this.isContextual("static");
  10642. if (isStatic) {
  10643. if (this.parseClassMemberFromModifier(classBody, member)) {
  10644. return;
  10645. }
  10646. if (this.eat(types.braceL)) {
  10647. this.parseClassStaticBlock(classBody, member);
  10648. return;
  10649. }
  10650. }
  10651. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  10652. }
  10653. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  10654. const publicMethod = member;
  10655. const privateMethod = member;
  10656. const publicProp = member;
  10657. const privateProp = member;
  10658. const method = publicMethod;
  10659. const publicMember = publicMethod;
  10660. member.static = isStatic;
  10661. if (this.eat(types.star)) {
  10662. method.kind = "method";
  10663. this.parseClassElementName(method);
  10664. if (this.isPrivateName(method.key)) {
  10665. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  10666. return;
  10667. }
  10668. if (this.isNonstaticConstructor(publicMethod)) {
  10669. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  10670. }
  10671. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  10672. return;
  10673. }
  10674. const containsEsc = this.state.containsEsc;
  10675. const key = this.parseClassElementName(member);
  10676. const isPrivate = this.isPrivateName(key);
  10677. const isSimple = key.type === "Identifier";
  10678. const maybeQuestionTokenStart = this.state.start;
  10679. this.parsePostMemberNameModifiers(publicMember);
  10680. if (this.isClassMethod()) {
  10681. method.kind = "method";
  10682. if (isPrivate) {
  10683. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10684. return;
  10685. }
  10686. const isConstructor = this.isNonstaticConstructor(publicMethod);
  10687. let allowsDirectSuper = false;
  10688. if (isConstructor) {
  10689. publicMethod.kind = "constructor";
  10690. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  10691. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  10692. }
  10693. state.hadConstructor = true;
  10694. allowsDirectSuper = state.constructorAllowsSuper;
  10695. }
  10696. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  10697. } else if (this.isClassProperty()) {
  10698. if (isPrivate) {
  10699. this.pushClassPrivateProperty(classBody, privateProp);
  10700. } else {
  10701. this.pushClassProperty(classBody, publicProp);
  10702. }
  10703. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  10704. const isGenerator = this.eat(types.star);
  10705. if (publicMember.optional) {
  10706. this.unexpected(maybeQuestionTokenStart);
  10707. }
  10708. method.kind = "method";
  10709. this.parseClassElementName(method);
  10710. this.parsePostMemberNameModifiers(publicMember);
  10711. if (this.isPrivateName(method.key)) {
  10712. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  10713. } else {
  10714. if (this.isNonstaticConstructor(publicMethod)) {
  10715. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  10716. }
  10717. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  10718. }
  10719. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  10720. method.kind = key.name;
  10721. this.parseClassElementName(publicMethod);
  10722. if (this.isPrivateName(method.key)) {
  10723. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10724. } else {
  10725. if (this.isNonstaticConstructor(publicMethod)) {
  10726. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  10727. }
  10728. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  10729. }
  10730. this.checkGetterSetterParams(publicMethod);
  10731. } else if (this.isLineTerminator()) {
  10732. if (isPrivate) {
  10733. this.pushClassPrivateProperty(classBody, privateProp);
  10734. } else {
  10735. this.pushClassProperty(classBody, publicProp);
  10736. }
  10737. } else {
  10738. this.unexpected();
  10739. }
  10740. }
  10741. parseClassElementName(member) {
  10742. const key = this.parsePropertyName(member, true);
  10743. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  10744. this.raise(key.start, ErrorMessages.StaticPrototype);
  10745. }
  10746. if (this.isPrivateName(key) && this.getPrivateNameSV(key) === "constructor") {
  10747. this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
  10748. }
  10749. return key;
  10750. }
  10751. parseClassStaticBlock(classBody, member) {
  10752. var _member$decorators;
  10753. this.expectPlugin("classStaticBlock", member.start);
  10754. this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
  10755. const oldLabels = this.state.labels;
  10756. this.state.labels = [];
  10757. this.prodParam.enter(PARAM);
  10758. const body = member.body = [];
  10759. this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
  10760. this.prodParam.exit();
  10761. this.scope.exit();
  10762. this.state.labels = oldLabels;
  10763. classBody.body.push(this.finishNode(member, "StaticBlock"));
  10764. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  10765. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  10766. }
  10767. }
  10768. pushClassProperty(classBody, prop) {
  10769. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  10770. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  10771. }
  10772. classBody.body.push(this.parseClassProperty(prop));
  10773. }
  10774. pushClassPrivateProperty(classBody, prop) {
  10775. this.expectPlugin("classPrivateProperties", prop.key.start);
  10776. const node = this.parseClassPrivateProperty(prop);
  10777. classBody.body.push(node);
  10778. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start);
  10779. }
  10780. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  10781. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  10782. }
  10783. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  10784. this.expectPlugin("classPrivateMethods", method.key.start);
  10785. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  10786. classBody.body.push(node);
  10787. 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;
  10788. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start);
  10789. }
  10790. parsePostMemberNameModifiers(methodOrProp) {}
  10791. parseClassPrivateProperty(node) {
  10792. this.parseInitializer(node);
  10793. this.semicolon();
  10794. return this.finishNode(node, "ClassPrivateProperty");
  10795. }
  10796. parseClassProperty(node) {
  10797. if (!node.typeAnnotation || this.match(types.eq)) {
  10798. this.expectPlugin("classProperties");
  10799. }
  10800. this.parseInitializer(node);
  10801. this.semicolon();
  10802. return this.finishNode(node, "ClassProperty");
  10803. }
  10804. parseInitializer(node) {
  10805. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10806. this.expressionScope.enter(newExpressionScope());
  10807. this.prodParam.enter(PARAM);
  10808. node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
  10809. this.expressionScope.exit();
  10810. this.prodParam.exit();
  10811. this.scope.exit();
  10812. }
  10813. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  10814. if (this.match(types.name)) {
  10815. node.id = this.parseIdentifier();
  10816. if (isStatement) {
  10817. this.checkLVal(node.id, "class name", bindingType);
  10818. }
  10819. } else {
  10820. if (optionalId || !isStatement) {
  10821. node.id = null;
  10822. } else {
  10823. this.unexpected(null, ErrorMessages.MissingClassName);
  10824. }
  10825. }
  10826. }
  10827. parseClassSuper(node) {
  10828. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  10829. }
  10830. parseExport(node) {
  10831. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  10832. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  10833. const hasStar = parseAfterDefault && this.eatExportStar(node);
  10834. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  10835. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  10836. const isFromRequired = hasDefault || hasStar;
  10837. if (hasStar && !hasNamespace) {
  10838. if (hasDefault) this.unexpected();
  10839. this.parseExportFrom(node, true);
  10840. return this.finishNode(node, "ExportAllDeclaration");
  10841. }
  10842. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  10843. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  10844. throw this.unexpected(null, types.braceL);
  10845. }
  10846. let hasDeclaration;
  10847. if (isFromRequired || hasSpecifiers) {
  10848. hasDeclaration = false;
  10849. this.parseExportFrom(node, isFromRequired);
  10850. } else {
  10851. hasDeclaration = this.maybeParseExportDeclaration(node);
  10852. }
  10853. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  10854. this.checkExport(node, true, false, !!node.source);
  10855. return this.finishNode(node, "ExportNamedDeclaration");
  10856. }
  10857. if (this.eat(types._default)) {
  10858. node.declaration = this.parseExportDefaultExpression();
  10859. this.checkExport(node, true, true);
  10860. return this.finishNode(node, "ExportDefaultDeclaration");
  10861. }
  10862. throw this.unexpected(null, types.braceL);
  10863. }
  10864. eatExportStar(node) {
  10865. return this.eat(types.star);
  10866. }
  10867. maybeParseExportDefaultSpecifier(node) {
  10868. if (this.isExportDefaultSpecifier()) {
  10869. this.expectPlugin("exportDefaultFrom");
  10870. const specifier = this.startNode();
  10871. specifier.exported = this.parseIdentifier(true);
  10872. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10873. return true;
  10874. }
  10875. return false;
  10876. }
  10877. maybeParseExportNamespaceSpecifier(node) {
  10878. if (this.isContextual("as")) {
  10879. if (!node.specifiers) node.specifiers = [];
  10880. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  10881. this.next();
  10882. specifier.exported = this.parseModuleExportName();
  10883. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  10884. return true;
  10885. }
  10886. return false;
  10887. }
  10888. maybeParseExportNamedSpecifiers(node) {
  10889. if (this.match(types.braceL)) {
  10890. if (!node.specifiers) node.specifiers = [];
  10891. node.specifiers.push(...this.parseExportSpecifiers());
  10892. node.source = null;
  10893. node.declaration = null;
  10894. return true;
  10895. }
  10896. return false;
  10897. }
  10898. maybeParseExportDeclaration(node) {
  10899. if (this.shouldParseExportDeclaration()) {
  10900. node.specifiers = [];
  10901. node.source = null;
  10902. node.declaration = this.parseExportDeclaration(node);
  10903. return true;
  10904. }
  10905. return false;
  10906. }
  10907. isAsyncFunction() {
  10908. if (!this.isContextual("async")) return false;
  10909. const next = this.nextTokenStart();
  10910. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10911. }
  10912. parseExportDefaultExpression() {
  10913. const expr = this.startNode();
  10914. const isAsync = this.isAsyncFunction();
  10915. if (this.match(types._function) || isAsync) {
  10916. this.next();
  10917. if (isAsync) {
  10918. this.next();
  10919. }
  10920. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10921. } else if (this.match(types._class)) {
  10922. return this.parseClass(expr, true, true);
  10923. } else if (this.match(types.at)) {
  10924. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10925. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10926. }
  10927. this.parseDecorators(false);
  10928. return this.parseClass(expr, true, true);
  10929. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10930. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  10931. } else {
  10932. const res = this.parseMaybeAssignAllowIn();
  10933. this.semicolon();
  10934. return res;
  10935. }
  10936. }
  10937. parseExportDeclaration(node) {
  10938. return this.parseStatement(null);
  10939. }
  10940. isExportDefaultSpecifier() {
  10941. if (this.match(types.name)) {
  10942. const value = this.state.value;
  10943. if (value === "async" && !this.state.containsEsc || value === "let") {
  10944. return false;
  10945. }
  10946. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  10947. const l = this.lookahead();
  10948. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  10949. this.expectOnePlugin(["flow", "typescript"]);
  10950. return false;
  10951. }
  10952. }
  10953. } else if (!this.match(types._default)) {
  10954. return false;
  10955. }
  10956. const next = this.nextTokenStart();
  10957. const hasFrom = this.isUnparsedContextual(next, "from");
  10958. if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
  10959. return true;
  10960. }
  10961. if (this.match(types._default) && hasFrom) {
  10962. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  10963. return nextAfterFrom === 34 || nextAfterFrom === 39;
  10964. }
  10965. return false;
  10966. }
  10967. parseExportFrom(node, expect) {
  10968. if (this.eatContextual("from")) {
  10969. node.source = this.parseImportSource();
  10970. this.checkExport(node);
  10971. const assertions = this.maybeParseImportAssertions();
  10972. if (assertions) {
  10973. node.assertions = assertions;
  10974. }
  10975. } else {
  10976. if (expect) {
  10977. this.unexpected();
  10978. } else {
  10979. node.source = null;
  10980. }
  10981. }
  10982. this.semicolon();
  10983. }
  10984. shouldParseExportDeclaration() {
  10985. if (this.match(types.at)) {
  10986. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  10987. if (this.hasPlugin("decorators")) {
  10988. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10989. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10990. } else {
  10991. return true;
  10992. }
  10993. }
  10994. }
  10995. return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction();
  10996. }
  10997. checkExport(node, checkNames, isDefault, isFrom) {
  10998. if (checkNames) {
  10999. if (isDefault) {
  11000. this.checkDuplicateExports(node, "default");
  11001. if (this.hasPlugin("exportDefaultFrom")) {
  11002. var _declaration$extra;
  11003. const declaration = node.declaration;
  11004. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  11005. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  11006. }
  11007. }
  11008. } else if (node.specifiers && node.specifiers.length) {
  11009. for (const specifier of node.specifiers) {
  11010. const {
  11011. exported
  11012. } = specifier;
  11013. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  11014. this.checkDuplicateExports(specifier, exportedName);
  11015. if (!isFrom && specifier.local) {
  11016. const {
  11017. local
  11018. } = specifier;
  11019. if (local.type === "StringLiteral") {
  11020. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName);
  11021. } else {
  11022. this.checkReservedWord(local.name, local.start, true, false);
  11023. this.scope.checkLocalExport(local);
  11024. }
  11025. }
  11026. }
  11027. } else if (node.declaration) {
  11028. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  11029. const id = node.declaration.id;
  11030. if (!id) throw new Error("Assertion failure");
  11031. this.checkDuplicateExports(node, id.name);
  11032. } else if (node.declaration.type === "VariableDeclaration") {
  11033. for (const declaration of node.declaration.declarations) {
  11034. this.checkDeclaration(declaration.id);
  11035. }
  11036. }
  11037. }
  11038. }
  11039. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11040. if (currentContextDecorators.length) {
  11041. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  11042. }
  11043. }
  11044. checkDeclaration(node) {
  11045. if (node.type === "Identifier") {
  11046. this.checkDuplicateExports(node, node.name);
  11047. } else if (node.type === "ObjectPattern") {
  11048. for (const prop of node.properties) {
  11049. this.checkDeclaration(prop);
  11050. }
  11051. } else if (node.type === "ArrayPattern") {
  11052. for (const elem of node.elements) {
  11053. if (elem) {
  11054. this.checkDeclaration(elem);
  11055. }
  11056. }
  11057. } else if (node.type === "ObjectProperty") {
  11058. this.checkDeclaration(node.value);
  11059. } else if (node.type === "RestElement") {
  11060. this.checkDeclaration(node.argument);
  11061. } else if (node.type === "AssignmentPattern") {
  11062. this.checkDeclaration(node.left);
  11063. }
  11064. }
  11065. checkDuplicateExports(node, name) {
  11066. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  11067. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  11068. }
  11069. this.state.exportedIdentifiers.push(name);
  11070. }
  11071. parseExportSpecifiers() {
  11072. const nodes = [];
  11073. let first = true;
  11074. this.expect(types.braceL);
  11075. while (!this.eat(types.braceR)) {
  11076. if (first) {
  11077. first = false;
  11078. } else {
  11079. this.expect(types.comma);
  11080. if (this.eat(types.braceR)) break;
  11081. }
  11082. const node = this.startNode();
  11083. node.local = this.parseModuleExportName();
  11084. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
  11085. nodes.push(this.finishNode(node, "ExportSpecifier"));
  11086. }
  11087. return nodes;
  11088. }
  11089. parseModuleExportName() {
  11090. if (this.match(types.string)) {
  11091. this.expectPlugin("moduleStringNames");
  11092. const result = this.parseLiteral(this.state.value, "StringLiteral");
  11093. const surrogate = result.value.match(loneSurrogate);
  11094. if (surrogate) {
  11095. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  11096. }
  11097. return result;
  11098. }
  11099. return this.parseIdentifier(true);
  11100. }
  11101. parseImport(node) {
  11102. node.specifiers = [];
  11103. if (!this.match(types.string)) {
  11104. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  11105. const parseNext = !hasDefault || this.eat(types.comma);
  11106. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  11107. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  11108. this.expectContextual("from");
  11109. }
  11110. node.source = this.parseImportSource();
  11111. const assertions = this.maybeParseImportAssertions();
  11112. if (assertions) {
  11113. node.assertions = assertions;
  11114. } else {
  11115. const attributes = this.maybeParseModuleAttributes();
  11116. if (attributes) {
  11117. node.attributes = attributes;
  11118. }
  11119. }
  11120. this.semicolon();
  11121. return this.finishNode(node, "ImportDeclaration");
  11122. }
  11123. parseImportSource() {
  11124. if (!this.match(types.string)) this.unexpected();
  11125. return this.parseExprAtom();
  11126. }
  11127. shouldParseDefaultImport(node) {
  11128. return this.match(types.name);
  11129. }
  11130. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  11131. specifier.local = this.parseIdentifier();
  11132. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  11133. node.specifiers.push(this.finishNode(specifier, type));
  11134. }
  11135. parseAssertEntries() {
  11136. const attrs = [];
  11137. const attrNames = new Set();
  11138. do {
  11139. if (this.match(types.braceR)) {
  11140. break;
  11141. }
  11142. const node = this.startNode();
  11143. const keyName = this.state.value;
  11144. if (this.match(types.string)) {
  11145. node.key = this.parseLiteral(keyName, "StringLiteral");
  11146. } else {
  11147. node.key = this.parseIdentifier(true);
  11148. }
  11149. this.expect(types.colon);
  11150. if (keyName !== "type") {
  11151. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName);
  11152. }
  11153. if (attrNames.has(keyName)) {
  11154. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  11155. }
  11156. attrNames.add(keyName);
  11157. if (!this.match(types.string)) {
  11158. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  11159. }
  11160. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  11161. this.finishNode(node, "ImportAttribute");
  11162. attrs.push(node);
  11163. } while (this.eat(types.comma));
  11164. return attrs;
  11165. }
  11166. maybeParseModuleAttributes() {
  11167. if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
  11168. this.expectPlugin("moduleAttributes");
  11169. this.next();
  11170. } else {
  11171. if (this.hasPlugin("moduleAttributes")) return [];
  11172. return null;
  11173. }
  11174. const attrs = [];
  11175. const attributes = new Set();
  11176. do {
  11177. const node = this.startNode();
  11178. node.key = this.parseIdentifier(true);
  11179. if (node.key.name !== "type") {
  11180. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  11181. }
  11182. if (attributes.has(node.key.name)) {
  11183. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  11184. }
  11185. attributes.add(node.key.name);
  11186. this.expect(types.colon);
  11187. if (!this.match(types.string)) {
  11188. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  11189. }
  11190. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  11191. this.finishNode(node, "ImportAttribute");
  11192. attrs.push(node);
  11193. } while (this.eat(types.comma));
  11194. return attrs;
  11195. }
  11196. maybeParseImportAssertions() {
  11197. if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) {
  11198. this.expectPlugin("importAssertions");
  11199. this.next();
  11200. } else {
  11201. if (this.hasPlugin("importAssertions")) return [];
  11202. return null;
  11203. }
  11204. this.eat(types.braceL);
  11205. const attrs = this.parseAssertEntries();
  11206. this.eat(types.braceR);
  11207. return attrs;
  11208. }
  11209. maybeParseDefaultImportSpecifier(node) {
  11210. if (this.shouldParseDefaultImport(node)) {
  11211. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  11212. return true;
  11213. }
  11214. return false;
  11215. }
  11216. maybeParseStarImportSpecifier(node) {
  11217. if (this.match(types.star)) {
  11218. const specifier = this.startNode();
  11219. this.next();
  11220. this.expectContextual("as");
  11221. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  11222. return true;
  11223. }
  11224. return false;
  11225. }
  11226. parseNamedImportSpecifiers(node) {
  11227. let first = true;
  11228. this.expect(types.braceL);
  11229. while (!this.eat(types.braceR)) {
  11230. if (first) {
  11231. first = false;
  11232. } else {
  11233. if (this.eat(types.colon)) {
  11234. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  11235. }
  11236. this.expect(types.comma);
  11237. if (this.eat(types.braceR)) break;
  11238. }
  11239. this.parseImportSpecifier(node);
  11240. }
  11241. }
  11242. parseImportSpecifier(node) {
  11243. const specifier = this.startNode();
  11244. specifier.imported = this.parseModuleExportName();
  11245. if (this.eatContextual("as")) {
  11246. specifier.local = this.parseIdentifier();
  11247. } else {
  11248. const {
  11249. imported
  11250. } = specifier;
  11251. if (imported.type === "StringLiteral") {
  11252. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  11253. }
  11254. this.checkReservedWord(imported.name, specifier.start, true, true);
  11255. specifier.local = imported.__clone();
  11256. }
  11257. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  11258. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  11259. }
  11260. }
  11261. class Parser extends StatementParser {
  11262. constructor(options, input) {
  11263. options = getOptions(options);
  11264. super(options, input);
  11265. this.options = options;
  11266. this.initializeScopes();
  11267. this.plugins = pluginsMap(this.options.plugins);
  11268. this.filename = options.sourceFilename;
  11269. }
  11270. getScopeHandler() {
  11271. return ScopeHandler;
  11272. }
  11273. parse() {
  11274. this.enterInitialScopes();
  11275. const file = this.startNode();
  11276. const program = this.startNode();
  11277. this.nextToken();
  11278. file.errors = null;
  11279. this.parseTopLevel(file, program);
  11280. file.errors = this.state.errors;
  11281. return file;
  11282. }
  11283. }
  11284. function pluginsMap(plugins) {
  11285. const pluginMap = new Map();
  11286. for (const plugin of plugins) {
  11287. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  11288. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  11289. }
  11290. return pluginMap;
  11291. }
  11292. function parse(input, options) {
  11293. var _options;
  11294. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  11295. options = Object.assign({}, options);
  11296. try {
  11297. options.sourceType = "module";
  11298. const parser = getParser(options, input);
  11299. const ast = parser.parse();
  11300. if (parser.sawUnambiguousESM) {
  11301. return ast;
  11302. }
  11303. if (parser.ambiguousScriptDifferentAst) {
  11304. try {
  11305. options.sourceType = "script";
  11306. return getParser(options, input).parse();
  11307. } catch (_unused) {}
  11308. } else {
  11309. ast.program.sourceType = "script";
  11310. }
  11311. return ast;
  11312. } catch (moduleError) {
  11313. try {
  11314. options.sourceType = "script";
  11315. return getParser(options, input).parse();
  11316. } catch (_unused2) {}
  11317. throw moduleError;
  11318. }
  11319. } else {
  11320. return getParser(options, input).parse();
  11321. }
  11322. }
  11323. function parseExpression(input, options) {
  11324. const parser = getParser(options, input);
  11325. if (parser.options.strictMode) {
  11326. parser.state.strict = true;
  11327. }
  11328. return parser.getExpression();
  11329. }
  11330. function getParser(options, input) {
  11331. let cls = Parser;
  11332. if (options != null && options.plugins) {
  11333. validatePlugins(options.plugins);
  11334. cls = getParserClass(options.plugins);
  11335. }
  11336. return new cls(options, input);
  11337. }
  11338. const parserClassCache = {};
  11339. function getParserClass(pluginsFromOptions) {
  11340. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  11341. const key = pluginList.join("/");
  11342. let cls = parserClassCache[key];
  11343. if (!cls) {
  11344. cls = Parser;
  11345. for (const plugin of pluginList) {
  11346. cls = mixinPlugins[plugin](cls);
  11347. }
  11348. parserClassCache[key] = cls;
  11349. }
  11350. return cls;
  11351. }
  11352. exports.parse = parse;
  11353. exports.parseExpression = parseExpression;
  11354. exports.tokTypes = types;
  11355. //# sourceMappingURL=index.js.map