index.js 402 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516
  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. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  530. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules",
  531. AwaitNotInAsyncFunction: "'await' is only allowed within async functions",
  532. BadGetterArity: "getter must not have any formal parameters",
  533. BadSetterArity: "setter must have exactly one formal parameter",
  534. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  535. ConstructorClassField: "Classes may not have a field named 'constructor'",
  536. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  537. ConstructorIsAccessor: "Class constructor may not be an accessor",
  538. ConstructorIsAsync: "Constructor can't be an async function",
  539. ConstructorIsGenerator: "Constructor can't be a generator",
  540. DeclarationMissingInitializer: "%0 require an initialization value",
  541. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  542. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  543. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  544. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  545. DecoratorStaticBlock: "Decorators can't be used with a static block",
  546. DeletePrivateField: "Deleting a private field is not allowed",
  547. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  548. DuplicateConstructor: "Duplicate constructor in the same class",
  549. DuplicateDefaultExport: "Only one default export allowed per module.",
  550. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  551. DuplicateProto: "Redefinition of __proto__ property",
  552. DuplicateRegExpFlags: "Duplicate regular expression flag",
  553. DuplicateStaticBlock: "Duplicate static block in the same class",
  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. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  595. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  596. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
  597. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
  598. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
  599. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
  600. ModuleExportUndefined: "Export '%0' is not defined",
  601. MultipleDefaultsInSwitch: "Multiple default clauses",
  602. NewlineAfterThrow: "Illegal newline after throw",
  603. NoCatchOrFinally: "Missing catch or finally clause",
  604. NumberIdentifier: "Identifier directly after number",
  605. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  606. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  607. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  608. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  609. ParamDupe: "Argument name clash",
  610. PatternHasAccessor: "Object pattern can't contain getter or setter",
  611. PatternHasMethod: "Object pattern can't contain methods",
  612. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  613. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  614. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  615. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  616. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  617. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  618. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
  619. PrivateNameRedeclaration: "Duplicate private name #%0",
  620. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  621. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  622. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  623. RecordNoProto: "'__proto__' is not allowed in Record expressions",
  624. RestTrailingComma: "Unexpected trailing comma after rest element",
  625. 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",
  626. StaticPrototype: "Classes may not have static property named prototype",
  627. StrictDelete: "Deleting local variable in strict mode",
  628. StrictEvalArguments: "Assigning to '%0' in strict mode",
  629. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  630. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  631. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
  632. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  633. StrictWith: "'with' in strict mode",
  634. 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?",
  635. SuperPrivateField: "Private fields can't be accessed on super",
  636. TrailingDecorator: "Decorators must be attached to a class element",
  637. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  638. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  639. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  640. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  641. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  642. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  643. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  644. UnexpectedKeyword: "Unexpected keyword '%0'",
  645. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  646. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  647. UnexpectedNewTarget: "new.target can only be used in functions",
  648. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  649. 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).",
  650. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  651. UnexpectedSuper: "super is only allowed in object methods and classes",
  652. UnexpectedToken: "Unexpected token '%0'",
  653. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  654. UnsupportedBind: "Binding should be performed on object property.",
  655. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  656. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  657. UnsupportedImport: "import can only be used in import() or import.meta",
  658. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  659. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  660. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  661. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  662. UnterminatedComment: "Unterminated comment",
  663. UnterminatedRegExp: "Unterminated regular expression",
  664. UnterminatedString: "Unterminated string constant",
  665. UnterminatedTemplate: "Unterminated template",
  666. VarRedeclaration: "Identifier '%0' has already been declared",
  667. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  668. YieldInParameter: "Yield expression is not allowed in formal parameters",
  669. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  670. });
  671. class ParserError extends CommentsParser {
  672. getLocationForPosition(pos) {
  673. let loc;
  674. 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);
  675. return loc;
  676. }
  677. raise(pos, errorTemplate, ...params) {
  678. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  679. }
  680. raiseWithData(pos, data, errorTemplate, ...params) {
  681. const loc = this.getLocationForPosition(pos);
  682. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  683. return this._raise(Object.assign({
  684. loc,
  685. pos
  686. }, data), message);
  687. }
  688. _raise(errorContext, message) {
  689. const err = new SyntaxError(message);
  690. Object.assign(err, errorContext);
  691. if (this.options.errorRecovery) {
  692. if (!this.isLookahead) this.state.errors.push(err);
  693. return err;
  694. } else {
  695. throw err;
  696. }
  697. }
  698. }
  699. var estree = (superClass => class extends superClass {
  700. estreeParseRegExpLiteral({
  701. pattern,
  702. flags
  703. }) {
  704. let regex = null;
  705. try {
  706. regex = new RegExp(pattern, flags);
  707. } catch (e) {}
  708. const node = this.estreeParseLiteral(regex);
  709. node.regex = {
  710. pattern,
  711. flags
  712. };
  713. return node;
  714. }
  715. estreeParseBigIntLiteral(value) {
  716. let bigInt;
  717. try {
  718. bigInt = BigInt(value);
  719. } catch (_unused) {
  720. bigInt = null;
  721. }
  722. const node = this.estreeParseLiteral(bigInt);
  723. node.bigint = String(node.value || value);
  724. return node;
  725. }
  726. estreeParseDecimalLiteral(value) {
  727. const decimal = null;
  728. const node = this.estreeParseLiteral(decimal);
  729. node.decimal = String(node.value || value);
  730. return node;
  731. }
  732. estreeParseLiteral(value) {
  733. return this.parseLiteral(value, "Literal");
  734. }
  735. directiveToStmt(directive) {
  736. const directiveLiteral = directive.value;
  737. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  738. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  739. expression.value = directiveLiteral.extra.expressionValue;
  740. expression.raw = directiveLiteral.extra.raw;
  741. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  742. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  743. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  744. }
  745. initFunction(node, isAsync) {
  746. super.initFunction(node, isAsync);
  747. node.expression = false;
  748. }
  749. checkDeclaration(node) {
  750. if (node != null && this.isObjectProperty(node)) {
  751. this.checkDeclaration(node.value);
  752. } else {
  753. super.checkDeclaration(node);
  754. }
  755. }
  756. getObjectOrClassMethodParams(method) {
  757. return method.value.params;
  758. }
  759. isValidDirective(stmt) {
  760. var _stmt$expression$extr;
  761. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) == null ? void 0 : _stmt$expression$extr.parenthesized);
  762. }
  763. stmtToDirective(stmt) {
  764. const directive = super.stmtToDirective(stmt);
  765. const value = stmt.expression.value;
  766. this.addExtra(directive.value, "expressionValue", value);
  767. return directive;
  768. }
  769. parseBlockBody(node, ...args) {
  770. super.parseBlockBody(node, ...args);
  771. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  772. node.body = directiveStatements.concat(node.body);
  773. delete node.directives;
  774. }
  775. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  776. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  777. if (method.typeParameters) {
  778. method.value.typeParameters = method.typeParameters;
  779. delete method.typeParameters;
  780. }
  781. classBody.body.push(method);
  782. }
  783. parseExprAtom(refExpressionErrors) {
  784. switch (this.state.type) {
  785. case types.num:
  786. case types.string:
  787. return this.estreeParseLiteral(this.state.value);
  788. case types.regexp:
  789. return this.estreeParseRegExpLiteral(this.state.value);
  790. case types.bigint:
  791. return this.estreeParseBigIntLiteral(this.state.value);
  792. case types.decimal:
  793. return this.estreeParseDecimalLiteral(this.state.value);
  794. case types._null:
  795. return this.estreeParseLiteral(null);
  796. case types._true:
  797. return this.estreeParseLiteral(true);
  798. case types._false:
  799. return this.estreeParseLiteral(false);
  800. default:
  801. return super.parseExprAtom(refExpressionErrors);
  802. }
  803. }
  804. parseLiteral(value, type, startPos, startLoc) {
  805. const node = super.parseLiteral(value, type, startPos, startLoc);
  806. node.raw = node.extra.raw;
  807. delete node.extra;
  808. return node;
  809. }
  810. parseFunctionBody(node, allowExpression, isMethod = false) {
  811. super.parseFunctionBody(node, allowExpression, isMethod);
  812. node.expression = node.body.type !== "BlockStatement";
  813. }
  814. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  815. let funcNode = this.startNode();
  816. funcNode.kind = node.kind;
  817. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  818. funcNode.type = "FunctionExpression";
  819. delete funcNode.kind;
  820. node.value = funcNode;
  821. type = type === "ClassMethod" ? "MethodDefinition" : type;
  822. return this.finishNode(node, type);
  823. }
  824. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  825. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  826. if (node) {
  827. node.type = "Property";
  828. if (node.kind === "method") node.kind = "init";
  829. node.shorthand = false;
  830. }
  831. return node;
  832. }
  833. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  834. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  835. if (node) {
  836. node.kind = "init";
  837. node.type = "Property";
  838. }
  839. return node;
  840. }
  841. toAssignable(node, isLHS = false) {
  842. if (node != null && this.isObjectProperty(node)) {
  843. this.toAssignable(node.value, isLHS);
  844. return node;
  845. }
  846. return super.toAssignable(node, isLHS);
  847. }
  848. toAssignableObjectExpressionProp(prop, ...args) {
  849. if (prop.kind === "get" || prop.kind === "set") {
  850. this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  851. } else if (prop.method) {
  852. this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  853. } else {
  854. super.toAssignableObjectExpressionProp(prop, ...args);
  855. }
  856. }
  857. finishCallExpression(node, optional) {
  858. super.finishCallExpression(node, optional);
  859. if (node.callee.type === "Import") {
  860. node.type = "ImportExpression";
  861. node.source = node.arguments[0];
  862. delete node.arguments;
  863. delete node.callee;
  864. }
  865. return node;
  866. }
  867. toReferencedArguments(node) {
  868. if (node.type === "ImportExpression") {
  869. return;
  870. }
  871. super.toReferencedArguments(node);
  872. }
  873. parseExport(node) {
  874. super.parseExport(node);
  875. switch (node.type) {
  876. case "ExportAllDeclaration":
  877. node.exported = null;
  878. break;
  879. case "ExportNamedDeclaration":
  880. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  881. node.type = "ExportAllDeclaration";
  882. node.exported = node.specifiers[0].exported;
  883. delete node.specifiers;
  884. }
  885. break;
  886. }
  887. return node;
  888. }
  889. parseSubscript(base, startPos, startLoc, noCalls, state) {
  890. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  891. if (state.optionalChainMember) {
  892. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  893. node.type = node.type.substring(8);
  894. }
  895. if (state.stop) {
  896. const chain = this.startNodeAtNode(node);
  897. chain.expression = node;
  898. return this.finishNode(chain, "ChainExpression");
  899. }
  900. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  901. node.optional = false;
  902. }
  903. return node;
  904. }
  905. hasPropertyAsPrivateName(node) {
  906. if (node.type === "ChainExpression") {
  907. node = node.expression;
  908. }
  909. return super.hasPropertyAsPrivateName(node);
  910. }
  911. isOptionalChain(node) {
  912. return node.type === "ChainExpression";
  913. }
  914. isObjectProperty(node) {
  915. return node.type === "Property" && node.kind === "init" && !node.method;
  916. }
  917. isObjectMethod(node) {
  918. return node.method || node.kind === "get" || node.kind === "set";
  919. }
  920. });
  921. class TokContext {
  922. constructor(token, isExpr, preserveSpace, override) {
  923. this.token = void 0;
  924. this.isExpr = void 0;
  925. this.preserveSpace = void 0;
  926. this.override = void 0;
  927. this.token = token;
  928. this.isExpr = !!isExpr;
  929. this.preserveSpace = !!preserveSpace;
  930. this.override = override;
  931. }
  932. }
  933. const types$1 = {
  934. braceStatement: new TokContext("{", false),
  935. braceExpression: new TokContext("{", true),
  936. recordExpression: new TokContext("#{", true),
  937. templateQuasi: new TokContext("${", false),
  938. parenStatement: new TokContext("(", false),
  939. parenExpression: new TokContext("(", true),
  940. template: new TokContext("`", true, true, p => p.readTmplToken()),
  941. functionExpression: new TokContext("function", true),
  942. functionStatement: new TokContext("function", false)
  943. };
  944. types.parenR.updateContext = types.braceR.updateContext = function () {
  945. if (this.state.context.length === 1) {
  946. this.state.exprAllowed = true;
  947. return;
  948. }
  949. let out = this.state.context.pop();
  950. if (out === types$1.braceStatement && this.curContext().token === "function") {
  951. out = this.state.context.pop();
  952. }
  953. this.state.exprAllowed = !out.isExpr;
  954. };
  955. types.name.updateContext = function (prevType) {
  956. let allowed = false;
  957. if (prevType !== types.dot) {
  958. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class) {
  959. allowed = true;
  960. }
  961. }
  962. this.state.exprAllowed = allowed;
  963. if (this.state.isIterator) {
  964. this.state.isIterator = false;
  965. }
  966. };
  967. types.braceL.updateContext = function (prevType) {
  968. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  969. this.state.exprAllowed = true;
  970. };
  971. types.dollarBraceL.updateContext = function () {
  972. this.state.context.push(types$1.templateQuasi);
  973. this.state.exprAllowed = true;
  974. };
  975. types.parenL.updateContext = function (prevType) {
  976. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  977. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  978. this.state.exprAllowed = true;
  979. };
  980. types.incDec.updateContext = function () {};
  981. types._function.updateContext = types._class.updateContext = function (prevType) {
  982. 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)) {
  983. this.state.context.push(types$1.functionExpression);
  984. } else {
  985. this.state.context.push(types$1.functionStatement);
  986. }
  987. this.state.exprAllowed = false;
  988. };
  989. types.backQuote.updateContext = function () {
  990. if (this.curContext() === types$1.template) {
  991. this.state.context.pop();
  992. } else {
  993. this.state.context.push(types$1.template);
  994. }
  995. this.state.exprAllowed = false;
  996. };
  997. types.braceHashL.updateContext = function () {
  998. this.state.context.push(types$1.recordExpression);
  999. this.state.exprAllowed = true;
  1000. };
  1001. 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";
  1002. 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";
  1003. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1004. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1005. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1006. 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];
  1007. 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];
  1008. function isInAstralSet(code, set) {
  1009. let pos = 0x10000;
  1010. for (let i = 0, length = set.length; i < length; i += 2) {
  1011. pos += set[i];
  1012. if (pos > code) return false;
  1013. pos += set[i + 1];
  1014. if (pos >= code) return true;
  1015. }
  1016. return false;
  1017. }
  1018. function isIdentifierStart(code) {
  1019. if (code < 65) return code === 36;
  1020. if (code <= 90) return true;
  1021. if (code < 97) return code === 95;
  1022. if (code <= 122) return true;
  1023. if (code <= 0xffff) {
  1024. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1025. }
  1026. return isInAstralSet(code, astralIdentifierStartCodes);
  1027. }
  1028. function isIdentifierChar(code) {
  1029. if (code < 48) return code === 36;
  1030. if (code < 58) return true;
  1031. if (code < 65) return false;
  1032. if (code <= 90) return true;
  1033. if (code < 97) return code === 95;
  1034. if (code <= 122) return true;
  1035. if (code <= 0xffff) {
  1036. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1037. }
  1038. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1039. }
  1040. const reservedWords = {
  1041. 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"],
  1042. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1043. strictBind: ["eval", "arguments"]
  1044. };
  1045. const keywords$1 = new Set(reservedWords.keyword);
  1046. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1047. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1048. function isReservedWord(word, inModule) {
  1049. return inModule && word === "await" || word === "enum";
  1050. }
  1051. function isStrictReservedWord(word, inModule) {
  1052. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1053. }
  1054. function isStrictBindOnlyReservedWord(word) {
  1055. return reservedWordsStrictBindSet.has(word);
  1056. }
  1057. function isStrictBindReservedWord(word, inModule) {
  1058. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1059. }
  1060. function isKeyword(word) {
  1061. return keywords$1.has(word);
  1062. }
  1063. const keywordRelationalOperator = /^in(stanceof)?$/;
  1064. function isIteratorStart(current, next) {
  1065. return current === 64 && next === 64;
  1066. }
  1067. const SCOPE_OTHER = 0b00000000,
  1068. SCOPE_PROGRAM = 0b00000001,
  1069. SCOPE_FUNCTION = 0b00000010,
  1070. SCOPE_ARROW = 0b00000100,
  1071. SCOPE_SIMPLE_CATCH = 0b00001000,
  1072. SCOPE_SUPER = 0b00010000,
  1073. SCOPE_DIRECT_SUPER = 0b00100000,
  1074. SCOPE_CLASS = 0b01000000,
  1075. SCOPE_TS_MODULE = 0b10000000,
  1076. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  1077. const BIND_KIND_VALUE = 0b00000000001,
  1078. BIND_KIND_TYPE = 0b00000000010,
  1079. BIND_SCOPE_VAR = 0b00000000100,
  1080. BIND_SCOPE_LEXICAL = 0b00000001000,
  1081. BIND_SCOPE_FUNCTION = 0b00000010000,
  1082. BIND_FLAGS_NONE = 0b00001000000,
  1083. BIND_FLAGS_CLASS = 0b00010000000,
  1084. BIND_FLAGS_TS_ENUM = 0b00100000000,
  1085. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  1086. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  1087. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  1088. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  1089. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  1090. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  1091. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  1092. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  1093. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  1094. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  1095. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  1096. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  1097. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  1098. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  1099. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  1100. CLASS_ELEMENT_KIND_GETTER = 0b010,
  1101. CLASS_ELEMENT_KIND_SETTER = 0b001,
  1102. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  1103. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  1104. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  1105. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  1106. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  1107. CLASS_ELEMENT_OTHER = 0;
  1108. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1109. const FlowErrors = Object.freeze({
  1110. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1111. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",
  1112. AssignReservedType: "Cannot overwrite reserved type %0",
  1113. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1114. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1115. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1116. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1117. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1118. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1119. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1120. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1121. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1122. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1123. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1124. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1125. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1126. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1127. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",
  1128. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1129. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1130. InexactVariance: "Explicit inexact syntax cannot have variance",
  1131. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1132. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1133. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1134. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1135. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1136. SpreadVariance: "Spread properties cannot have variance",
  1137. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1138. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1139. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1140. UnexpectedReservedType: "Unexpected reserved type %0",
  1141. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1142. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1143. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1144. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1145. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1146. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  1147. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1148. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1149. UnterminatedFlowComment: "Unterminated flow-comment"
  1150. });
  1151. function isEsModuleType(bodyElement) {
  1152. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1153. }
  1154. function hasTypeImportKind(node) {
  1155. return node.importKind === "type" || node.importKind === "typeof";
  1156. }
  1157. function isMaybeDefaultImport(state) {
  1158. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1159. }
  1160. const exportSuggestions = {
  1161. const: "declare export var",
  1162. let: "declare export var",
  1163. type: "export type",
  1164. interface: "export interface"
  1165. };
  1166. function partition(list, test) {
  1167. const list1 = [];
  1168. const list2 = [];
  1169. for (let i = 0; i < list.length; i++) {
  1170. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1171. }
  1172. return [list1, list2];
  1173. }
  1174. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1175. var flow = (superClass => {
  1176. var _temp;
  1177. return _temp = class extends superClass {
  1178. constructor(options, input) {
  1179. super(options, input);
  1180. this.flowPragma = void 0;
  1181. this.flowPragma = undefined;
  1182. }
  1183. shouldParseTypes() {
  1184. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1185. }
  1186. shouldParseEnums() {
  1187. return !!this.getPluginOption("flow", "enums");
  1188. }
  1189. finishToken(type, val) {
  1190. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1191. if (this.flowPragma === undefined) {
  1192. this.flowPragma = null;
  1193. }
  1194. }
  1195. return super.finishToken(type, val);
  1196. }
  1197. addComment(comment) {
  1198. if (this.flowPragma === undefined) {
  1199. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1200. if (!matches) ; else if (matches[1] === "flow") {
  1201. this.flowPragma = "flow";
  1202. } else if (matches[1] === "noflow") {
  1203. this.flowPragma = "noflow";
  1204. } else {
  1205. throw new Error("Unexpected flow pragma");
  1206. }
  1207. }
  1208. return super.addComment(comment);
  1209. }
  1210. flowParseTypeInitialiser(tok) {
  1211. const oldInType = this.state.inType;
  1212. this.state.inType = true;
  1213. this.expect(tok || types.colon);
  1214. const type = this.flowParseType();
  1215. this.state.inType = oldInType;
  1216. return type;
  1217. }
  1218. flowParsePredicate() {
  1219. const node = this.startNode();
  1220. const moduloLoc = this.state.startLoc;
  1221. const moduloPos = this.state.start;
  1222. this.expect(types.modulo);
  1223. const checksLoc = this.state.startLoc;
  1224. this.expectContextual("checks");
  1225. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1226. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1227. }
  1228. if (this.eat(types.parenL)) {
  1229. node.value = this.parseExpression();
  1230. this.expect(types.parenR);
  1231. return this.finishNode(node, "DeclaredPredicate");
  1232. } else {
  1233. return this.finishNode(node, "InferredPredicate");
  1234. }
  1235. }
  1236. flowParseTypeAndPredicateInitialiser() {
  1237. const oldInType = this.state.inType;
  1238. this.state.inType = true;
  1239. this.expect(types.colon);
  1240. let type = null;
  1241. let predicate = null;
  1242. if (this.match(types.modulo)) {
  1243. this.state.inType = oldInType;
  1244. predicate = this.flowParsePredicate();
  1245. } else {
  1246. type = this.flowParseType();
  1247. this.state.inType = oldInType;
  1248. if (this.match(types.modulo)) {
  1249. predicate = this.flowParsePredicate();
  1250. }
  1251. }
  1252. return [type, predicate];
  1253. }
  1254. flowParseDeclareClass(node) {
  1255. this.next();
  1256. this.flowParseInterfaceish(node, true);
  1257. return this.finishNode(node, "DeclareClass");
  1258. }
  1259. flowParseDeclareFunction(node) {
  1260. this.next();
  1261. const id = node.id = this.parseIdentifier();
  1262. const typeNode = this.startNode();
  1263. const typeContainer = this.startNode();
  1264. if (this.isRelational("<")) {
  1265. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1266. } else {
  1267. typeNode.typeParameters = null;
  1268. }
  1269. this.expect(types.parenL);
  1270. const tmp = this.flowParseFunctionTypeParams();
  1271. typeNode.params = tmp.params;
  1272. typeNode.rest = tmp.rest;
  1273. this.expect(types.parenR);
  1274. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1275. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1276. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1277. this.resetEndLocation(id);
  1278. this.semicolon();
  1279. return this.finishNode(node, "DeclareFunction");
  1280. }
  1281. flowParseDeclare(node, insideModule) {
  1282. if (this.match(types._class)) {
  1283. return this.flowParseDeclareClass(node);
  1284. } else if (this.match(types._function)) {
  1285. return this.flowParseDeclareFunction(node);
  1286. } else if (this.match(types._var)) {
  1287. return this.flowParseDeclareVariable(node);
  1288. } else if (this.eatContextual("module")) {
  1289. if (this.match(types.dot)) {
  1290. return this.flowParseDeclareModuleExports(node);
  1291. } else {
  1292. if (insideModule) {
  1293. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1294. }
  1295. return this.flowParseDeclareModule(node);
  1296. }
  1297. } else if (this.isContextual("type")) {
  1298. return this.flowParseDeclareTypeAlias(node);
  1299. } else if (this.isContextual("opaque")) {
  1300. return this.flowParseDeclareOpaqueType(node);
  1301. } else if (this.isContextual("interface")) {
  1302. return this.flowParseDeclareInterface(node);
  1303. } else if (this.match(types._export)) {
  1304. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1305. } else {
  1306. throw this.unexpected();
  1307. }
  1308. }
  1309. flowParseDeclareVariable(node) {
  1310. this.next();
  1311. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1312. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1313. this.semicolon();
  1314. return this.finishNode(node, "DeclareVariable");
  1315. }
  1316. flowParseDeclareModule(node) {
  1317. this.scope.enter(SCOPE_OTHER);
  1318. if (this.match(types.string)) {
  1319. node.id = this.parseExprAtom();
  1320. } else {
  1321. node.id = this.parseIdentifier();
  1322. }
  1323. const bodyNode = node.body = this.startNode();
  1324. const body = bodyNode.body = [];
  1325. this.expect(types.braceL);
  1326. while (!this.match(types.braceR)) {
  1327. let bodyNode = this.startNode();
  1328. if (this.match(types._import)) {
  1329. this.next();
  1330. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1331. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1332. }
  1333. this.parseImport(bodyNode);
  1334. } else {
  1335. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1336. bodyNode = this.flowParseDeclare(bodyNode, true);
  1337. }
  1338. body.push(bodyNode);
  1339. }
  1340. this.scope.exit();
  1341. this.expect(types.braceR);
  1342. this.finishNode(bodyNode, "BlockStatement");
  1343. let kind = null;
  1344. let hasModuleExport = false;
  1345. body.forEach(bodyElement => {
  1346. if (isEsModuleType(bodyElement)) {
  1347. if (kind === "CommonJS") {
  1348. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1349. }
  1350. kind = "ES";
  1351. } else if (bodyElement.type === "DeclareModuleExports") {
  1352. if (hasModuleExport) {
  1353. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1354. }
  1355. if (kind === "ES") {
  1356. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1357. }
  1358. kind = "CommonJS";
  1359. hasModuleExport = true;
  1360. }
  1361. });
  1362. node.kind = kind || "CommonJS";
  1363. return this.finishNode(node, "DeclareModule");
  1364. }
  1365. flowParseDeclareExportDeclaration(node, insideModule) {
  1366. this.expect(types._export);
  1367. if (this.eat(types._default)) {
  1368. if (this.match(types._function) || this.match(types._class)) {
  1369. node.declaration = this.flowParseDeclare(this.startNode());
  1370. } else {
  1371. node.declaration = this.flowParseType();
  1372. this.semicolon();
  1373. }
  1374. node.default = true;
  1375. return this.finishNode(node, "DeclareExportDeclaration");
  1376. } else {
  1377. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1378. const label = this.state.value;
  1379. const suggestion = exportSuggestions[label];
  1380. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1381. }
  1382. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1383. node.declaration = this.flowParseDeclare(this.startNode());
  1384. node.default = false;
  1385. return this.finishNode(node, "DeclareExportDeclaration");
  1386. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1387. node = this.parseExport(node);
  1388. if (node.type === "ExportNamedDeclaration") {
  1389. node.type = "ExportDeclaration";
  1390. node.default = false;
  1391. delete node.exportKind;
  1392. }
  1393. node.type = "Declare" + node.type;
  1394. return node;
  1395. }
  1396. }
  1397. throw this.unexpected();
  1398. }
  1399. flowParseDeclareModuleExports(node) {
  1400. this.next();
  1401. this.expectContextual("exports");
  1402. node.typeAnnotation = this.flowParseTypeAnnotation();
  1403. this.semicolon();
  1404. return this.finishNode(node, "DeclareModuleExports");
  1405. }
  1406. flowParseDeclareTypeAlias(node) {
  1407. this.next();
  1408. this.flowParseTypeAlias(node);
  1409. node.type = "DeclareTypeAlias";
  1410. return node;
  1411. }
  1412. flowParseDeclareOpaqueType(node) {
  1413. this.next();
  1414. this.flowParseOpaqueType(node, true);
  1415. node.type = "DeclareOpaqueType";
  1416. return node;
  1417. }
  1418. flowParseDeclareInterface(node) {
  1419. this.next();
  1420. this.flowParseInterfaceish(node);
  1421. return this.finishNode(node, "DeclareInterface");
  1422. }
  1423. flowParseInterfaceish(node, isClass = false) {
  1424. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1425. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1426. if (this.isRelational("<")) {
  1427. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1428. } else {
  1429. node.typeParameters = null;
  1430. }
  1431. node.extends = [];
  1432. node.implements = [];
  1433. node.mixins = [];
  1434. if (this.eat(types._extends)) {
  1435. do {
  1436. node.extends.push(this.flowParseInterfaceExtends());
  1437. } while (!isClass && this.eat(types.comma));
  1438. }
  1439. if (this.isContextual("mixins")) {
  1440. this.next();
  1441. do {
  1442. node.mixins.push(this.flowParseInterfaceExtends());
  1443. } while (this.eat(types.comma));
  1444. }
  1445. if (this.isContextual("implements")) {
  1446. this.next();
  1447. do {
  1448. node.implements.push(this.flowParseInterfaceExtends());
  1449. } while (this.eat(types.comma));
  1450. }
  1451. node.body = this.flowParseObjectType({
  1452. allowStatic: isClass,
  1453. allowExact: false,
  1454. allowSpread: false,
  1455. allowProto: isClass,
  1456. allowInexact: false
  1457. });
  1458. }
  1459. flowParseInterfaceExtends() {
  1460. const node = this.startNode();
  1461. node.id = this.flowParseQualifiedTypeIdentifier();
  1462. if (this.isRelational("<")) {
  1463. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1464. } else {
  1465. node.typeParameters = null;
  1466. }
  1467. return this.finishNode(node, "InterfaceExtends");
  1468. }
  1469. flowParseInterface(node) {
  1470. this.flowParseInterfaceish(node);
  1471. return this.finishNode(node, "InterfaceDeclaration");
  1472. }
  1473. checkNotUnderscore(word) {
  1474. if (word === "_") {
  1475. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1476. }
  1477. }
  1478. checkReservedType(word, startLoc, declaration) {
  1479. if (!reservedTypes.has(word)) return;
  1480. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1481. }
  1482. flowParseRestrictedIdentifier(liberal, declaration) {
  1483. this.checkReservedType(this.state.value, this.state.start, declaration);
  1484. return this.parseIdentifier(liberal);
  1485. }
  1486. flowParseTypeAlias(node) {
  1487. node.id = this.flowParseRestrictedIdentifier(false, true);
  1488. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1489. if (this.isRelational("<")) {
  1490. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1491. } else {
  1492. node.typeParameters = null;
  1493. }
  1494. node.right = this.flowParseTypeInitialiser(types.eq);
  1495. this.semicolon();
  1496. return this.finishNode(node, "TypeAlias");
  1497. }
  1498. flowParseOpaqueType(node, declare) {
  1499. this.expectContextual("type");
  1500. node.id = this.flowParseRestrictedIdentifier(true, true);
  1501. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1502. if (this.isRelational("<")) {
  1503. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1504. } else {
  1505. node.typeParameters = null;
  1506. }
  1507. node.supertype = null;
  1508. if (this.match(types.colon)) {
  1509. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1510. }
  1511. node.impltype = null;
  1512. if (!declare) {
  1513. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1514. }
  1515. this.semicolon();
  1516. return this.finishNode(node, "OpaqueType");
  1517. }
  1518. flowParseTypeParameter(requireDefault = false) {
  1519. const nodeStart = this.state.start;
  1520. const node = this.startNode();
  1521. const variance = this.flowParseVariance();
  1522. const ident = this.flowParseTypeAnnotatableIdentifier();
  1523. node.name = ident.name;
  1524. node.variance = variance;
  1525. node.bound = ident.typeAnnotation;
  1526. if (this.match(types.eq)) {
  1527. this.eat(types.eq);
  1528. node.default = this.flowParseType();
  1529. } else {
  1530. if (requireDefault) {
  1531. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1532. }
  1533. }
  1534. return this.finishNode(node, "TypeParameter");
  1535. }
  1536. flowParseTypeParameterDeclaration() {
  1537. const oldInType = this.state.inType;
  1538. const node = this.startNode();
  1539. node.params = [];
  1540. this.state.inType = true;
  1541. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1542. this.next();
  1543. } else {
  1544. this.unexpected();
  1545. }
  1546. let defaultRequired = false;
  1547. do {
  1548. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1549. node.params.push(typeParameter);
  1550. if (typeParameter.default) {
  1551. defaultRequired = true;
  1552. }
  1553. if (!this.isRelational(">")) {
  1554. this.expect(types.comma);
  1555. }
  1556. } while (!this.isRelational(">"));
  1557. this.expectRelational(">");
  1558. this.state.inType = oldInType;
  1559. return this.finishNode(node, "TypeParameterDeclaration");
  1560. }
  1561. flowParseTypeParameterInstantiation() {
  1562. const node = this.startNode();
  1563. const oldInType = this.state.inType;
  1564. node.params = [];
  1565. this.state.inType = true;
  1566. this.expectRelational("<");
  1567. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1568. this.state.noAnonFunctionType = false;
  1569. while (!this.isRelational(">")) {
  1570. node.params.push(this.flowParseType());
  1571. if (!this.isRelational(">")) {
  1572. this.expect(types.comma);
  1573. }
  1574. }
  1575. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1576. this.expectRelational(">");
  1577. this.state.inType = oldInType;
  1578. return this.finishNode(node, "TypeParameterInstantiation");
  1579. }
  1580. flowParseTypeParameterInstantiationCallOrNew() {
  1581. const node = this.startNode();
  1582. const oldInType = this.state.inType;
  1583. node.params = [];
  1584. this.state.inType = true;
  1585. this.expectRelational("<");
  1586. while (!this.isRelational(">")) {
  1587. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1588. if (!this.isRelational(">")) {
  1589. this.expect(types.comma);
  1590. }
  1591. }
  1592. this.expectRelational(">");
  1593. this.state.inType = oldInType;
  1594. return this.finishNode(node, "TypeParameterInstantiation");
  1595. }
  1596. flowParseInterfaceType() {
  1597. const node = this.startNode();
  1598. this.expectContextual("interface");
  1599. node.extends = [];
  1600. if (this.eat(types._extends)) {
  1601. do {
  1602. node.extends.push(this.flowParseInterfaceExtends());
  1603. } while (this.eat(types.comma));
  1604. }
  1605. node.body = this.flowParseObjectType({
  1606. allowStatic: false,
  1607. allowExact: false,
  1608. allowSpread: false,
  1609. allowProto: false,
  1610. allowInexact: false
  1611. });
  1612. return this.finishNode(node, "InterfaceTypeAnnotation");
  1613. }
  1614. flowParseObjectPropertyKey() {
  1615. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1616. }
  1617. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1618. node.static = isStatic;
  1619. if (this.lookahead().type === types.colon) {
  1620. node.id = this.flowParseObjectPropertyKey();
  1621. node.key = this.flowParseTypeInitialiser();
  1622. } else {
  1623. node.id = null;
  1624. node.key = this.flowParseType();
  1625. }
  1626. this.expect(types.bracketR);
  1627. node.value = this.flowParseTypeInitialiser();
  1628. node.variance = variance;
  1629. return this.finishNode(node, "ObjectTypeIndexer");
  1630. }
  1631. flowParseObjectTypeInternalSlot(node, isStatic) {
  1632. node.static = isStatic;
  1633. node.id = this.flowParseObjectPropertyKey();
  1634. this.expect(types.bracketR);
  1635. this.expect(types.bracketR);
  1636. if (this.isRelational("<") || this.match(types.parenL)) {
  1637. node.method = true;
  1638. node.optional = false;
  1639. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1640. } else {
  1641. node.method = false;
  1642. if (this.eat(types.question)) {
  1643. node.optional = true;
  1644. }
  1645. node.value = this.flowParseTypeInitialiser();
  1646. }
  1647. return this.finishNode(node, "ObjectTypeInternalSlot");
  1648. }
  1649. flowParseObjectTypeMethodish(node) {
  1650. node.params = [];
  1651. node.rest = null;
  1652. node.typeParameters = null;
  1653. if (this.isRelational("<")) {
  1654. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1655. }
  1656. this.expect(types.parenL);
  1657. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1658. node.params.push(this.flowParseFunctionTypeParam());
  1659. if (!this.match(types.parenR)) {
  1660. this.expect(types.comma);
  1661. }
  1662. }
  1663. if (this.eat(types.ellipsis)) {
  1664. node.rest = this.flowParseFunctionTypeParam();
  1665. }
  1666. this.expect(types.parenR);
  1667. node.returnType = this.flowParseTypeInitialiser();
  1668. return this.finishNode(node, "FunctionTypeAnnotation");
  1669. }
  1670. flowParseObjectTypeCallProperty(node, isStatic) {
  1671. const valueNode = this.startNode();
  1672. node.static = isStatic;
  1673. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1674. return this.finishNode(node, "ObjectTypeCallProperty");
  1675. }
  1676. flowParseObjectType({
  1677. allowStatic,
  1678. allowExact,
  1679. allowSpread,
  1680. allowProto,
  1681. allowInexact
  1682. }) {
  1683. const oldInType = this.state.inType;
  1684. this.state.inType = true;
  1685. const nodeStart = this.startNode();
  1686. nodeStart.callProperties = [];
  1687. nodeStart.properties = [];
  1688. nodeStart.indexers = [];
  1689. nodeStart.internalSlots = [];
  1690. let endDelim;
  1691. let exact;
  1692. let inexact = false;
  1693. if (allowExact && this.match(types.braceBarL)) {
  1694. this.expect(types.braceBarL);
  1695. endDelim = types.braceBarR;
  1696. exact = true;
  1697. } else {
  1698. this.expect(types.braceL);
  1699. endDelim = types.braceR;
  1700. exact = false;
  1701. }
  1702. nodeStart.exact = exact;
  1703. while (!this.match(endDelim)) {
  1704. let isStatic = false;
  1705. let protoStart = null;
  1706. let inexactStart = null;
  1707. const node = this.startNode();
  1708. if (allowProto && this.isContextual("proto")) {
  1709. const lookahead = this.lookahead();
  1710. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1711. this.next();
  1712. protoStart = this.state.start;
  1713. allowStatic = false;
  1714. }
  1715. }
  1716. if (allowStatic && this.isContextual("static")) {
  1717. const lookahead = this.lookahead();
  1718. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1719. this.next();
  1720. isStatic = true;
  1721. }
  1722. }
  1723. const variance = this.flowParseVariance();
  1724. if (this.eat(types.bracketL)) {
  1725. if (protoStart != null) {
  1726. this.unexpected(protoStart);
  1727. }
  1728. if (this.eat(types.bracketL)) {
  1729. if (variance) {
  1730. this.unexpected(variance.start);
  1731. }
  1732. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1733. } else {
  1734. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1735. }
  1736. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1737. if (protoStart != null) {
  1738. this.unexpected(protoStart);
  1739. }
  1740. if (variance) {
  1741. this.unexpected(variance.start);
  1742. }
  1743. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1744. } else {
  1745. let kind = "init";
  1746. if (this.isContextual("get") || this.isContextual("set")) {
  1747. const lookahead = this.lookahead();
  1748. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1749. kind = this.state.value;
  1750. this.next();
  1751. }
  1752. }
  1753. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1754. if (propOrInexact === null) {
  1755. inexact = true;
  1756. inexactStart = this.state.lastTokStart;
  1757. } else {
  1758. nodeStart.properties.push(propOrInexact);
  1759. }
  1760. }
  1761. this.flowObjectTypeSemicolon();
  1762. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1763. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  1764. }
  1765. }
  1766. this.expect(endDelim);
  1767. if (allowSpread) {
  1768. nodeStart.inexact = inexact;
  1769. }
  1770. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1771. this.state.inType = oldInType;
  1772. return out;
  1773. }
  1774. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1775. if (this.eat(types.ellipsis)) {
  1776. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1777. if (isInexactToken) {
  1778. if (!allowSpread) {
  1779. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  1780. } else if (!allowInexact) {
  1781. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  1782. }
  1783. if (variance) {
  1784. this.raise(variance.start, FlowErrors.InexactVariance);
  1785. }
  1786. return null;
  1787. }
  1788. if (!allowSpread) {
  1789. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  1790. }
  1791. if (protoStart != null) {
  1792. this.unexpected(protoStart);
  1793. }
  1794. if (variance) {
  1795. this.raise(variance.start, FlowErrors.SpreadVariance);
  1796. }
  1797. node.argument = this.flowParseType();
  1798. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1799. } else {
  1800. node.key = this.flowParseObjectPropertyKey();
  1801. node.static = isStatic;
  1802. node.proto = protoStart != null;
  1803. node.kind = kind;
  1804. let optional = false;
  1805. if (this.isRelational("<") || this.match(types.parenL)) {
  1806. node.method = true;
  1807. if (protoStart != null) {
  1808. this.unexpected(protoStart);
  1809. }
  1810. if (variance) {
  1811. this.unexpected(variance.start);
  1812. }
  1813. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1814. if (kind === "get" || kind === "set") {
  1815. this.flowCheckGetterSetterParams(node);
  1816. }
  1817. } else {
  1818. if (kind !== "init") this.unexpected();
  1819. node.method = false;
  1820. if (this.eat(types.question)) {
  1821. optional = true;
  1822. }
  1823. node.value = this.flowParseTypeInitialiser();
  1824. node.variance = variance;
  1825. }
  1826. node.optional = optional;
  1827. return this.finishNode(node, "ObjectTypeProperty");
  1828. }
  1829. }
  1830. flowCheckGetterSetterParams(property) {
  1831. const paramCount = property.kind === "get" ? 0 : 1;
  1832. const start = property.start;
  1833. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1834. if (length !== paramCount) {
  1835. if (property.kind === "get") {
  1836. this.raise(start, ErrorMessages.BadGetterArity);
  1837. } else {
  1838. this.raise(start, ErrorMessages.BadSetterArity);
  1839. }
  1840. }
  1841. if (property.kind === "set" && property.value.rest) {
  1842. this.raise(start, ErrorMessages.BadSetterRestParameter);
  1843. }
  1844. }
  1845. flowObjectTypeSemicolon() {
  1846. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1847. this.unexpected();
  1848. }
  1849. }
  1850. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1851. startPos = startPos || this.state.start;
  1852. startLoc = startLoc || this.state.startLoc;
  1853. let node = id || this.flowParseRestrictedIdentifier(true);
  1854. while (this.eat(types.dot)) {
  1855. const node2 = this.startNodeAt(startPos, startLoc);
  1856. node2.qualification = node;
  1857. node2.id = this.flowParseRestrictedIdentifier(true);
  1858. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1859. }
  1860. return node;
  1861. }
  1862. flowParseGenericType(startPos, startLoc, id) {
  1863. const node = this.startNodeAt(startPos, startLoc);
  1864. node.typeParameters = null;
  1865. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1866. if (this.isRelational("<")) {
  1867. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1868. }
  1869. return this.finishNode(node, "GenericTypeAnnotation");
  1870. }
  1871. flowParseTypeofType() {
  1872. const node = this.startNode();
  1873. this.expect(types._typeof);
  1874. node.argument = this.flowParsePrimaryType();
  1875. return this.finishNode(node, "TypeofTypeAnnotation");
  1876. }
  1877. flowParseTupleType() {
  1878. const node = this.startNode();
  1879. node.types = [];
  1880. this.expect(types.bracketL);
  1881. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1882. node.types.push(this.flowParseType());
  1883. if (this.match(types.bracketR)) break;
  1884. this.expect(types.comma);
  1885. }
  1886. this.expect(types.bracketR);
  1887. return this.finishNode(node, "TupleTypeAnnotation");
  1888. }
  1889. flowParseFunctionTypeParam() {
  1890. let name = null;
  1891. let optional = false;
  1892. let typeAnnotation = null;
  1893. const node = this.startNode();
  1894. const lh = this.lookahead();
  1895. if (lh.type === types.colon || lh.type === types.question) {
  1896. name = this.parseIdentifier();
  1897. if (this.eat(types.question)) {
  1898. optional = true;
  1899. }
  1900. typeAnnotation = this.flowParseTypeInitialiser();
  1901. } else {
  1902. typeAnnotation = this.flowParseType();
  1903. }
  1904. node.name = name;
  1905. node.optional = optional;
  1906. node.typeAnnotation = typeAnnotation;
  1907. return this.finishNode(node, "FunctionTypeParam");
  1908. }
  1909. reinterpretTypeAsFunctionTypeParam(type) {
  1910. const node = this.startNodeAt(type.start, type.loc.start);
  1911. node.name = null;
  1912. node.optional = false;
  1913. node.typeAnnotation = type;
  1914. return this.finishNode(node, "FunctionTypeParam");
  1915. }
  1916. flowParseFunctionTypeParams(params = []) {
  1917. let rest = null;
  1918. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1919. params.push(this.flowParseFunctionTypeParam());
  1920. if (!this.match(types.parenR)) {
  1921. this.expect(types.comma);
  1922. }
  1923. }
  1924. if (this.eat(types.ellipsis)) {
  1925. rest = this.flowParseFunctionTypeParam();
  1926. }
  1927. return {
  1928. params,
  1929. rest
  1930. };
  1931. }
  1932. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1933. switch (id.name) {
  1934. case "any":
  1935. return this.finishNode(node, "AnyTypeAnnotation");
  1936. case "bool":
  1937. case "boolean":
  1938. return this.finishNode(node, "BooleanTypeAnnotation");
  1939. case "mixed":
  1940. return this.finishNode(node, "MixedTypeAnnotation");
  1941. case "empty":
  1942. return this.finishNode(node, "EmptyTypeAnnotation");
  1943. case "number":
  1944. return this.finishNode(node, "NumberTypeAnnotation");
  1945. case "string":
  1946. return this.finishNode(node, "StringTypeAnnotation");
  1947. case "symbol":
  1948. return this.finishNode(node, "SymbolTypeAnnotation");
  1949. default:
  1950. this.checkNotUnderscore(id.name);
  1951. return this.flowParseGenericType(startPos, startLoc, id);
  1952. }
  1953. }
  1954. flowParsePrimaryType() {
  1955. const startPos = this.state.start;
  1956. const startLoc = this.state.startLoc;
  1957. const node = this.startNode();
  1958. let tmp;
  1959. let type;
  1960. let isGroupedType = false;
  1961. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1962. switch (this.state.type) {
  1963. case types.name:
  1964. if (this.isContextual("interface")) {
  1965. return this.flowParseInterfaceType();
  1966. }
  1967. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1968. case types.braceL:
  1969. return this.flowParseObjectType({
  1970. allowStatic: false,
  1971. allowExact: false,
  1972. allowSpread: true,
  1973. allowProto: false,
  1974. allowInexact: true
  1975. });
  1976. case types.braceBarL:
  1977. return this.flowParseObjectType({
  1978. allowStatic: false,
  1979. allowExact: true,
  1980. allowSpread: true,
  1981. allowProto: false,
  1982. allowInexact: false
  1983. });
  1984. case types.bracketL:
  1985. this.state.noAnonFunctionType = false;
  1986. type = this.flowParseTupleType();
  1987. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1988. return type;
  1989. case types.relational:
  1990. if (this.state.value === "<") {
  1991. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1992. this.expect(types.parenL);
  1993. tmp = this.flowParseFunctionTypeParams();
  1994. node.params = tmp.params;
  1995. node.rest = tmp.rest;
  1996. this.expect(types.parenR);
  1997. this.expect(types.arrow);
  1998. node.returnType = this.flowParseType();
  1999. return this.finishNode(node, "FunctionTypeAnnotation");
  2000. }
  2001. break;
  2002. case types.parenL:
  2003. this.next();
  2004. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  2005. if (this.match(types.name)) {
  2006. const token = this.lookahead().type;
  2007. isGroupedType = token !== types.question && token !== types.colon;
  2008. } else {
  2009. isGroupedType = true;
  2010. }
  2011. }
  2012. if (isGroupedType) {
  2013. this.state.noAnonFunctionType = false;
  2014. type = this.flowParseType();
  2015. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2016. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  2017. this.expect(types.parenR);
  2018. return type;
  2019. } else {
  2020. this.eat(types.comma);
  2021. }
  2022. }
  2023. if (type) {
  2024. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  2025. } else {
  2026. tmp = this.flowParseFunctionTypeParams();
  2027. }
  2028. node.params = tmp.params;
  2029. node.rest = tmp.rest;
  2030. this.expect(types.parenR);
  2031. this.expect(types.arrow);
  2032. node.returnType = this.flowParseType();
  2033. node.typeParameters = null;
  2034. return this.finishNode(node, "FunctionTypeAnnotation");
  2035. case types.string:
  2036. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  2037. case types._true:
  2038. case types._false:
  2039. node.value = this.match(types._true);
  2040. this.next();
  2041. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  2042. case types.plusMin:
  2043. if (this.state.value === "-") {
  2044. this.next();
  2045. if (this.match(types.num)) {
  2046. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  2047. }
  2048. if (this.match(types.bigint)) {
  2049. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  2050. }
  2051. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  2052. }
  2053. throw this.unexpected();
  2054. case types.num:
  2055. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  2056. case types.bigint:
  2057. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  2058. case types._void:
  2059. this.next();
  2060. return this.finishNode(node, "VoidTypeAnnotation");
  2061. case types._null:
  2062. this.next();
  2063. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2064. case types._this:
  2065. this.next();
  2066. return this.finishNode(node, "ThisTypeAnnotation");
  2067. case types.star:
  2068. this.next();
  2069. return this.finishNode(node, "ExistsTypeAnnotation");
  2070. default:
  2071. if (this.state.type.keyword === "typeof") {
  2072. return this.flowParseTypeofType();
  2073. } else if (this.state.type.keyword) {
  2074. const label = this.state.type.label;
  2075. this.next();
  2076. return super.createIdentifier(node, label);
  2077. }
  2078. }
  2079. throw this.unexpected();
  2080. }
  2081. flowParsePostfixType() {
  2082. const startPos = this.state.start,
  2083. startLoc = this.state.startLoc;
  2084. let type = this.flowParsePrimaryType();
  2085. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2086. const node = this.startNodeAt(startPos, startLoc);
  2087. node.elementType = type;
  2088. this.expect(types.bracketL);
  2089. this.expect(types.bracketR);
  2090. type = this.finishNode(node, "ArrayTypeAnnotation");
  2091. }
  2092. return type;
  2093. }
  2094. flowParsePrefixType() {
  2095. const node = this.startNode();
  2096. if (this.eat(types.question)) {
  2097. node.typeAnnotation = this.flowParsePrefixType();
  2098. return this.finishNode(node, "NullableTypeAnnotation");
  2099. } else {
  2100. return this.flowParsePostfixType();
  2101. }
  2102. }
  2103. flowParseAnonFunctionWithoutParens() {
  2104. const param = this.flowParsePrefixType();
  2105. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2106. const node = this.startNodeAt(param.start, param.loc.start);
  2107. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2108. node.rest = null;
  2109. node.returnType = this.flowParseType();
  2110. node.typeParameters = null;
  2111. return this.finishNode(node, "FunctionTypeAnnotation");
  2112. }
  2113. return param;
  2114. }
  2115. flowParseIntersectionType() {
  2116. const node = this.startNode();
  2117. this.eat(types.bitwiseAND);
  2118. const type = this.flowParseAnonFunctionWithoutParens();
  2119. node.types = [type];
  2120. while (this.eat(types.bitwiseAND)) {
  2121. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2122. }
  2123. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2124. }
  2125. flowParseUnionType() {
  2126. const node = this.startNode();
  2127. this.eat(types.bitwiseOR);
  2128. const type = this.flowParseIntersectionType();
  2129. node.types = [type];
  2130. while (this.eat(types.bitwiseOR)) {
  2131. node.types.push(this.flowParseIntersectionType());
  2132. }
  2133. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2134. }
  2135. flowParseType() {
  2136. const oldInType = this.state.inType;
  2137. this.state.inType = true;
  2138. const type = this.flowParseUnionType();
  2139. this.state.inType = oldInType;
  2140. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2141. return type;
  2142. }
  2143. flowParseTypeOrImplicitInstantiation() {
  2144. if (this.state.type === types.name && this.state.value === "_") {
  2145. const startPos = this.state.start;
  2146. const startLoc = this.state.startLoc;
  2147. const node = this.parseIdentifier();
  2148. return this.flowParseGenericType(startPos, startLoc, node);
  2149. } else {
  2150. return this.flowParseType();
  2151. }
  2152. }
  2153. flowParseTypeAnnotation() {
  2154. const node = this.startNode();
  2155. node.typeAnnotation = this.flowParseTypeInitialiser();
  2156. return this.finishNode(node, "TypeAnnotation");
  2157. }
  2158. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2159. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2160. if (this.match(types.colon)) {
  2161. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2162. this.resetEndLocation(ident);
  2163. }
  2164. return ident;
  2165. }
  2166. typeCastToParameter(node) {
  2167. node.expression.typeAnnotation = node.typeAnnotation;
  2168. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2169. return node.expression;
  2170. }
  2171. flowParseVariance() {
  2172. let variance = null;
  2173. if (this.match(types.plusMin)) {
  2174. variance = this.startNode();
  2175. if (this.state.value === "+") {
  2176. variance.kind = "plus";
  2177. } else {
  2178. variance.kind = "minus";
  2179. }
  2180. this.next();
  2181. this.finishNode(variance, "Variance");
  2182. }
  2183. return variance;
  2184. }
  2185. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2186. if (allowExpressionBody) {
  2187. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2188. }
  2189. return super.parseFunctionBody(node, false, isMethod);
  2190. }
  2191. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2192. if (this.match(types.colon)) {
  2193. const typeNode = this.startNode();
  2194. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2195. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2196. }
  2197. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2198. }
  2199. parseStatement(context, topLevel) {
  2200. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2201. const lookahead = this.lookahead();
  2202. if (lookahead.type === types.name || isKeyword(lookahead.value)) {
  2203. const node = this.startNode();
  2204. this.next();
  2205. return this.flowParseInterface(node);
  2206. }
  2207. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2208. const node = this.startNode();
  2209. this.next();
  2210. return this.flowParseEnumDeclaration(node);
  2211. }
  2212. const stmt = super.parseStatement(context, topLevel);
  2213. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2214. this.flowPragma = null;
  2215. }
  2216. return stmt;
  2217. }
  2218. parseExpressionStatement(node, expr) {
  2219. if (expr.type === "Identifier") {
  2220. if (expr.name === "declare") {
  2221. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2222. return this.flowParseDeclare(node);
  2223. }
  2224. } else if (this.match(types.name)) {
  2225. if (expr.name === "interface") {
  2226. return this.flowParseInterface(node);
  2227. } else if (expr.name === "type") {
  2228. return this.flowParseTypeAlias(node);
  2229. } else if (expr.name === "opaque") {
  2230. return this.flowParseOpaqueType(node, false);
  2231. }
  2232. }
  2233. }
  2234. return super.parseExpressionStatement(node, expr);
  2235. }
  2236. shouldParseExportDeclaration() {
  2237. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2238. }
  2239. isExportDefaultSpecifier() {
  2240. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2241. return false;
  2242. }
  2243. return super.isExportDefaultSpecifier();
  2244. }
  2245. parseExportDefaultExpression() {
  2246. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2247. const node = this.startNode();
  2248. this.next();
  2249. return this.flowParseEnumDeclaration(node);
  2250. }
  2251. return super.parseExportDefaultExpression();
  2252. }
  2253. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  2254. if (!this.match(types.question)) return expr;
  2255. if (refNeedsArrowPos) {
  2256. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  2257. if (!result.node) {
  2258. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2259. return expr;
  2260. }
  2261. if (result.error) this.state = result.failState;
  2262. return result.node;
  2263. }
  2264. this.expect(types.question);
  2265. const state = this.state.clone();
  2266. const originalNoArrowAt = this.state.noArrowAt;
  2267. const node = this.startNodeAt(startPos, startLoc);
  2268. let {
  2269. consequent,
  2270. failed
  2271. } = this.tryParseConditionalConsequent();
  2272. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2273. if (failed || invalid.length > 0) {
  2274. const noArrowAt = [...originalNoArrowAt];
  2275. if (invalid.length > 0) {
  2276. this.state = state;
  2277. this.state.noArrowAt = noArrowAt;
  2278. for (let i = 0; i < invalid.length; i++) {
  2279. noArrowAt.push(invalid[i].start);
  2280. }
  2281. ({
  2282. consequent,
  2283. failed
  2284. } = this.tryParseConditionalConsequent());
  2285. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2286. }
  2287. if (failed && valid.length > 1) {
  2288. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2289. }
  2290. if (failed && valid.length === 1) {
  2291. this.state = state;
  2292. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2293. ({
  2294. consequent,
  2295. failed
  2296. } = this.tryParseConditionalConsequent());
  2297. }
  2298. }
  2299. this.getArrowLikeExpressions(consequent, true);
  2300. this.state.noArrowAt = originalNoArrowAt;
  2301. this.expect(types.colon);
  2302. node.test = expr;
  2303. node.consequent = consequent;
  2304. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  2305. return this.finishNode(node, "ConditionalExpression");
  2306. }
  2307. tryParseConditionalConsequent() {
  2308. this.state.noArrowParamsConversionAt.push(this.state.start);
  2309. const consequent = this.parseMaybeAssignAllowIn();
  2310. const failed = !this.match(types.colon);
  2311. this.state.noArrowParamsConversionAt.pop();
  2312. return {
  2313. consequent,
  2314. failed
  2315. };
  2316. }
  2317. getArrowLikeExpressions(node, disallowInvalid) {
  2318. const stack = [node];
  2319. const arrows = [];
  2320. while (stack.length !== 0) {
  2321. const node = stack.pop();
  2322. if (node.type === "ArrowFunctionExpression") {
  2323. if (node.typeParameters || !node.returnType) {
  2324. this.finishArrowValidation(node);
  2325. } else {
  2326. arrows.push(node);
  2327. }
  2328. stack.push(node.body);
  2329. } else if (node.type === "ConditionalExpression") {
  2330. stack.push(node.consequent);
  2331. stack.push(node.alternate);
  2332. }
  2333. }
  2334. if (disallowInvalid) {
  2335. arrows.forEach(node => this.finishArrowValidation(node));
  2336. return [arrows, []];
  2337. }
  2338. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2339. }
  2340. finishArrowValidation(node) {
  2341. var _node$extra;
  2342. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  2343. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2344. super.checkParams(node, false, true);
  2345. this.scope.exit();
  2346. }
  2347. forwardNoArrowParamsConversionAt(node, parse) {
  2348. let result;
  2349. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2350. this.state.noArrowParamsConversionAt.push(this.state.start);
  2351. result = parse();
  2352. this.state.noArrowParamsConversionAt.pop();
  2353. } else {
  2354. result = parse();
  2355. }
  2356. return result;
  2357. }
  2358. parseParenItem(node, startPos, startLoc) {
  2359. node = super.parseParenItem(node, startPos, startLoc);
  2360. if (this.eat(types.question)) {
  2361. node.optional = true;
  2362. this.resetEndLocation(node);
  2363. }
  2364. if (this.match(types.colon)) {
  2365. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2366. typeCastNode.expression = node;
  2367. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2368. return this.finishNode(typeCastNode, "TypeCastExpression");
  2369. }
  2370. return node;
  2371. }
  2372. assertModuleNodeAllowed(node) {
  2373. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2374. return;
  2375. }
  2376. super.assertModuleNodeAllowed(node);
  2377. }
  2378. parseExport(node) {
  2379. const decl = super.parseExport(node);
  2380. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2381. decl.exportKind = decl.exportKind || "value";
  2382. }
  2383. return decl;
  2384. }
  2385. parseExportDeclaration(node) {
  2386. if (this.isContextual("type")) {
  2387. node.exportKind = "type";
  2388. const declarationNode = this.startNode();
  2389. this.next();
  2390. if (this.match(types.braceL)) {
  2391. node.specifiers = this.parseExportSpecifiers();
  2392. this.parseExportFrom(node);
  2393. return null;
  2394. } else {
  2395. return this.flowParseTypeAlias(declarationNode);
  2396. }
  2397. } else if (this.isContextual("opaque")) {
  2398. node.exportKind = "type";
  2399. const declarationNode = this.startNode();
  2400. this.next();
  2401. return this.flowParseOpaqueType(declarationNode, false);
  2402. } else if (this.isContextual("interface")) {
  2403. node.exportKind = "type";
  2404. const declarationNode = this.startNode();
  2405. this.next();
  2406. return this.flowParseInterface(declarationNode);
  2407. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2408. node.exportKind = "value";
  2409. const declarationNode = this.startNode();
  2410. this.next();
  2411. return this.flowParseEnumDeclaration(declarationNode);
  2412. } else {
  2413. return super.parseExportDeclaration(node);
  2414. }
  2415. }
  2416. eatExportStar(node) {
  2417. if (super.eatExportStar(...arguments)) return true;
  2418. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2419. node.exportKind = "type";
  2420. this.next();
  2421. this.next();
  2422. return true;
  2423. }
  2424. return false;
  2425. }
  2426. maybeParseExportNamespaceSpecifier(node) {
  2427. const pos = this.state.start;
  2428. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2429. if (hasNamespace && node.exportKind === "type") {
  2430. this.unexpected(pos);
  2431. }
  2432. return hasNamespace;
  2433. }
  2434. parseClassId(node, isStatement, optionalId) {
  2435. super.parseClassId(node, isStatement, optionalId);
  2436. if (this.isRelational("<")) {
  2437. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2438. }
  2439. }
  2440. parseClassMember(classBody, member, state) {
  2441. const pos = this.state.start;
  2442. if (this.isContextual("declare")) {
  2443. if (this.parseClassMemberFromModifier(classBody, member)) {
  2444. return;
  2445. }
  2446. member.declare = true;
  2447. }
  2448. super.parseClassMember(classBody, member, state);
  2449. if (member.declare) {
  2450. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  2451. this.raise(pos, FlowErrors.DeclareClassElement);
  2452. } else if (member.value) {
  2453. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2454. }
  2455. }
  2456. }
  2457. getTokenFromCode(code) {
  2458. const next = this.input.charCodeAt(this.state.pos + 1);
  2459. if (code === 123 && next === 124) {
  2460. return this.finishOp(types.braceBarL, 2);
  2461. } else if (this.state.inType && (code === 62 || code === 60)) {
  2462. return this.finishOp(types.relational, 1);
  2463. } else if (this.state.inType && code === 63) {
  2464. return this.finishOp(types.question, 1);
  2465. } else if (isIteratorStart(code, next)) {
  2466. this.state.isIterator = true;
  2467. return super.readWord();
  2468. } else {
  2469. return super.getTokenFromCode(code);
  2470. }
  2471. }
  2472. isAssignable(node, isBinding) {
  2473. switch (node.type) {
  2474. case "Identifier":
  2475. case "ObjectPattern":
  2476. case "ArrayPattern":
  2477. case "AssignmentPattern":
  2478. return true;
  2479. case "ObjectExpression":
  2480. {
  2481. const last = node.properties.length - 1;
  2482. return node.properties.every((prop, i) => {
  2483. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2484. });
  2485. }
  2486. case "ObjectProperty":
  2487. return this.isAssignable(node.value);
  2488. case "SpreadElement":
  2489. return this.isAssignable(node.argument);
  2490. case "ArrayExpression":
  2491. return node.elements.every(element => this.isAssignable(element));
  2492. case "AssignmentExpression":
  2493. return node.operator === "=";
  2494. case "ParenthesizedExpression":
  2495. case "TypeCastExpression":
  2496. return this.isAssignable(node.expression);
  2497. case "MemberExpression":
  2498. case "OptionalMemberExpression":
  2499. return !isBinding;
  2500. default:
  2501. return false;
  2502. }
  2503. }
  2504. toAssignable(node, isLHS = false) {
  2505. if (node.type === "TypeCastExpression") {
  2506. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  2507. } else {
  2508. return super.toAssignable(node, isLHS);
  2509. }
  2510. }
  2511. toAssignableList(exprList, trailingCommaPos, isLHS) {
  2512. for (let i = 0; i < exprList.length; i++) {
  2513. const expr = exprList[i];
  2514. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  2515. exprList[i] = this.typeCastToParameter(expr);
  2516. }
  2517. }
  2518. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  2519. }
  2520. toReferencedList(exprList, isParenthesizedExpr) {
  2521. for (let i = 0; i < exprList.length; i++) {
  2522. var _expr$extra;
  2523. const expr = exprList[i];
  2524. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) == null ? void 0 : _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2525. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2526. }
  2527. }
  2528. return exprList;
  2529. }
  2530. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  2531. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  2532. if (canBePattern && !this.state.maybeInArrowParameters) {
  2533. this.toReferencedList(node.elements);
  2534. }
  2535. return node;
  2536. }
  2537. checkLVal(expr, ...args) {
  2538. if (expr.type !== "TypeCastExpression") {
  2539. return super.checkLVal(expr, ...args);
  2540. }
  2541. }
  2542. parseClassProperty(node) {
  2543. if (this.match(types.colon)) {
  2544. node.typeAnnotation = this.flowParseTypeAnnotation();
  2545. }
  2546. return super.parseClassProperty(node);
  2547. }
  2548. parseClassPrivateProperty(node) {
  2549. if (this.match(types.colon)) {
  2550. node.typeAnnotation = this.flowParseTypeAnnotation();
  2551. }
  2552. return super.parseClassPrivateProperty(node);
  2553. }
  2554. isClassMethod() {
  2555. return this.isRelational("<") || super.isClassMethod();
  2556. }
  2557. isClassProperty() {
  2558. return this.match(types.colon) || super.isClassProperty();
  2559. }
  2560. isNonstaticConstructor(method) {
  2561. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2562. }
  2563. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2564. if (method.variance) {
  2565. this.unexpected(method.variance.start);
  2566. }
  2567. delete method.variance;
  2568. if (this.isRelational("<")) {
  2569. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2570. }
  2571. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2572. }
  2573. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2574. if (method.variance) {
  2575. this.unexpected(method.variance.start);
  2576. }
  2577. delete method.variance;
  2578. if (this.isRelational("<")) {
  2579. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2580. }
  2581. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2582. }
  2583. parseClassSuper(node) {
  2584. super.parseClassSuper(node);
  2585. if (node.superClass && this.isRelational("<")) {
  2586. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2587. }
  2588. if (this.isContextual("implements")) {
  2589. this.next();
  2590. const implemented = node.implements = [];
  2591. do {
  2592. const node = this.startNode();
  2593. node.id = this.flowParseRestrictedIdentifier(true);
  2594. if (this.isRelational("<")) {
  2595. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2596. } else {
  2597. node.typeParameters = null;
  2598. }
  2599. implemented.push(this.finishNode(node, "ClassImplements"));
  2600. } while (this.eat(types.comma));
  2601. }
  2602. }
  2603. parsePropertyName(node, isPrivateNameAllowed) {
  2604. const variance = this.flowParseVariance();
  2605. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2606. node.variance = variance;
  2607. return key;
  2608. }
  2609. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  2610. if (prop.variance) {
  2611. this.unexpected(prop.variance.start);
  2612. }
  2613. delete prop.variance;
  2614. let typeParameters;
  2615. if (this.isRelational("<") && !isAccessor) {
  2616. typeParameters = this.flowParseTypeParameterDeclaration();
  2617. if (!this.match(types.parenL)) this.unexpected();
  2618. }
  2619. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  2620. if (typeParameters) {
  2621. (prop.value || prop).typeParameters = typeParameters;
  2622. }
  2623. }
  2624. parseAssignableListItemTypes(param) {
  2625. if (this.eat(types.question)) {
  2626. if (param.type !== "Identifier") {
  2627. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  2628. }
  2629. param.optional = true;
  2630. }
  2631. if (this.match(types.colon)) {
  2632. param.typeAnnotation = this.flowParseTypeAnnotation();
  2633. }
  2634. this.resetEndLocation(param);
  2635. return param;
  2636. }
  2637. parseMaybeDefault(startPos, startLoc, left) {
  2638. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2639. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2640. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  2641. }
  2642. return node;
  2643. }
  2644. shouldParseDefaultImport(node) {
  2645. if (!hasTypeImportKind(node)) {
  2646. return super.shouldParseDefaultImport(node);
  2647. }
  2648. return isMaybeDefaultImport(this.state);
  2649. }
  2650. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2651. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2652. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  2653. node.specifiers.push(this.finishNode(specifier, type));
  2654. }
  2655. maybeParseDefaultImportSpecifier(node) {
  2656. node.importKind = "value";
  2657. let kind = null;
  2658. if (this.match(types._typeof)) {
  2659. kind = "typeof";
  2660. } else if (this.isContextual("type")) {
  2661. kind = "type";
  2662. }
  2663. if (kind) {
  2664. const lh = this.lookahead();
  2665. if (kind === "type" && lh.type === types.star) {
  2666. this.unexpected(lh.start);
  2667. }
  2668. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2669. this.next();
  2670. node.importKind = kind;
  2671. }
  2672. }
  2673. return super.maybeParseDefaultImportSpecifier(node);
  2674. }
  2675. parseImportSpecifier(node) {
  2676. const specifier = this.startNode();
  2677. const firstIdentLoc = this.state.start;
  2678. const firstIdent = this.parseModuleExportName();
  2679. let specifierTypeKind = null;
  2680. if (firstIdent.type === "Identifier") {
  2681. if (firstIdent.name === "type") {
  2682. specifierTypeKind = "type";
  2683. } else if (firstIdent.name === "typeof") {
  2684. specifierTypeKind = "typeof";
  2685. }
  2686. }
  2687. let isBinding = false;
  2688. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2689. const as_ident = this.parseIdentifier(true);
  2690. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2691. specifier.imported = as_ident;
  2692. specifier.importKind = specifierTypeKind;
  2693. specifier.local = as_ident.__clone();
  2694. } else {
  2695. specifier.imported = firstIdent;
  2696. specifier.importKind = null;
  2697. specifier.local = this.parseIdentifier();
  2698. }
  2699. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2700. specifier.imported = this.parseIdentifier(true);
  2701. specifier.importKind = specifierTypeKind;
  2702. if (this.eatContextual("as")) {
  2703. specifier.local = this.parseIdentifier();
  2704. } else {
  2705. isBinding = true;
  2706. specifier.local = specifier.imported.__clone();
  2707. }
  2708. } else {
  2709. if (firstIdent.type === "StringLiteral") {
  2710. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  2711. }
  2712. isBinding = true;
  2713. specifier.imported = firstIdent;
  2714. specifier.importKind = null;
  2715. specifier.local = specifier.imported.__clone();
  2716. }
  2717. const nodeIsTypeImport = hasTypeImportKind(node);
  2718. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2719. if (nodeIsTypeImport && specifierIsTypeImport) {
  2720. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  2721. }
  2722. if (nodeIsTypeImport || specifierIsTypeImport) {
  2723. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2724. }
  2725. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2726. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2727. }
  2728. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  2729. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2730. }
  2731. parseFunctionParams(node, allowModifiers) {
  2732. const kind = node.kind;
  2733. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2734. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2735. }
  2736. super.parseFunctionParams(node, allowModifiers);
  2737. }
  2738. parseVarId(decl, kind) {
  2739. super.parseVarId(decl, kind);
  2740. if (this.match(types.colon)) {
  2741. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2742. this.resetEndLocation(decl.id);
  2743. }
  2744. }
  2745. parseAsyncArrowFromCallExpression(node, call) {
  2746. if (this.match(types.colon)) {
  2747. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2748. this.state.noAnonFunctionType = true;
  2749. node.returnType = this.flowParseTypeAnnotation();
  2750. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2751. }
  2752. return super.parseAsyncArrowFromCallExpression(node, call);
  2753. }
  2754. shouldParseAsyncArrow() {
  2755. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2756. }
  2757. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  2758. var _jsx;
  2759. let state = null;
  2760. let jsx;
  2761. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2762. state = this.state.clone();
  2763. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  2764. if (!jsx.error) return jsx.node;
  2765. const {
  2766. context
  2767. } = this.state;
  2768. if (context[context.length - 1] === types$1.j_oTag) {
  2769. context.length -= 2;
  2770. } else if (context[context.length - 1] === types$1.j_expr) {
  2771. context.length -= 1;
  2772. }
  2773. }
  2774. if (((_jsx = jsx) == null ? void 0 : _jsx.error) || this.isRelational("<")) {
  2775. var _jsx2, _jsx3;
  2776. state = state || this.state.clone();
  2777. let typeParameters;
  2778. const arrow = this.tryParse(abort => {
  2779. var _arrowExpression$extr;
  2780. typeParameters = this.flowParseTypeParameterDeclaration();
  2781. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  2782. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2783. this.resetStartLocationFromNode(result, typeParameters);
  2784. return result;
  2785. });
  2786. if (arrowExpression.type !== "ArrowFunctionExpression" && ((_arrowExpression$extr = arrowExpression.extra) == null ? void 0 : _arrowExpression$extr.parenthesized)) {
  2787. abort();
  2788. }
  2789. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  2790. expr.typeParameters = typeParameters;
  2791. this.resetStartLocationFromNode(expr, typeParameters);
  2792. return arrowExpression;
  2793. }, state);
  2794. let arrowExpression = null;
  2795. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  2796. if (!arrow.error && !arrow.aborted) {
  2797. if (arrow.node.async) {
  2798. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  2799. }
  2800. return arrow.node;
  2801. }
  2802. arrowExpression = arrow.node;
  2803. }
  2804. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  2805. this.state = jsx.failState;
  2806. return jsx.node;
  2807. }
  2808. if (arrowExpression) {
  2809. this.state = arrow.failState;
  2810. return arrowExpression;
  2811. }
  2812. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  2813. if (arrow.thrown) throw arrow.error;
  2814. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  2815. }
  2816. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2817. }
  2818. parseArrow(node) {
  2819. if (this.match(types.colon)) {
  2820. const result = this.tryParse(() => {
  2821. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2822. this.state.noAnonFunctionType = true;
  2823. const typeNode = this.startNode();
  2824. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2825. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2826. if (this.canInsertSemicolon()) this.unexpected();
  2827. if (!this.match(types.arrow)) this.unexpected();
  2828. return typeNode;
  2829. });
  2830. if (result.thrown) return null;
  2831. if (result.error) this.state = result.failState;
  2832. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2833. }
  2834. return super.parseArrow(node);
  2835. }
  2836. shouldParseArrow() {
  2837. return this.match(types.colon) || super.shouldParseArrow();
  2838. }
  2839. setArrowFunctionParameters(node, params) {
  2840. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2841. node.params = params;
  2842. } else {
  2843. super.setArrowFunctionParameters(node, params);
  2844. }
  2845. }
  2846. checkParams(node, allowDuplicates, isArrowFunction) {
  2847. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2848. return;
  2849. }
  2850. return super.checkParams(...arguments);
  2851. }
  2852. parseParenAndDistinguishExpression(canBeArrow) {
  2853. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2854. }
  2855. parseSubscripts(base, startPos, startLoc, noCalls) {
  2856. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2857. this.next();
  2858. const node = this.startNodeAt(startPos, startLoc);
  2859. node.callee = base;
  2860. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2861. base = this.finishNode(node, "CallExpression");
  2862. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2863. const state = this.state.clone();
  2864. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2865. if (!arrow.error && !arrow.aborted) return arrow.node;
  2866. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2867. if (result.node && !result.error) return result.node;
  2868. if (arrow.node) {
  2869. this.state = arrow.failState;
  2870. return arrow.node;
  2871. }
  2872. if (result.node) {
  2873. this.state = result.failState;
  2874. return result.node;
  2875. }
  2876. throw arrow.error || result.error;
  2877. }
  2878. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2879. }
  2880. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2881. if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
  2882. subscriptState.optionalChainMember = true;
  2883. if (noCalls) {
  2884. subscriptState.stop = true;
  2885. return base;
  2886. }
  2887. this.next();
  2888. const node = this.startNodeAt(startPos, startLoc);
  2889. node.callee = base;
  2890. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2891. this.expect(types.parenL);
  2892. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2893. node.optional = true;
  2894. return this.finishCallExpression(node, true);
  2895. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2896. const node = this.startNodeAt(startPos, startLoc);
  2897. node.callee = base;
  2898. const result = this.tryParse(() => {
  2899. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2900. this.expect(types.parenL);
  2901. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2902. if (subscriptState.optionalChainMember) node.optional = false;
  2903. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2904. });
  2905. if (result.node) {
  2906. if (result.error) this.state = result.failState;
  2907. return result.node;
  2908. }
  2909. }
  2910. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2911. }
  2912. parseNewArguments(node) {
  2913. let targs = null;
  2914. if (this.shouldParseTypes() && this.isRelational("<")) {
  2915. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2916. }
  2917. node.typeArguments = targs;
  2918. super.parseNewArguments(node);
  2919. }
  2920. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2921. const node = this.startNodeAt(startPos, startLoc);
  2922. this.parseFunctionParams(node);
  2923. if (!this.parseArrow(node)) return;
  2924. return this.parseArrowExpression(node, undefined, true);
  2925. }
  2926. readToken_mult_modulo(code) {
  2927. const next = this.input.charCodeAt(this.state.pos + 1);
  2928. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2929. this.state.hasFlowComment = false;
  2930. this.state.pos += 2;
  2931. this.nextToken();
  2932. return;
  2933. }
  2934. super.readToken_mult_modulo(code);
  2935. }
  2936. readToken_pipe_amp(code) {
  2937. const next = this.input.charCodeAt(this.state.pos + 1);
  2938. if (code === 124 && next === 125) {
  2939. this.finishOp(types.braceBarR, 2);
  2940. return;
  2941. }
  2942. super.readToken_pipe_amp(code);
  2943. }
  2944. parseTopLevel(file, program) {
  2945. const fileNode = super.parseTopLevel(file, program);
  2946. if (this.state.hasFlowComment) {
  2947. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  2948. }
  2949. return fileNode;
  2950. }
  2951. skipBlockComment() {
  2952. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2953. if (this.state.hasFlowComment) {
  2954. this.unexpected(null, FlowErrors.NestedFlowComment);
  2955. }
  2956. this.hasFlowCommentCompletion();
  2957. this.state.pos += this.skipFlowComment();
  2958. this.state.hasFlowComment = true;
  2959. return;
  2960. }
  2961. if (this.state.hasFlowComment) {
  2962. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2963. if (end === -1) {
  2964. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  2965. }
  2966. this.state.pos = end + 3;
  2967. return;
  2968. }
  2969. super.skipBlockComment();
  2970. }
  2971. skipFlowComment() {
  2972. const {
  2973. pos
  2974. } = this.state;
  2975. let shiftToFirstNonWhiteSpace = 2;
  2976. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2977. shiftToFirstNonWhiteSpace++;
  2978. }
  2979. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2980. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2981. if (ch2 === 58 && ch3 === 58) {
  2982. return shiftToFirstNonWhiteSpace + 2;
  2983. }
  2984. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2985. return shiftToFirstNonWhiteSpace + 12;
  2986. }
  2987. if (ch2 === 58 && ch3 !== 58) {
  2988. return shiftToFirstNonWhiteSpace;
  2989. }
  2990. return false;
  2991. }
  2992. hasFlowCommentCompletion() {
  2993. const end = this.input.indexOf("*/", this.state.pos);
  2994. if (end === -1) {
  2995. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  2996. }
  2997. }
  2998. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2999. enumName,
  3000. memberName
  3001. }) {
  3002. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  3003. }
  3004. flowEnumErrorInvalidMemberName(pos, {
  3005. enumName,
  3006. memberName
  3007. }) {
  3008. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  3009. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  3010. }
  3011. flowEnumErrorDuplicateMemberName(pos, {
  3012. enumName,
  3013. memberName
  3014. }) {
  3015. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  3016. }
  3017. flowEnumErrorInconsistentMemberValues(pos, {
  3018. enumName
  3019. }) {
  3020. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  3021. }
  3022. flowEnumErrorInvalidExplicitType(pos, {
  3023. enumName,
  3024. suppliedType
  3025. }) {
  3026. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  3027. }
  3028. flowEnumErrorInvalidMemberInitializer(pos, {
  3029. enumName,
  3030. explicitType,
  3031. memberName
  3032. }) {
  3033. let message = null;
  3034. switch (explicitType) {
  3035. case "boolean":
  3036. case "number":
  3037. case "string":
  3038. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  3039. break;
  3040. case "symbol":
  3041. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  3042. break;
  3043. default:
  3044. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  3045. }
  3046. return this.raise(pos, message, enumName, memberName, explicitType);
  3047. }
  3048. flowEnumErrorNumberMemberNotInitialized(pos, {
  3049. enumName,
  3050. memberName
  3051. }) {
  3052. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  3053. }
  3054. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  3055. enumName
  3056. }) {
  3057. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  3058. }
  3059. flowEnumMemberInit() {
  3060. const startPos = this.state.start;
  3061. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  3062. switch (this.state.type) {
  3063. case types.num:
  3064. {
  3065. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  3066. if (endOfInit()) {
  3067. return {
  3068. type: "number",
  3069. pos: literal.start,
  3070. value: literal
  3071. };
  3072. }
  3073. return {
  3074. type: "invalid",
  3075. pos: startPos
  3076. };
  3077. }
  3078. case types.string:
  3079. {
  3080. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  3081. if (endOfInit()) {
  3082. return {
  3083. type: "string",
  3084. pos: literal.start,
  3085. value: literal
  3086. };
  3087. }
  3088. return {
  3089. type: "invalid",
  3090. pos: startPos
  3091. };
  3092. }
  3093. case types._true:
  3094. case types._false:
  3095. {
  3096. const literal = this.parseBooleanLiteral();
  3097. if (endOfInit()) {
  3098. return {
  3099. type: "boolean",
  3100. pos: literal.start,
  3101. value: literal
  3102. };
  3103. }
  3104. return {
  3105. type: "invalid",
  3106. pos: startPos
  3107. };
  3108. }
  3109. default:
  3110. return {
  3111. type: "invalid",
  3112. pos: startPos
  3113. };
  3114. }
  3115. }
  3116. flowEnumMemberRaw() {
  3117. const pos = this.state.start;
  3118. const id = this.parseIdentifier(true);
  3119. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3120. type: "none",
  3121. pos
  3122. };
  3123. return {
  3124. id,
  3125. init
  3126. };
  3127. }
  3128. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3129. const {
  3130. explicitType
  3131. } = context;
  3132. if (explicitType === null) {
  3133. return;
  3134. }
  3135. if (explicitType !== expectedType) {
  3136. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3137. }
  3138. }
  3139. flowEnumMembers({
  3140. enumName,
  3141. explicitType
  3142. }) {
  3143. const seenNames = new Set();
  3144. const members = {
  3145. booleanMembers: [],
  3146. numberMembers: [],
  3147. stringMembers: [],
  3148. defaultedMembers: []
  3149. };
  3150. while (!this.match(types.braceR)) {
  3151. const memberNode = this.startNode();
  3152. const {
  3153. id,
  3154. init
  3155. } = this.flowEnumMemberRaw();
  3156. const memberName = id.name;
  3157. if (memberName === "") {
  3158. continue;
  3159. }
  3160. if (/^[a-z]/.test(memberName)) {
  3161. this.flowEnumErrorInvalidMemberName(id.start, {
  3162. enumName,
  3163. memberName
  3164. });
  3165. }
  3166. if (seenNames.has(memberName)) {
  3167. this.flowEnumErrorDuplicateMemberName(id.start, {
  3168. enumName,
  3169. memberName
  3170. });
  3171. }
  3172. seenNames.add(memberName);
  3173. const context = {
  3174. enumName,
  3175. explicitType,
  3176. memberName
  3177. };
  3178. memberNode.id = id;
  3179. switch (init.type) {
  3180. case "boolean":
  3181. {
  3182. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3183. memberNode.init = init.value;
  3184. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3185. break;
  3186. }
  3187. case "number":
  3188. {
  3189. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3190. memberNode.init = init.value;
  3191. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3192. break;
  3193. }
  3194. case "string":
  3195. {
  3196. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3197. memberNode.init = init.value;
  3198. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3199. break;
  3200. }
  3201. case "invalid":
  3202. {
  3203. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3204. }
  3205. case "none":
  3206. {
  3207. switch (explicitType) {
  3208. case "boolean":
  3209. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3210. break;
  3211. case "number":
  3212. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3213. break;
  3214. default:
  3215. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3216. }
  3217. }
  3218. }
  3219. if (!this.match(types.braceR)) {
  3220. this.expect(types.comma);
  3221. }
  3222. }
  3223. return members;
  3224. }
  3225. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3226. enumName
  3227. }) {
  3228. if (initializedMembers.length === 0) {
  3229. return defaultedMembers;
  3230. } else if (defaultedMembers.length === 0) {
  3231. return initializedMembers;
  3232. } else if (defaultedMembers.length > initializedMembers.length) {
  3233. for (let _i = 0; _i < initializedMembers.length; _i++) {
  3234. const member = initializedMembers[_i];
  3235. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3236. enumName
  3237. });
  3238. }
  3239. return defaultedMembers;
  3240. } else {
  3241. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  3242. const member = defaultedMembers[_i2];
  3243. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3244. enumName
  3245. });
  3246. }
  3247. return initializedMembers;
  3248. }
  3249. }
  3250. flowEnumParseExplicitType({
  3251. enumName
  3252. }) {
  3253. if (this.eatContextual("of")) {
  3254. if (!this.match(types.name)) {
  3255. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3256. enumName,
  3257. suppliedType: null
  3258. });
  3259. }
  3260. const {
  3261. value
  3262. } = this.state;
  3263. this.next();
  3264. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3265. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3266. enumName,
  3267. suppliedType: value
  3268. });
  3269. }
  3270. return value;
  3271. }
  3272. return null;
  3273. }
  3274. flowEnumBody(node, {
  3275. enumName,
  3276. nameLoc
  3277. }) {
  3278. const explicitType = this.flowEnumParseExplicitType({
  3279. enumName
  3280. });
  3281. this.expect(types.braceL);
  3282. const members = this.flowEnumMembers({
  3283. enumName,
  3284. explicitType
  3285. });
  3286. switch (explicitType) {
  3287. case "boolean":
  3288. node.explicitType = true;
  3289. node.members = members.booleanMembers;
  3290. this.expect(types.braceR);
  3291. return this.finishNode(node, "EnumBooleanBody");
  3292. case "number":
  3293. node.explicitType = true;
  3294. node.members = members.numberMembers;
  3295. this.expect(types.braceR);
  3296. return this.finishNode(node, "EnumNumberBody");
  3297. case "string":
  3298. node.explicitType = true;
  3299. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3300. enumName
  3301. });
  3302. this.expect(types.braceR);
  3303. return this.finishNode(node, "EnumStringBody");
  3304. case "symbol":
  3305. node.members = members.defaultedMembers;
  3306. this.expect(types.braceR);
  3307. return this.finishNode(node, "EnumSymbolBody");
  3308. default:
  3309. {
  3310. const empty = () => {
  3311. node.members = [];
  3312. this.expect(types.braceR);
  3313. return this.finishNode(node, "EnumStringBody");
  3314. };
  3315. node.explicitType = false;
  3316. const boolsLen = members.booleanMembers.length;
  3317. const numsLen = members.numberMembers.length;
  3318. const strsLen = members.stringMembers.length;
  3319. const defaultedLen = members.defaultedMembers.length;
  3320. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3321. return empty();
  3322. } else if (!boolsLen && !numsLen) {
  3323. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3324. enumName
  3325. });
  3326. this.expect(types.braceR);
  3327. return this.finishNode(node, "EnumStringBody");
  3328. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3329. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  3330. const member = _members$defaultedMem[_i3];
  3331. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3332. enumName,
  3333. memberName: member.id.name
  3334. });
  3335. }
  3336. node.members = members.booleanMembers;
  3337. this.expect(types.braceR);
  3338. return this.finishNode(node, "EnumBooleanBody");
  3339. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3340. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  3341. const member = _members$defaultedMem2[_i4];
  3342. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3343. enumName,
  3344. memberName: member.id.name
  3345. });
  3346. }
  3347. node.members = members.numberMembers;
  3348. this.expect(types.braceR);
  3349. return this.finishNode(node, "EnumNumberBody");
  3350. } else {
  3351. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3352. enumName
  3353. });
  3354. return empty();
  3355. }
  3356. }
  3357. }
  3358. }
  3359. flowParseEnumDeclaration(node) {
  3360. const id = this.parseIdentifier();
  3361. node.id = id;
  3362. node.body = this.flowEnumBody(this.startNode(), {
  3363. enumName: id.name,
  3364. nameLoc: id.start
  3365. });
  3366. return this.finishNode(node, "EnumDeclaration");
  3367. }
  3368. updateContext(prevType) {
  3369. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  3370. this.state.exprAllowed = false;
  3371. } else {
  3372. super.updateContext(prevType);
  3373. }
  3374. }
  3375. isLookaheadToken_lt() {
  3376. const next = this.nextTokenStart();
  3377. if (this.input.charCodeAt(next) === 60) {
  3378. const afterNext = this.input.charCodeAt(next + 1);
  3379. return afterNext !== 60 && afterNext !== 61;
  3380. }
  3381. return false;
  3382. }
  3383. maybeUnwrapTypeCastExpression(node) {
  3384. return node.type === "TypeCastExpression" ? node.expression : node;
  3385. }
  3386. }, _temp;
  3387. });
  3388. const entities = {
  3389. quot: "\u0022",
  3390. amp: "&",
  3391. apos: "\u0027",
  3392. lt: "<",
  3393. gt: ">",
  3394. nbsp: "\u00A0",
  3395. iexcl: "\u00A1",
  3396. cent: "\u00A2",
  3397. pound: "\u00A3",
  3398. curren: "\u00A4",
  3399. yen: "\u00A5",
  3400. brvbar: "\u00A6",
  3401. sect: "\u00A7",
  3402. uml: "\u00A8",
  3403. copy: "\u00A9",
  3404. ordf: "\u00AA",
  3405. laquo: "\u00AB",
  3406. not: "\u00AC",
  3407. shy: "\u00AD",
  3408. reg: "\u00AE",
  3409. macr: "\u00AF",
  3410. deg: "\u00B0",
  3411. plusmn: "\u00B1",
  3412. sup2: "\u00B2",
  3413. sup3: "\u00B3",
  3414. acute: "\u00B4",
  3415. micro: "\u00B5",
  3416. para: "\u00B6",
  3417. middot: "\u00B7",
  3418. cedil: "\u00B8",
  3419. sup1: "\u00B9",
  3420. ordm: "\u00BA",
  3421. raquo: "\u00BB",
  3422. frac14: "\u00BC",
  3423. frac12: "\u00BD",
  3424. frac34: "\u00BE",
  3425. iquest: "\u00BF",
  3426. Agrave: "\u00C0",
  3427. Aacute: "\u00C1",
  3428. Acirc: "\u00C2",
  3429. Atilde: "\u00C3",
  3430. Auml: "\u00C4",
  3431. Aring: "\u00C5",
  3432. AElig: "\u00C6",
  3433. Ccedil: "\u00C7",
  3434. Egrave: "\u00C8",
  3435. Eacute: "\u00C9",
  3436. Ecirc: "\u00CA",
  3437. Euml: "\u00CB",
  3438. Igrave: "\u00CC",
  3439. Iacute: "\u00CD",
  3440. Icirc: "\u00CE",
  3441. Iuml: "\u00CF",
  3442. ETH: "\u00D0",
  3443. Ntilde: "\u00D1",
  3444. Ograve: "\u00D2",
  3445. Oacute: "\u00D3",
  3446. Ocirc: "\u00D4",
  3447. Otilde: "\u00D5",
  3448. Ouml: "\u00D6",
  3449. times: "\u00D7",
  3450. Oslash: "\u00D8",
  3451. Ugrave: "\u00D9",
  3452. Uacute: "\u00DA",
  3453. Ucirc: "\u00DB",
  3454. Uuml: "\u00DC",
  3455. Yacute: "\u00DD",
  3456. THORN: "\u00DE",
  3457. szlig: "\u00DF",
  3458. agrave: "\u00E0",
  3459. aacute: "\u00E1",
  3460. acirc: "\u00E2",
  3461. atilde: "\u00E3",
  3462. auml: "\u00E4",
  3463. aring: "\u00E5",
  3464. aelig: "\u00E6",
  3465. ccedil: "\u00E7",
  3466. egrave: "\u00E8",
  3467. eacute: "\u00E9",
  3468. ecirc: "\u00EA",
  3469. euml: "\u00EB",
  3470. igrave: "\u00EC",
  3471. iacute: "\u00ED",
  3472. icirc: "\u00EE",
  3473. iuml: "\u00EF",
  3474. eth: "\u00F0",
  3475. ntilde: "\u00F1",
  3476. ograve: "\u00F2",
  3477. oacute: "\u00F3",
  3478. ocirc: "\u00F4",
  3479. otilde: "\u00F5",
  3480. ouml: "\u00F6",
  3481. divide: "\u00F7",
  3482. oslash: "\u00F8",
  3483. ugrave: "\u00F9",
  3484. uacute: "\u00FA",
  3485. ucirc: "\u00FB",
  3486. uuml: "\u00FC",
  3487. yacute: "\u00FD",
  3488. thorn: "\u00FE",
  3489. yuml: "\u00FF",
  3490. OElig: "\u0152",
  3491. oelig: "\u0153",
  3492. Scaron: "\u0160",
  3493. scaron: "\u0161",
  3494. Yuml: "\u0178",
  3495. fnof: "\u0192",
  3496. circ: "\u02C6",
  3497. tilde: "\u02DC",
  3498. Alpha: "\u0391",
  3499. Beta: "\u0392",
  3500. Gamma: "\u0393",
  3501. Delta: "\u0394",
  3502. Epsilon: "\u0395",
  3503. Zeta: "\u0396",
  3504. Eta: "\u0397",
  3505. Theta: "\u0398",
  3506. Iota: "\u0399",
  3507. Kappa: "\u039A",
  3508. Lambda: "\u039B",
  3509. Mu: "\u039C",
  3510. Nu: "\u039D",
  3511. Xi: "\u039E",
  3512. Omicron: "\u039F",
  3513. Pi: "\u03A0",
  3514. Rho: "\u03A1",
  3515. Sigma: "\u03A3",
  3516. Tau: "\u03A4",
  3517. Upsilon: "\u03A5",
  3518. Phi: "\u03A6",
  3519. Chi: "\u03A7",
  3520. Psi: "\u03A8",
  3521. Omega: "\u03A9",
  3522. alpha: "\u03B1",
  3523. beta: "\u03B2",
  3524. gamma: "\u03B3",
  3525. delta: "\u03B4",
  3526. epsilon: "\u03B5",
  3527. zeta: "\u03B6",
  3528. eta: "\u03B7",
  3529. theta: "\u03B8",
  3530. iota: "\u03B9",
  3531. kappa: "\u03BA",
  3532. lambda: "\u03BB",
  3533. mu: "\u03BC",
  3534. nu: "\u03BD",
  3535. xi: "\u03BE",
  3536. omicron: "\u03BF",
  3537. pi: "\u03C0",
  3538. rho: "\u03C1",
  3539. sigmaf: "\u03C2",
  3540. sigma: "\u03C3",
  3541. tau: "\u03C4",
  3542. upsilon: "\u03C5",
  3543. phi: "\u03C6",
  3544. chi: "\u03C7",
  3545. psi: "\u03C8",
  3546. omega: "\u03C9",
  3547. thetasym: "\u03D1",
  3548. upsih: "\u03D2",
  3549. piv: "\u03D6",
  3550. ensp: "\u2002",
  3551. emsp: "\u2003",
  3552. thinsp: "\u2009",
  3553. zwnj: "\u200C",
  3554. zwj: "\u200D",
  3555. lrm: "\u200E",
  3556. rlm: "\u200F",
  3557. ndash: "\u2013",
  3558. mdash: "\u2014",
  3559. lsquo: "\u2018",
  3560. rsquo: "\u2019",
  3561. sbquo: "\u201A",
  3562. ldquo: "\u201C",
  3563. rdquo: "\u201D",
  3564. bdquo: "\u201E",
  3565. dagger: "\u2020",
  3566. Dagger: "\u2021",
  3567. bull: "\u2022",
  3568. hellip: "\u2026",
  3569. permil: "\u2030",
  3570. prime: "\u2032",
  3571. Prime: "\u2033",
  3572. lsaquo: "\u2039",
  3573. rsaquo: "\u203A",
  3574. oline: "\u203E",
  3575. frasl: "\u2044",
  3576. euro: "\u20AC",
  3577. image: "\u2111",
  3578. weierp: "\u2118",
  3579. real: "\u211C",
  3580. trade: "\u2122",
  3581. alefsym: "\u2135",
  3582. larr: "\u2190",
  3583. uarr: "\u2191",
  3584. rarr: "\u2192",
  3585. darr: "\u2193",
  3586. harr: "\u2194",
  3587. crarr: "\u21B5",
  3588. lArr: "\u21D0",
  3589. uArr: "\u21D1",
  3590. rArr: "\u21D2",
  3591. dArr: "\u21D3",
  3592. hArr: "\u21D4",
  3593. forall: "\u2200",
  3594. part: "\u2202",
  3595. exist: "\u2203",
  3596. empty: "\u2205",
  3597. nabla: "\u2207",
  3598. isin: "\u2208",
  3599. notin: "\u2209",
  3600. ni: "\u220B",
  3601. prod: "\u220F",
  3602. sum: "\u2211",
  3603. minus: "\u2212",
  3604. lowast: "\u2217",
  3605. radic: "\u221A",
  3606. prop: "\u221D",
  3607. infin: "\u221E",
  3608. ang: "\u2220",
  3609. and: "\u2227",
  3610. or: "\u2228",
  3611. cap: "\u2229",
  3612. cup: "\u222A",
  3613. int: "\u222B",
  3614. there4: "\u2234",
  3615. sim: "\u223C",
  3616. cong: "\u2245",
  3617. asymp: "\u2248",
  3618. ne: "\u2260",
  3619. equiv: "\u2261",
  3620. le: "\u2264",
  3621. ge: "\u2265",
  3622. sub: "\u2282",
  3623. sup: "\u2283",
  3624. nsub: "\u2284",
  3625. sube: "\u2286",
  3626. supe: "\u2287",
  3627. oplus: "\u2295",
  3628. otimes: "\u2297",
  3629. perp: "\u22A5",
  3630. sdot: "\u22C5",
  3631. lceil: "\u2308",
  3632. rceil: "\u2309",
  3633. lfloor: "\u230A",
  3634. rfloor: "\u230B",
  3635. lang: "\u2329",
  3636. rang: "\u232A",
  3637. loz: "\u25CA",
  3638. spades: "\u2660",
  3639. clubs: "\u2663",
  3640. hearts: "\u2665",
  3641. diams: "\u2666"
  3642. };
  3643. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3644. const DECIMAL_NUMBER = /^\d+$/;
  3645. const JsxErrors = Object.freeze({
  3646. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3647. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3648. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3649. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  3650. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3651. UnterminatedJsxContent: "Unterminated JSX contents",
  3652. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3653. });
  3654. types$1.j_oTag = new TokContext("<tag", false);
  3655. types$1.j_cTag = new TokContext("</tag", false);
  3656. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3657. types.jsxName = new TokenType("jsxName");
  3658. types.jsxText = new TokenType("jsxText", {
  3659. beforeExpr: true
  3660. });
  3661. types.jsxTagStart = new TokenType("jsxTagStart", {
  3662. startsExpr: true
  3663. });
  3664. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3665. types.jsxTagStart.updateContext = function () {
  3666. this.state.context.push(types$1.j_expr);
  3667. this.state.context.push(types$1.j_oTag);
  3668. this.state.exprAllowed = false;
  3669. };
  3670. types.jsxTagEnd.updateContext = function (prevType) {
  3671. const out = this.state.context.pop();
  3672. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3673. this.state.context.pop();
  3674. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3675. } else {
  3676. this.state.exprAllowed = true;
  3677. }
  3678. };
  3679. function isFragment(object) {
  3680. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3681. }
  3682. function getQualifiedJSXName(object) {
  3683. if (object.type === "JSXIdentifier") {
  3684. return object.name;
  3685. }
  3686. if (object.type === "JSXNamespacedName") {
  3687. return object.namespace.name + ":" + object.name.name;
  3688. }
  3689. if (object.type === "JSXMemberExpression") {
  3690. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3691. }
  3692. throw new Error("Node had unexpected type: " + object.type);
  3693. }
  3694. var jsx = (superClass => class extends superClass {
  3695. jsxReadToken() {
  3696. let out = "";
  3697. let chunkStart = this.state.pos;
  3698. for (;;) {
  3699. if (this.state.pos >= this.length) {
  3700. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  3701. }
  3702. const ch = this.input.charCodeAt(this.state.pos);
  3703. switch (ch) {
  3704. case 60:
  3705. case 123:
  3706. if (this.state.pos === this.state.start) {
  3707. if (ch === 60 && this.state.exprAllowed) {
  3708. ++this.state.pos;
  3709. return this.finishToken(types.jsxTagStart);
  3710. }
  3711. return super.getTokenFromCode(ch);
  3712. }
  3713. out += this.input.slice(chunkStart, this.state.pos);
  3714. return this.finishToken(types.jsxText, out);
  3715. case 38:
  3716. out += this.input.slice(chunkStart, this.state.pos);
  3717. out += this.jsxReadEntity();
  3718. chunkStart = this.state.pos;
  3719. break;
  3720. default:
  3721. if (isNewLine(ch)) {
  3722. out += this.input.slice(chunkStart, this.state.pos);
  3723. out += this.jsxReadNewLine(true);
  3724. chunkStart = this.state.pos;
  3725. } else {
  3726. ++this.state.pos;
  3727. }
  3728. }
  3729. }
  3730. }
  3731. jsxReadNewLine(normalizeCRLF) {
  3732. const ch = this.input.charCodeAt(this.state.pos);
  3733. let out;
  3734. ++this.state.pos;
  3735. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3736. ++this.state.pos;
  3737. out = normalizeCRLF ? "\n" : "\r\n";
  3738. } else {
  3739. out = String.fromCharCode(ch);
  3740. }
  3741. ++this.state.curLine;
  3742. this.state.lineStart = this.state.pos;
  3743. return out;
  3744. }
  3745. jsxReadString(quote) {
  3746. let out = "";
  3747. let chunkStart = ++this.state.pos;
  3748. for (;;) {
  3749. if (this.state.pos >= this.length) {
  3750. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3751. }
  3752. const ch = this.input.charCodeAt(this.state.pos);
  3753. if (ch === quote) break;
  3754. if (ch === 38) {
  3755. out += this.input.slice(chunkStart, this.state.pos);
  3756. out += this.jsxReadEntity();
  3757. chunkStart = this.state.pos;
  3758. } else if (isNewLine(ch)) {
  3759. out += this.input.slice(chunkStart, this.state.pos);
  3760. out += this.jsxReadNewLine(false);
  3761. chunkStart = this.state.pos;
  3762. } else {
  3763. ++this.state.pos;
  3764. }
  3765. }
  3766. out += this.input.slice(chunkStart, this.state.pos++);
  3767. return this.finishToken(types.string, out);
  3768. }
  3769. jsxReadEntity() {
  3770. let str = "";
  3771. let count = 0;
  3772. let entity;
  3773. let ch = this.input[this.state.pos];
  3774. const startPos = ++this.state.pos;
  3775. while (this.state.pos < this.length && count++ < 10) {
  3776. ch = this.input[this.state.pos++];
  3777. if (ch === ";") {
  3778. if (str[0] === "#") {
  3779. if (str[1] === "x") {
  3780. str = str.substr(2);
  3781. if (HEX_NUMBER.test(str)) {
  3782. entity = String.fromCodePoint(parseInt(str, 16));
  3783. }
  3784. } else {
  3785. str = str.substr(1);
  3786. if (DECIMAL_NUMBER.test(str)) {
  3787. entity = String.fromCodePoint(parseInt(str, 10));
  3788. }
  3789. }
  3790. } else {
  3791. entity = entities[str];
  3792. }
  3793. break;
  3794. }
  3795. str += ch;
  3796. }
  3797. if (!entity) {
  3798. this.state.pos = startPos;
  3799. return "&";
  3800. }
  3801. return entity;
  3802. }
  3803. jsxReadWord() {
  3804. let ch;
  3805. const start = this.state.pos;
  3806. do {
  3807. ch = this.input.charCodeAt(++this.state.pos);
  3808. } while (isIdentifierChar(ch) || ch === 45);
  3809. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3810. }
  3811. jsxParseIdentifier() {
  3812. const node = this.startNode();
  3813. if (this.match(types.jsxName)) {
  3814. node.name = this.state.value;
  3815. } else if (this.state.type.keyword) {
  3816. node.name = this.state.type.keyword;
  3817. } else {
  3818. this.unexpected();
  3819. }
  3820. this.next();
  3821. return this.finishNode(node, "JSXIdentifier");
  3822. }
  3823. jsxParseNamespacedName() {
  3824. const startPos = this.state.start;
  3825. const startLoc = this.state.startLoc;
  3826. const name = this.jsxParseIdentifier();
  3827. if (!this.eat(types.colon)) return name;
  3828. const node = this.startNodeAt(startPos, startLoc);
  3829. node.namespace = name;
  3830. node.name = this.jsxParseIdentifier();
  3831. return this.finishNode(node, "JSXNamespacedName");
  3832. }
  3833. jsxParseElementName() {
  3834. const startPos = this.state.start;
  3835. const startLoc = this.state.startLoc;
  3836. let node = this.jsxParseNamespacedName();
  3837. if (node.type === "JSXNamespacedName") {
  3838. return node;
  3839. }
  3840. while (this.eat(types.dot)) {
  3841. const newNode = this.startNodeAt(startPos, startLoc);
  3842. newNode.object = node;
  3843. newNode.property = this.jsxParseIdentifier();
  3844. node = this.finishNode(newNode, "JSXMemberExpression");
  3845. }
  3846. return node;
  3847. }
  3848. jsxParseAttributeValue() {
  3849. let node;
  3850. switch (this.state.type) {
  3851. case types.braceL:
  3852. node = this.startNode();
  3853. this.next();
  3854. node = this.jsxParseExpressionContainer(node);
  3855. if (node.expression.type === "JSXEmptyExpression") {
  3856. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  3857. }
  3858. return node;
  3859. case types.jsxTagStart:
  3860. case types.string:
  3861. return this.parseExprAtom();
  3862. default:
  3863. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  3864. }
  3865. }
  3866. jsxParseEmptyExpression() {
  3867. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3868. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3869. }
  3870. jsxParseSpreadChild(node) {
  3871. this.next();
  3872. node.expression = this.parseExpression();
  3873. this.expect(types.braceR);
  3874. return this.finishNode(node, "JSXSpreadChild");
  3875. }
  3876. jsxParseExpressionContainer(node) {
  3877. if (this.match(types.braceR)) {
  3878. node.expression = this.jsxParseEmptyExpression();
  3879. } else {
  3880. const expression = this.parseExpression();
  3881. node.expression = expression;
  3882. }
  3883. this.expect(types.braceR);
  3884. return this.finishNode(node, "JSXExpressionContainer");
  3885. }
  3886. jsxParseAttribute() {
  3887. const node = this.startNode();
  3888. if (this.eat(types.braceL)) {
  3889. this.expect(types.ellipsis);
  3890. node.argument = this.parseMaybeAssignAllowIn();
  3891. this.expect(types.braceR);
  3892. return this.finishNode(node, "JSXSpreadAttribute");
  3893. }
  3894. node.name = this.jsxParseNamespacedName();
  3895. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3896. return this.finishNode(node, "JSXAttribute");
  3897. }
  3898. jsxParseOpeningElementAt(startPos, startLoc) {
  3899. const node = this.startNodeAt(startPos, startLoc);
  3900. if (this.match(types.jsxTagEnd)) {
  3901. this.expect(types.jsxTagEnd);
  3902. return this.finishNode(node, "JSXOpeningFragment");
  3903. }
  3904. node.name = this.jsxParseElementName();
  3905. return this.jsxParseOpeningElementAfterName(node);
  3906. }
  3907. jsxParseOpeningElementAfterName(node) {
  3908. const attributes = [];
  3909. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3910. attributes.push(this.jsxParseAttribute());
  3911. }
  3912. node.attributes = attributes;
  3913. node.selfClosing = this.eat(types.slash);
  3914. this.expect(types.jsxTagEnd);
  3915. return this.finishNode(node, "JSXOpeningElement");
  3916. }
  3917. jsxParseClosingElementAt(startPos, startLoc) {
  3918. const node = this.startNodeAt(startPos, startLoc);
  3919. if (this.match(types.jsxTagEnd)) {
  3920. this.expect(types.jsxTagEnd);
  3921. return this.finishNode(node, "JSXClosingFragment");
  3922. }
  3923. node.name = this.jsxParseElementName();
  3924. this.expect(types.jsxTagEnd);
  3925. return this.finishNode(node, "JSXClosingElement");
  3926. }
  3927. jsxParseElementAt(startPos, startLoc) {
  3928. const node = this.startNodeAt(startPos, startLoc);
  3929. const children = [];
  3930. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3931. let closingElement = null;
  3932. if (!openingElement.selfClosing) {
  3933. contents: for (;;) {
  3934. switch (this.state.type) {
  3935. case types.jsxTagStart:
  3936. startPos = this.state.start;
  3937. startLoc = this.state.startLoc;
  3938. this.next();
  3939. if (this.eat(types.slash)) {
  3940. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3941. break contents;
  3942. }
  3943. children.push(this.jsxParseElementAt(startPos, startLoc));
  3944. break;
  3945. case types.jsxText:
  3946. children.push(this.parseExprAtom());
  3947. break;
  3948. case types.braceL:
  3949. {
  3950. const node = this.startNode();
  3951. this.next();
  3952. if (this.match(types.ellipsis)) {
  3953. children.push(this.jsxParseSpreadChild(node));
  3954. } else {
  3955. children.push(this.jsxParseExpressionContainer(node));
  3956. }
  3957. break;
  3958. }
  3959. default:
  3960. throw this.unexpected();
  3961. }
  3962. }
  3963. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3964. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  3965. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3966. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3967. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3968. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3969. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3970. }
  3971. }
  3972. }
  3973. if (isFragment(openingElement)) {
  3974. node.openingFragment = openingElement;
  3975. node.closingFragment = closingElement;
  3976. } else {
  3977. node.openingElement = openingElement;
  3978. node.closingElement = closingElement;
  3979. }
  3980. node.children = children;
  3981. if (this.isRelational("<")) {
  3982. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  3983. }
  3984. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3985. }
  3986. jsxParseElement() {
  3987. const startPos = this.state.start;
  3988. const startLoc = this.state.startLoc;
  3989. this.next();
  3990. return this.jsxParseElementAt(startPos, startLoc);
  3991. }
  3992. parseExprAtom(refExpressionErrors) {
  3993. if (this.match(types.jsxText)) {
  3994. return this.parseLiteral(this.state.value, "JSXText");
  3995. } else if (this.match(types.jsxTagStart)) {
  3996. return this.jsxParseElement();
  3997. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3998. this.finishToken(types.jsxTagStart);
  3999. return this.jsxParseElement();
  4000. } else {
  4001. return super.parseExprAtom(refExpressionErrors);
  4002. }
  4003. }
  4004. getTokenFromCode(code) {
  4005. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  4006. const context = this.curContext();
  4007. if (context === types$1.j_expr) {
  4008. return this.jsxReadToken();
  4009. }
  4010. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  4011. if (isIdentifierStart(code)) {
  4012. return this.jsxReadWord();
  4013. }
  4014. if (code === 62) {
  4015. ++this.state.pos;
  4016. return this.finishToken(types.jsxTagEnd);
  4017. }
  4018. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  4019. return this.jsxReadString(code);
  4020. }
  4021. }
  4022. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  4023. ++this.state.pos;
  4024. return this.finishToken(types.jsxTagStart);
  4025. }
  4026. return super.getTokenFromCode(code);
  4027. }
  4028. updateContext(prevType) {
  4029. if (this.match(types.braceL)) {
  4030. const curContext = this.curContext();
  4031. if (curContext === types$1.j_oTag) {
  4032. this.state.context.push(types$1.braceExpression);
  4033. } else if (curContext === types$1.j_expr) {
  4034. this.state.context.push(types$1.templateQuasi);
  4035. } else {
  4036. super.updateContext(prevType);
  4037. }
  4038. this.state.exprAllowed = true;
  4039. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  4040. this.state.context.length -= 2;
  4041. this.state.context.push(types$1.j_cTag);
  4042. this.state.exprAllowed = false;
  4043. } else {
  4044. return super.updateContext(prevType);
  4045. }
  4046. }
  4047. });
  4048. class Scope {
  4049. constructor(flags) {
  4050. this.flags = void 0;
  4051. this.var = [];
  4052. this.lexical = [];
  4053. this.functions = [];
  4054. this.flags = flags;
  4055. }
  4056. }
  4057. class ScopeHandler {
  4058. constructor(raise, inModule) {
  4059. this.scopeStack = [];
  4060. this.undefinedExports = new Map();
  4061. this.undefinedPrivateNames = new Map();
  4062. this.raise = raise;
  4063. this.inModule = inModule;
  4064. }
  4065. get inFunction() {
  4066. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  4067. }
  4068. get allowSuper() {
  4069. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  4070. }
  4071. get allowDirectSuper() {
  4072. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  4073. }
  4074. get inClass() {
  4075. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  4076. }
  4077. get inNonArrowFunction() {
  4078. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  4079. }
  4080. get treatFunctionsAsVar() {
  4081. return this.treatFunctionsAsVarInScope(this.currentScope());
  4082. }
  4083. createScope(flags) {
  4084. return new Scope(flags);
  4085. }
  4086. enter(flags) {
  4087. this.scopeStack.push(this.createScope(flags));
  4088. }
  4089. exit() {
  4090. this.scopeStack.pop();
  4091. }
  4092. treatFunctionsAsVarInScope(scope) {
  4093. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  4094. }
  4095. declareName(name, bindingType, pos) {
  4096. let scope = this.currentScope();
  4097. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  4098. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4099. if (bindingType & BIND_SCOPE_FUNCTION) {
  4100. scope.functions.push(name);
  4101. } else {
  4102. scope.lexical.push(name);
  4103. }
  4104. if (bindingType & BIND_SCOPE_LEXICAL) {
  4105. this.maybeExportDefined(scope, name);
  4106. }
  4107. } else if (bindingType & BIND_SCOPE_VAR) {
  4108. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  4109. scope = this.scopeStack[i];
  4110. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4111. scope.var.push(name);
  4112. this.maybeExportDefined(scope, name);
  4113. if (scope.flags & SCOPE_VAR) break;
  4114. }
  4115. }
  4116. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4117. this.undefinedExports.delete(name);
  4118. }
  4119. }
  4120. maybeExportDefined(scope, name) {
  4121. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4122. this.undefinedExports.delete(name);
  4123. }
  4124. }
  4125. checkRedeclarationInScope(scope, name, bindingType, pos) {
  4126. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  4127. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  4128. }
  4129. }
  4130. isRedeclaredInScope(scope, name, bindingType) {
  4131. if (!(bindingType & BIND_KIND_VALUE)) return false;
  4132. if (bindingType & BIND_SCOPE_LEXICAL) {
  4133. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  4134. }
  4135. if (bindingType & BIND_SCOPE_FUNCTION) {
  4136. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  4137. }
  4138. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  4139. }
  4140. checkLocalExport(id) {
  4141. 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) {
  4142. this.undefinedExports.set(id.name, id.start);
  4143. }
  4144. }
  4145. currentScope() {
  4146. return this.scopeStack[this.scopeStack.length - 1];
  4147. }
  4148. currentVarScope() {
  4149. for (let i = this.scopeStack.length - 1;; i--) {
  4150. const scope = this.scopeStack[i];
  4151. if (scope.flags & SCOPE_VAR) {
  4152. return scope;
  4153. }
  4154. }
  4155. }
  4156. currentThisScope() {
  4157. for (let i = this.scopeStack.length - 1;; i--) {
  4158. const scope = this.scopeStack[i];
  4159. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  4160. return scope;
  4161. }
  4162. }
  4163. }
  4164. }
  4165. class TypeScriptScope extends Scope {
  4166. constructor(...args) {
  4167. super(...args);
  4168. this.types = [];
  4169. this.enums = [];
  4170. this.constEnums = [];
  4171. this.classes = [];
  4172. this.exportOnlyBindings = [];
  4173. }
  4174. }
  4175. class TypeScriptScopeHandler extends ScopeHandler {
  4176. createScope(flags) {
  4177. return new TypeScriptScope(flags);
  4178. }
  4179. declareName(name, bindingType, pos) {
  4180. const scope = this.currentScope();
  4181. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4182. this.maybeExportDefined(scope, name);
  4183. scope.exportOnlyBindings.push(name);
  4184. return;
  4185. }
  4186. super.declareName(...arguments);
  4187. if (bindingType & BIND_KIND_TYPE) {
  4188. if (!(bindingType & BIND_KIND_VALUE)) {
  4189. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4190. this.maybeExportDefined(scope, name);
  4191. }
  4192. scope.types.push(name);
  4193. }
  4194. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4195. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4196. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4197. }
  4198. isRedeclaredInScope(scope, name, bindingType) {
  4199. if (scope.enums.indexOf(name) > -1) {
  4200. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4201. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4202. const wasConst = scope.constEnums.indexOf(name) > -1;
  4203. return isConst !== wasConst;
  4204. }
  4205. return true;
  4206. }
  4207. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4208. if (scope.lexical.indexOf(name) > -1) {
  4209. return !!(bindingType & BIND_KIND_VALUE);
  4210. } else {
  4211. return false;
  4212. }
  4213. }
  4214. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4215. return true;
  4216. }
  4217. return super.isRedeclaredInScope(...arguments);
  4218. }
  4219. checkLocalExport(id) {
  4220. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4221. super.checkLocalExport(id);
  4222. }
  4223. }
  4224. }
  4225. const PARAM = 0b0000,
  4226. PARAM_YIELD = 0b0001,
  4227. PARAM_AWAIT = 0b0010,
  4228. PARAM_RETURN = 0b0100,
  4229. PARAM_IN = 0b1000;
  4230. class ProductionParameterHandler {
  4231. constructor() {
  4232. this.stacks = [];
  4233. }
  4234. enter(flags) {
  4235. this.stacks.push(flags);
  4236. }
  4237. exit() {
  4238. this.stacks.pop();
  4239. }
  4240. currentFlags() {
  4241. return this.stacks[this.stacks.length - 1];
  4242. }
  4243. get hasAwait() {
  4244. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4245. }
  4246. get hasYield() {
  4247. return (this.currentFlags() & PARAM_YIELD) > 0;
  4248. }
  4249. get hasReturn() {
  4250. return (this.currentFlags() & PARAM_RETURN) > 0;
  4251. }
  4252. get hasIn() {
  4253. return (this.currentFlags() & PARAM_IN) > 0;
  4254. }
  4255. }
  4256. function functionFlags(isAsync, isGenerator) {
  4257. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4258. }
  4259. function nonNull(x) {
  4260. if (x == null) {
  4261. throw new Error(`Unexpected ${x} value.`);
  4262. }
  4263. return x;
  4264. }
  4265. function assert(x) {
  4266. if (!x) {
  4267. throw new Error("Assert fail");
  4268. }
  4269. }
  4270. const TSErrors = Object.freeze({
  4271. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4272. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4273. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  4274. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  4275. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  4276. DuplicateModifier: "Duplicate modifier: '%0'",
  4277. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4278. EmptyTypeArguments: "Type argument list cannot be empty.",
  4279. EmptyTypeParameters: "Type parameter list cannot be empty.",
  4280. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4281. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4282. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4283. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
  4284. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  4285. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  4286. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4287. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4288. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4289. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4290. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4291. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  4292. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4293. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4294. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4295. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4296. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4297. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4298. });
  4299. function keywordTypeFromName(value) {
  4300. switch (value) {
  4301. case "any":
  4302. return "TSAnyKeyword";
  4303. case "boolean":
  4304. return "TSBooleanKeyword";
  4305. case "bigint":
  4306. return "TSBigIntKeyword";
  4307. case "never":
  4308. return "TSNeverKeyword";
  4309. case "number":
  4310. return "TSNumberKeyword";
  4311. case "object":
  4312. return "TSObjectKeyword";
  4313. case "string":
  4314. return "TSStringKeyword";
  4315. case "symbol":
  4316. return "TSSymbolKeyword";
  4317. case "undefined":
  4318. return "TSUndefinedKeyword";
  4319. case "unknown":
  4320. return "TSUnknownKeyword";
  4321. default:
  4322. return undefined;
  4323. }
  4324. }
  4325. var typescript = (superClass => class extends superClass {
  4326. getScopeHandler() {
  4327. return TypeScriptScopeHandler;
  4328. }
  4329. tsIsIdentifier() {
  4330. return this.match(types.name);
  4331. }
  4332. tsNextTokenCanFollowModifier() {
  4333. this.next();
  4334. 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();
  4335. }
  4336. tsParseModifier(allowedModifiers) {
  4337. if (!this.match(types.name)) {
  4338. return undefined;
  4339. }
  4340. const modifier = this.state.value;
  4341. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4342. return modifier;
  4343. }
  4344. return undefined;
  4345. }
  4346. tsParseModifiers(modified, allowedModifiers) {
  4347. for (;;) {
  4348. const startPos = this.state.start;
  4349. const modifier = this.tsParseModifier(allowedModifiers);
  4350. if (!modifier) break;
  4351. if (Object.hasOwnProperty.call(modified, modifier)) {
  4352. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4353. }
  4354. modified[modifier] = true;
  4355. }
  4356. }
  4357. tsIsListTerminator(kind) {
  4358. switch (kind) {
  4359. case "EnumMembers":
  4360. case "TypeMembers":
  4361. return this.match(types.braceR);
  4362. case "HeritageClauseElement":
  4363. return this.match(types.braceL);
  4364. case "TupleElementTypes":
  4365. return this.match(types.bracketR);
  4366. case "TypeParametersOrArguments":
  4367. return this.isRelational(">");
  4368. }
  4369. throw new Error("Unreachable");
  4370. }
  4371. tsParseList(kind, parseElement) {
  4372. const result = [];
  4373. while (!this.tsIsListTerminator(kind)) {
  4374. result.push(parseElement());
  4375. }
  4376. return result;
  4377. }
  4378. tsParseDelimitedList(kind, parseElement) {
  4379. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4380. }
  4381. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4382. const result = [];
  4383. for (;;) {
  4384. if (this.tsIsListTerminator(kind)) {
  4385. break;
  4386. }
  4387. const element = parseElement();
  4388. if (element == null) {
  4389. return undefined;
  4390. }
  4391. result.push(element);
  4392. if (this.eat(types.comma)) {
  4393. continue;
  4394. }
  4395. if (this.tsIsListTerminator(kind)) {
  4396. break;
  4397. }
  4398. if (expectSuccess) {
  4399. this.expect(types.comma);
  4400. }
  4401. return undefined;
  4402. }
  4403. return result;
  4404. }
  4405. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4406. if (!skipFirstToken) {
  4407. if (bracket) {
  4408. this.expect(types.bracketL);
  4409. } else {
  4410. this.expectRelational("<");
  4411. }
  4412. }
  4413. const result = this.tsParseDelimitedList(kind, parseElement);
  4414. if (bracket) {
  4415. this.expect(types.bracketR);
  4416. } else {
  4417. this.expectRelational(">");
  4418. }
  4419. return result;
  4420. }
  4421. tsParseImportType() {
  4422. const node = this.startNode();
  4423. this.expect(types._import);
  4424. this.expect(types.parenL);
  4425. if (!this.match(types.string)) {
  4426. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4427. }
  4428. node.argument = this.parseExprAtom();
  4429. this.expect(types.parenR);
  4430. if (this.eat(types.dot)) {
  4431. node.qualifier = this.tsParseEntityName(true);
  4432. }
  4433. if (this.isRelational("<")) {
  4434. node.typeParameters = this.tsParseTypeArguments();
  4435. }
  4436. return this.finishNode(node, "TSImportType");
  4437. }
  4438. tsParseEntityName(allowReservedWords) {
  4439. let entity = this.parseIdentifier();
  4440. while (this.eat(types.dot)) {
  4441. const node = this.startNodeAtNode(entity);
  4442. node.left = entity;
  4443. node.right = this.parseIdentifier(allowReservedWords);
  4444. entity = this.finishNode(node, "TSQualifiedName");
  4445. }
  4446. return entity;
  4447. }
  4448. tsParseTypeReference() {
  4449. const node = this.startNode();
  4450. node.typeName = this.tsParseEntityName(false);
  4451. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4452. node.typeParameters = this.tsParseTypeArguments();
  4453. }
  4454. return this.finishNode(node, "TSTypeReference");
  4455. }
  4456. tsParseThisTypePredicate(lhs) {
  4457. this.next();
  4458. const node = this.startNodeAtNode(lhs);
  4459. node.parameterName = lhs;
  4460. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4461. node.asserts = false;
  4462. return this.finishNode(node, "TSTypePredicate");
  4463. }
  4464. tsParseThisTypeNode() {
  4465. const node = this.startNode();
  4466. this.next();
  4467. return this.finishNode(node, "TSThisType");
  4468. }
  4469. tsParseTypeQuery() {
  4470. const node = this.startNode();
  4471. this.expect(types._typeof);
  4472. if (this.match(types._import)) {
  4473. node.exprName = this.tsParseImportType();
  4474. } else {
  4475. node.exprName = this.tsParseEntityName(true);
  4476. }
  4477. return this.finishNode(node, "TSTypeQuery");
  4478. }
  4479. tsParseTypeParameter() {
  4480. const node = this.startNode();
  4481. node.name = this.parseIdentifierName(node.start);
  4482. node.constraint = this.tsEatThenParseType(types._extends);
  4483. node.default = this.tsEatThenParseType(types.eq);
  4484. return this.finishNode(node, "TSTypeParameter");
  4485. }
  4486. tsTryParseTypeParameters() {
  4487. if (this.isRelational("<")) {
  4488. return this.tsParseTypeParameters();
  4489. }
  4490. }
  4491. tsParseTypeParameters() {
  4492. const node = this.startNode();
  4493. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4494. this.next();
  4495. } else {
  4496. this.unexpected();
  4497. }
  4498. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4499. if (node.params.length === 0) {
  4500. this.raise(node.start, TSErrors.EmptyTypeParameters);
  4501. }
  4502. return this.finishNode(node, "TSTypeParameterDeclaration");
  4503. }
  4504. tsTryNextParseConstantContext() {
  4505. if (this.lookahead().type === types._const) {
  4506. this.next();
  4507. return this.tsParseTypeReference();
  4508. }
  4509. return null;
  4510. }
  4511. tsFillSignature(returnToken, signature) {
  4512. const returnTokenRequired = returnToken === types.arrow;
  4513. signature.typeParameters = this.tsTryParseTypeParameters();
  4514. this.expect(types.parenL);
  4515. signature.parameters = this.tsParseBindingListForSignature();
  4516. if (returnTokenRequired) {
  4517. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4518. } else if (this.match(returnToken)) {
  4519. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4520. }
  4521. }
  4522. tsParseBindingListForSignature() {
  4523. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4524. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4525. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4526. }
  4527. return pattern;
  4528. });
  4529. }
  4530. tsParseTypeMemberSemicolon() {
  4531. if (!this.eat(types.comma)) {
  4532. this.semicolon();
  4533. }
  4534. }
  4535. tsParseSignatureMember(kind, node) {
  4536. this.tsFillSignature(types.colon, node);
  4537. this.tsParseTypeMemberSemicolon();
  4538. return this.finishNode(node, kind);
  4539. }
  4540. tsIsUnambiguouslyIndexSignature() {
  4541. this.next();
  4542. return this.eat(types.name) && this.match(types.colon);
  4543. }
  4544. tsTryParseIndexSignature(node) {
  4545. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4546. return undefined;
  4547. }
  4548. this.expect(types.bracketL);
  4549. const id = this.parseIdentifier();
  4550. id.typeAnnotation = this.tsParseTypeAnnotation();
  4551. this.resetEndLocation(id);
  4552. this.expect(types.bracketR);
  4553. node.parameters = [id];
  4554. const type = this.tsTryParseTypeAnnotation();
  4555. if (type) node.typeAnnotation = type;
  4556. this.tsParseTypeMemberSemicolon();
  4557. return this.finishNode(node, "TSIndexSignature");
  4558. }
  4559. tsParsePropertyOrMethodSignature(node, readonly) {
  4560. if (this.eat(types.question)) node.optional = true;
  4561. const nodeAny = node;
  4562. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  4563. const method = nodeAny;
  4564. this.tsFillSignature(types.colon, method);
  4565. this.tsParseTypeMemberSemicolon();
  4566. return this.finishNode(method, "TSMethodSignature");
  4567. } else {
  4568. const property = nodeAny;
  4569. if (readonly) property.readonly = true;
  4570. const type = this.tsTryParseTypeAnnotation();
  4571. if (type) property.typeAnnotation = type;
  4572. this.tsParseTypeMemberSemicolon();
  4573. return this.finishNode(property, "TSPropertySignature");
  4574. }
  4575. }
  4576. tsParseTypeMember() {
  4577. const node = this.startNode();
  4578. if (this.match(types.parenL) || this.isRelational("<")) {
  4579. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4580. }
  4581. if (this.match(types._new)) {
  4582. const id = this.startNode();
  4583. this.next();
  4584. if (this.match(types.parenL) || this.isRelational("<")) {
  4585. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4586. } else {
  4587. node.key = this.createIdentifier(id, "new");
  4588. return this.tsParsePropertyOrMethodSignature(node, false);
  4589. }
  4590. }
  4591. const readonly = !!this.tsParseModifier(["readonly"]);
  4592. const idx = this.tsTryParseIndexSignature(node);
  4593. if (idx) {
  4594. if (readonly) node.readonly = true;
  4595. return idx;
  4596. }
  4597. this.parsePropertyName(node, false);
  4598. return this.tsParsePropertyOrMethodSignature(node, readonly);
  4599. }
  4600. tsParseTypeLiteral() {
  4601. const node = this.startNode();
  4602. node.members = this.tsParseObjectTypeMembers();
  4603. return this.finishNode(node, "TSTypeLiteral");
  4604. }
  4605. tsParseObjectTypeMembers() {
  4606. this.expect(types.braceL);
  4607. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4608. this.expect(types.braceR);
  4609. return members;
  4610. }
  4611. tsIsStartOfMappedType() {
  4612. this.next();
  4613. if (this.eat(types.plusMin)) {
  4614. return this.isContextual("readonly");
  4615. }
  4616. if (this.isContextual("readonly")) {
  4617. this.next();
  4618. }
  4619. if (!this.match(types.bracketL)) {
  4620. return false;
  4621. }
  4622. this.next();
  4623. if (!this.tsIsIdentifier()) {
  4624. return false;
  4625. }
  4626. this.next();
  4627. return this.match(types._in);
  4628. }
  4629. tsParseMappedTypeParameter() {
  4630. const node = this.startNode();
  4631. node.name = this.parseIdentifierName(node.start);
  4632. node.constraint = this.tsExpectThenParseType(types._in);
  4633. return this.finishNode(node, "TSTypeParameter");
  4634. }
  4635. tsParseMappedType() {
  4636. const node = this.startNode();
  4637. this.expect(types.braceL);
  4638. if (this.match(types.plusMin)) {
  4639. node.readonly = this.state.value;
  4640. this.next();
  4641. this.expectContextual("readonly");
  4642. } else if (this.eatContextual("readonly")) {
  4643. node.readonly = true;
  4644. }
  4645. this.expect(types.bracketL);
  4646. node.typeParameter = this.tsParseMappedTypeParameter();
  4647. node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
  4648. this.expect(types.bracketR);
  4649. if (this.match(types.plusMin)) {
  4650. node.optional = this.state.value;
  4651. this.next();
  4652. this.expect(types.question);
  4653. } else if (this.eat(types.question)) {
  4654. node.optional = true;
  4655. }
  4656. node.typeAnnotation = this.tsTryParseType();
  4657. this.semicolon();
  4658. this.expect(types.braceR);
  4659. return this.finishNode(node, "TSMappedType");
  4660. }
  4661. tsParseTupleType() {
  4662. const node = this.startNode();
  4663. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4664. let seenOptionalElement = false;
  4665. let labeledElements = null;
  4666. node.elementTypes.forEach(elementNode => {
  4667. var _labeledElements;
  4668. let {
  4669. type
  4670. } = elementNode;
  4671. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  4672. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4673. }
  4674. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  4675. if (type === "TSRestType") {
  4676. elementNode = elementNode.typeAnnotation;
  4677. type = elementNode.type;
  4678. }
  4679. const isLabeled = type === "TSNamedTupleMember";
  4680. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  4681. if (labeledElements !== isLabeled) {
  4682. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  4683. }
  4684. });
  4685. return this.finishNode(node, "TSTupleType");
  4686. }
  4687. tsParseTupleElementType() {
  4688. const {
  4689. start: startPos,
  4690. startLoc
  4691. } = this.state;
  4692. const rest = this.eat(types.ellipsis);
  4693. let type = this.tsParseType();
  4694. const optional = this.eat(types.question);
  4695. const labeled = this.eat(types.colon);
  4696. if (labeled) {
  4697. const labeledNode = this.startNodeAtNode(type);
  4698. labeledNode.optional = optional;
  4699. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  4700. labeledNode.label = type.typeName;
  4701. } else {
  4702. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  4703. labeledNode.label = type;
  4704. }
  4705. labeledNode.elementType = this.tsParseType();
  4706. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  4707. } else if (optional) {
  4708. const optionalTypeNode = this.startNodeAtNode(type);
  4709. optionalTypeNode.typeAnnotation = type;
  4710. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  4711. }
  4712. if (rest) {
  4713. const restNode = this.startNodeAt(startPos, startLoc);
  4714. restNode.typeAnnotation = type;
  4715. type = this.finishNode(restNode, "TSRestType");
  4716. }
  4717. return type;
  4718. }
  4719. tsParseParenthesizedType() {
  4720. const node = this.startNode();
  4721. this.expect(types.parenL);
  4722. node.typeAnnotation = this.tsParseType();
  4723. this.expect(types.parenR);
  4724. return this.finishNode(node, "TSParenthesizedType");
  4725. }
  4726. tsParseFunctionOrConstructorType(type) {
  4727. const node = this.startNode();
  4728. if (type === "TSConstructorType") {
  4729. this.expect(types._new);
  4730. }
  4731. this.tsFillSignature(types.arrow, node);
  4732. return this.finishNode(node, type);
  4733. }
  4734. tsParseLiteralTypeNode() {
  4735. const node = this.startNode();
  4736. node.literal = (() => {
  4737. switch (this.state.type) {
  4738. case types.num:
  4739. case types.bigint:
  4740. case types.string:
  4741. case types._true:
  4742. case types._false:
  4743. return this.parseExprAtom();
  4744. default:
  4745. throw this.unexpected();
  4746. }
  4747. })();
  4748. return this.finishNode(node, "TSLiteralType");
  4749. }
  4750. tsParseTemplateLiteralType() {
  4751. const node = this.startNode();
  4752. node.literal = this.parseTemplate(false);
  4753. return this.finishNode(node, "TSLiteralType");
  4754. }
  4755. parseTemplateSubstitution() {
  4756. if (this.state.inType) return this.tsParseType();
  4757. return super.parseTemplateSubstitution();
  4758. }
  4759. tsParseThisTypeOrThisTypePredicate() {
  4760. const thisKeyword = this.tsParseThisTypeNode();
  4761. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4762. return this.tsParseThisTypePredicate(thisKeyword);
  4763. } else {
  4764. return thisKeyword;
  4765. }
  4766. }
  4767. tsParseNonArrayType() {
  4768. switch (this.state.type) {
  4769. case types.name:
  4770. case types._void:
  4771. case types._null:
  4772. {
  4773. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4774. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4775. const node = this.startNode();
  4776. this.next();
  4777. return this.finishNode(node, type);
  4778. }
  4779. return this.tsParseTypeReference();
  4780. }
  4781. case types.string:
  4782. case types.num:
  4783. case types.bigint:
  4784. case types._true:
  4785. case types._false:
  4786. return this.tsParseLiteralTypeNode();
  4787. case types.plusMin:
  4788. if (this.state.value === "-") {
  4789. const node = this.startNode();
  4790. const nextToken = this.lookahead();
  4791. if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
  4792. throw this.unexpected();
  4793. }
  4794. node.literal = this.parseMaybeUnary();
  4795. return this.finishNode(node, "TSLiteralType");
  4796. }
  4797. break;
  4798. case types._this:
  4799. return this.tsParseThisTypeOrThisTypePredicate();
  4800. case types._typeof:
  4801. return this.tsParseTypeQuery();
  4802. case types._import:
  4803. return this.tsParseImportType();
  4804. case types.braceL:
  4805. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4806. case types.bracketL:
  4807. return this.tsParseTupleType();
  4808. case types.parenL:
  4809. return this.tsParseParenthesizedType();
  4810. case types.backQuote:
  4811. return this.tsParseTemplateLiteralType();
  4812. }
  4813. throw this.unexpected();
  4814. }
  4815. tsParseArrayTypeOrHigher() {
  4816. let type = this.tsParseNonArrayType();
  4817. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4818. if (this.match(types.bracketR)) {
  4819. const node = this.startNodeAtNode(type);
  4820. node.elementType = type;
  4821. this.expect(types.bracketR);
  4822. type = this.finishNode(node, "TSArrayType");
  4823. } else {
  4824. const node = this.startNodeAtNode(type);
  4825. node.objectType = type;
  4826. node.indexType = this.tsParseType();
  4827. this.expect(types.bracketR);
  4828. type = this.finishNode(node, "TSIndexedAccessType");
  4829. }
  4830. }
  4831. return type;
  4832. }
  4833. tsParseTypeOperator(operator) {
  4834. const node = this.startNode();
  4835. this.expectContextual(operator);
  4836. node.operator = operator;
  4837. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4838. if (operator === "readonly") {
  4839. this.tsCheckTypeAnnotationForReadOnly(node);
  4840. }
  4841. return this.finishNode(node, "TSTypeOperator");
  4842. }
  4843. tsCheckTypeAnnotationForReadOnly(node) {
  4844. switch (node.typeAnnotation.type) {
  4845. case "TSTupleType":
  4846. case "TSArrayType":
  4847. return;
  4848. default:
  4849. this.raise(node.start, TSErrors.UnexpectedReadonly);
  4850. }
  4851. }
  4852. tsParseInferType() {
  4853. const node = this.startNode();
  4854. this.expectContextual("infer");
  4855. const typeParameter = this.startNode();
  4856. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4857. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4858. return this.finishNode(node, "TSInferType");
  4859. }
  4860. tsParseTypeOperatorOrHigher() {
  4861. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4862. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4863. }
  4864. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4865. this.eat(operator);
  4866. let type = parseConstituentType();
  4867. if (this.match(operator)) {
  4868. const types = [type];
  4869. while (this.eat(operator)) {
  4870. types.push(parseConstituentType());
  4871. }
  4872. const node = this.startNodeAtNode(type);
  4873. node.types = types;
  4874. type = this.finishNode(node, kind);
  4875. }
  4876. return type;
  4877. }
  4878. tsParseIntersectionTypeOrHigher() {
  4879. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4880. }
  4881. tsParseUnionTypeOrHigher() {
  4882. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4883. }
  4884. tsIsStartOfFunctionType() {
  4885. if (this.isRelational("<")) {
  4886. return true;
  4887. }
  4888. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4889. }
  4890. tsSkipParameterStart() {
  4891. if (this.match(types.name) || this.match(types._this)) {
  4892. this.next();
  4893. return true;
  4894. }
  4895. if (this.match(types.braceL)) {
  4896. let braceStackCounter = 1;
  4897. this.next();
  4898. while (braceStackCounter > 0) {
  4899. if (this.match(types.braceL)) {
  4900. ++braceStackCounter;
  4901. } else if (this.match(types.braceR)) {
  4902. --braceStackCounter;
  4903. }
  4904. this.next();
  4905. }
  4906. return true;
  4907. }
  4908. if (this.match(types.bracketL)) {
  4909. let braceStackCounter = 1;
  4910. this.next();
  4911. while (braceStackCounter > 0) {
  4912. if (this.match(types.bracketL)) {
  4913. ++braceStackCounter;
  4914. } else if (this.match(types.bracketR)) {
  4915. --braceStackCounter;
  4916. }
  4917. this.next();
  4918. }
  4919. return true;
  4920. }
  4921. return false;
  4922. }
  4923. tsIsUnambiguouslyStartOfFunctionType() {
  4924. this.next();
  4925. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4926. return true;
  4927. }
  4928. if (this.tsSkipParameterStart()) {
  4929. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4930. return true;
  4931. }
  4932. if (this.match(types.parenR)) {
  4933. this.next();
  4934. if (this.match(types.arrow)) {
  4935. return true;
  4936. }
  4937. }
  4938. }
  4939. return false;
  4940. }
  4941. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4942. return this.tsInType(() => {
  4943. const t = this.startNode();
  4944. this.expect(returnToken);
  4945. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4946. if (asserts && this.match(types._this)) {
  4947. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4948. if (thisTypePredicate.type === "TSThisType") {
  4949. const node = this.startNodeAtNode(t);
  4950. node.parameterName = thisTypePredicate;
  4951. node.asserts = true;
  4952. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4953. } else {
  4954. thisTypePredicate.asserts = true;
  4955. }
  4956. t.typeAnnotation = thisTypePredicate;
  4957. return this.finishNode(t, "TSTypeAnnotation");
  4958. }
  4959. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4960. if (!typePredicateVariable) {
  4961. if (!asserts) {
  4962. return this.tsParseTypeAnnotation(false, t);
  4963. }
  4964. const node = this.startNodeAtNode(t);
  4965. node.parameterName = this.parseIdentifier();
  4966. node.asserts = asserts;
  4967. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4968. return this.finishNode(t, "TSTypeAnnotation");
  4969. }
  4970. const type = this.tsParseTypeAnnotation(false);
  4971. const node = this.startNodeAtNode(t);
  4972. node.parameterName = typePredicateVariable;
  4973. node.typeAnnotation = type;
  4974. node.asserts = asserts;
  4975. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4976. return this.finishNode(t, "TSTypeAnnotation");
  4977. });
  4978. }
  4979. tsTryParseTypeOrTypePredicateAnnotation() {
  4980. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4981. }
  4982. tsTryParseTypeAnnotation() {
  4983. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4984. }
  4985. tsTryParseType() {
  4986. return this.tsEatThenParseType(types.colon);
  4987. }
  4988. tsParseTypePredicatePrefix() {
  4989. const id = this.parseIdentifier();
  4990. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4991. this.next();
  4992. return id;
  4993. }
  4994. }
  4995. tsParseTypePredicateAsserts() {
  4996. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4997. return false;
  4998. }
  4999. const containsEsc = this.state.containsEsc;
  5000. this.next();
  5001. if (!this.match(types.name) && !this.match(types._this)) {
  5002. return false;
  5003. }
  5004. if (containsEsc) {
  5005. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  5006. }
  5007. return true;
  5008. }
  5009. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  5010. this.tsInType(() => {
  5011. if (eatColon) this.expect(types.colon);
  5012. t.typeAnnotation = this.tsParseType();
  5013. });
  5014. return this.finishNode(t, "TSTypeAnnotation");
  5015. }
  5016. tsParseType() {
  5017. assert(this.state.inType);
  5018. const type = this.tsParseNonConditionalType();
  5019. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  5020. return type;
  5021. }
  5022. const node = this.startNodeAtNode(type);
  5023. node.checkType = type;
  5024. node.extendsType = this.tsParseNonConditionalType();
  5025. this.expect(types.question);
  5026. node.trueType = this.tsParseType();
  5027. this.expect(types.colon);
  5028. node.falseType = this.tsParseType();
  5029. return this.finishNode(node, "TSConditionalType");
  5030. }
  5031. tsParseNonConditionalType() {
  5032. if (this.tsIsStartOfFunctionType()) {
  5033. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  5034. }
  5035. if (this.match(types._new)) {
  5036. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  5037. }
  5038. return this.tsParseUnionTypeOrHigher();
  5039. }
  5040. tsParseTypeAssertion() {
  5041. const node = this.startNode();
  5042. const _const = this.tsTryNextParseConstantContext();
  5043. node.typeAnnotation = _const || this.tsNextThenParseType();
  5044. this.expectRelational(">");
  5045. node.expression = this.parseMaybeUnary();
  5046. return this.finishNode(node, "TSTypeAssertion");
  5047. }
  5048. tsParseHeritageClause(descriptor) {
  5049. const originalStart = this.state.start;
  5050. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  5051. if (!delimitedList.length) {
  5052. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  5053. }
  5054. return delimitedList;
  5055. }
  5056. tsParseExpressionWithTypeArguments() {
  5057. const node = this.startNode();
  5058. node.expression = this.tsParseEntityName(false);
  5059. if (this.isRelational("<")) {
  5060. node.typeParameters = this.tsParseTypeArguments();
  5061. }
  5062. return this.finishNode(node, "TSExpressionWithTypeArguments");
  5063. }
  5064. tsParseInterfaceDeclaration(node) {
  5065. node.id = this.parseIdentifier();
  5066. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  5067. node.typeParameters = this.tsTryParseTypeParameters();
  5068. if (this.eat(types._extends)) {
  5069. node.extends = this.tsParseHeritageClause("extends");
  5070. }
  5071. const body = this.startNode();
  5072. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  5073. node.body = this.finishNode(body, "TSInterfaceBody");
  5074. return this.finishNode(node, "TSInterfaceDeclaration");
  5075. }
  5076. tsParseTypeAliasDeclaration(node) {
  5077. node.id = this.parseIdentifier();
  5078. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  5079. node.typeParameters = this.tsTryParseTypeParameters();
  5080. node.typeAnnotation = this.tsInType(() => {
  5081. this.expect(types.eq);
  5082. if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
  5083. const node = this.startNode();
  5084. this.next();
  5085. return this.finishNode(node, "TSIntrinsicKeyword");
  5086. }
  5087. return this.tsParseType();
  5088. });
  5089. this.semicolon();
  5090. return this.finishNode(node, "TSTypeAliasDeclaration");
  5091. }
  5092. tsInNoContext(cb) {
  5093. const oldContext = this.state.context;
  5094. this.state.context = [oldContext[0]];
  5095. try {
  5096. return cb();
  5097. } finally {
  5098. this.state.context = oldContext;
  5099. }
  5100. }
  5101. tsInType(cb) {
  5102. const oldInType = this.state.inType;
  5103. this.state.inType = true;
  5104. try {
  5105. return cb();
  5106. } finally {
  5107. this.state.inType = oldInType;
  5108. }
  5109. }
  5110. tsEatThenParseType(token) {
  5111. return !this.match(token) ? undefined : this.tsNextThenParseType();
  5112. }
  5113. tsExpectThenParseType(token) {
  5114. return this.tsDoThenParseType(() => this.expect(token));
  5115. }
  5116. tsNextThenParseType() {
  5117. return this.tsDoThenParseType(() => this.next());
  5118. }
  5119. tsDoThenParseType(cb) {
  5120. return this.tsInType(() => {
  5121. cb();
  5122. return this.tsParseType();
  5123. });
  5124. }
  5125. tsParseEnumMember() {
  5126. const node = this.startNode();
  5127. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  5128. if (this.eat(types.eq)) {
  5129. node.initializer = this.parseMaybeAssignAllowIn();
  5130. }
  5131. return this.finishNode(node, "TSEnumMember");
  5132. }
  5133. tsParseEnumDeclaration(node, isConst) {
  5134. if (isConst) node.const = true;
  5135. node.id = this.parseIdentifier();
  5136. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  5137. this.expect(types.braceL);
  5138. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  5139. this.expect(types.braceR);
  5140. return this.finishNode(node, "TSEnumDeclaration");
  5141. }
  5142. tsParseModuleBlock() {
  5143. const node = this.startNode();
  5144. this.scope.enter(SCOPE_OTHER);
  5145. this.expect(types.braceL);
  5146. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  5147. this.scope.exit();
  5148. return this.finishNode(node, "TSModuleBlock");
  5149. }
  5150. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  5151. node.id = this.parseIdentifier();
  5152. if (!nested) {
  5153. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  5154. }
  5155. if (this.eat(types.dot)) {
  5156. const inner = this.startNode();
  5157. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  5158. node.body = inner;
  5159. } else {
  5160. this.scope.enter(SCOPE_TS_MODULE);
  5161. this.prodParam.enter(PARAM);
  5162. node.body = this.tsParseModuleBlock();
  5163. this.prodParam.exit();
  5164. this.scope.exit();
  5165. }
  5166. return this.finishNode(node, "TSModuleDeclaration");
  5167. }
  5168. tsParseAmbientExternalModuleDeclaration(node) {
  5169. if (this.isContextual("global")) {
  5170. node.global = true;
  5171. node.id = this.parseIdentifier();
  5172. } else if (this.match(types.string)) {
  5173. node.id = this.parseExprAtom();
  5174. } else {
  5175. this.unexpected();
  5176. }
  5177. if (this.match(types.braceL)) {
  5178. this.scope.enter(SCOPE_TS_MODULE);
  5179. this.prodParam.enter(PARAM);
  5180. node.body = this.tsParseModuleBlock();
  5181. this.prodParam.exit();
  5182. this.scope.exit();
  5183. } else {
  5184. this.semicolon();
  5185. }
  5186. return this.finishNode(node, "TSModuleDeclaration");
  5187. }
  5188. tsParseImportEqualsDeclaration(node, isExport) {
  5189. node.isExport = isExport || false;
  5190. node.id = this.parseIdentifier();
  5191. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  5192. this.expect(types.eq);
  5193. node.moduleReference = this.tsParseModuleReference();
  5194. this.semicolon();
  5195. return this.finishNode(node, "TSImportEqualsDeclaration");
  5196. }
  5197. tsIsExternalModuleReference() {
  5198. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5199. }
  5200. tsParseModuleReference() {
  5201. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5202. }
  5203. tsParseExternalModuleReference() {
  5204. const node = this.startNode();
  5205. this.expectContextual("require");
  5206. this.expect(types.parenL);
  5207. if (!this.match(types.string)) {
  5208. throw this.unexpected();
  5209. }
  5210. node.expression = this.parseExprAtom();
  5211. this.expect(types.parenR);
  5212. return this.finishNode(node, "TSExternalModuleReference");
  5213. }
  5214. tsLookAhead(f) {
  5215. const state = this.state.clone();
  5216. const res = f();
  5217. this.state = state;
  5218. return res;
  5219. }
  5220. tsTryParseAndCatch(f) {
  5221. const result = this.tryParse(abort => f() || abort());
  5222. if (result.aborted || !result.node) return undefined;
  5223. if (result.error) this.state = result.failState;
  5224. return result.node;
  5225. }
  5226. tsTryParse(f) {
  5227. const state = this.state.clone();
  5228. const result = f();
  5229. if (result !== undefined && result !== false) {
  5230. return result;
  5231. } else {
  5232. this.state = state;
  5233. return undefined;
  5234. }
  5235. }
  5236. tsTryParseDeclare(nany) {
  5237. if (this.isLineTerminator()) {
  5238. return;
  5239. }
  5240. let starttype = this.state.type;
  5241. let kind;
  5242. if (this.isContextual("let")) {
  5243. starttype = types._var;
  5244. kind = "let";
  5245. }
  5246. return this.tsInDeclareContext(() => {
  5247. switch (starttype) {
  5248. case types._function:
  5249. nany.declare = true;
  5250. return this.parseFunctionStatement(nany, false, true);
  5251. case types._class:
  5252. nany.declare = true;
  5253. return this.parseClass(nany, true, false);
  5254. case types._const:
  5255. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5256. this.expect(types._const);
  5257. this.expectContextual("enum");
  5258. return this.tsParseEnumDeclaration(nany, true);
  5259. }
  5260. case types._var:
  5261. kind = kind || this.state.value;
  5262. return this.parseVarStatement(nany, kind);
  5263. case types.name:
  5264. {
  5265. const value = this.state.value;
  5266. if (value === "global") {
  5267. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5268. } else {
  5269. return this.tsParseDeclaration(nany, value, true);
  5270. }
  5271. }
  5272. }
  5273. });
  5274. }
  5275. tsTryParseExportDeclaration() {
  5276. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5277. }
  5278. tsParseExpressionStatement(node, expr) {
  5279. switch (expr.name) {
  5280. case "declare":
  5281. {
  5282. const declaration = this.tsTryParseDeclare(node);
  5283. if (declaration) {
  5284. declaration.declare = true;
  5285. return declaration;
  5286. }
  5287. break;
  5288. }
  5289. case "global":
  5290. if (this.match(types.braceL)) {
  5291. this.scope.enter(SCOPE_TS_MODULE);
  5292. this.prodParam.enter(PARAM);
  5293. const mod = node;
  5294. mod.global = true;
  5295. mod.id = expr;
  5296. mod.body = this.tsParseModuleBlock();
  5297. this.scope.exit();
  5298. this.prodParam.exit();
  5299. return this.finishNode(mod, "TSModuleDeclaration");
  5300. }
  5301. break;
  5302. default:
  5303. return this.tsParseDeclaration(node, expr.name, false);
  5304. }
  5305. }
  5306. tsParseDeclaration(node, value, next) {
  5307. switch (value) {
  5308. case "abstract":
  5309. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  5310. const cls = node;
  5311. cls.abstract = true;
  5312. if (next) {
  5313. this.next();
  5314. if (!this.match(types._class)) {
  5315. this.unexpected(null, types._class);
  5316. }
  5317. }
  5318. return this.parseClass(cls, true, false);
  5319. }
  5320. break;
  5321. case "enum":
  5322. if (next || this.match(types.name)) {
  5323. if (next) this.next();
  5324. return this.tsParseEnumDeclaration(node, false);
  5325. }
  5326. break;
  5327. case "interface":
  5328. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5329. if (next) this.next();
  5330. return this.tsParseInterfaceDeclaration(node);
  5331. }
  5332. break;
  5333. case "module":
  5334. if (next) this.next();
  5335. if (this.match(types.string)) {
  5336. return this.tsParseAmbientExternalModuleDeclaration(node);
  5337. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5338. return this.tsParseModuleOrNamespaceDeclaration(node);
  5339. }
  5340. break;
  5341. case "namespace":
  5342. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5343. if (next) this.next();
  5344. return this.tsParseModuleOrNamespaceDeclaration(node);
  5345. }
  5346. break;
  5347. case "type":
  5348. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5349. if (next) this.next();
  5350. return this.tsParseTypeAliasDeclaration(node);
  5351. }
  5352. break;
  5353. }
  5354. }
  5355. tsCheckLineTerminatorAndMatch(tokenType, next) {
  5356. return (next || this.match(tokenType)) && !this.isLineTerminator();
  5357. }
  5358. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5359. if (!this.isRelational("<")) {
  5360. return undefined;
  5361. }
  5362. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5363. this.state.maybeInArrowParameters = true;
  5364. const res = this.tsTryParseAndCatch(() => {
  5365. const node = this.startNodeAt(startPos, startLoc);
  5366. node.typeParameters = this.tsParseTypeParameters();
  5367. super.parseFunctionParams(node);
  5368. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5369. this.expect(types.arrow);
  5370. return node;
  5371. });
  5372. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5373. if (!res) {
  5374. return undefined;
  5375. }
  5376. return this.parseArrowExpression(res, null, true);
  5377. }
  5378. tsParseTypeArguments() {
  5379. const node = this.startNode();
  5380. node.params = this.tsInType(() => this.tsInNoContext(() => {
  5381. this.expectRelational("<");
  5382. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  5383. }));
  5384. if (node.params.length === 0) {
  5385. this.raise(node.start, TSErrors.EmptyTypeArguments);
  5386. }
  5387. this.state.exprAllowed = false;
  5388. this.expectRelational(">");
  5389. return this.finishNode(node, "TSTypeParameterInstantiation");
  5390. }
  5391. tsIsDeclarationStart() {
  5392. if (this.match(types.name)) {
  5393. switch (this.state.value) {
  5394. case "abstract":
  5395. case "declare":
  5396. case "enum":
  5397. case "interface":
  5398. case "module":
  5399. case "namespace":
  5400. case "type":
  5401. return true;
  5402. }
  5403. }
  5404. return false;
  5405. }
  5406. isExportDefaultSpecifier() {
  5407. if (this.tsIsDeclarationStart()) return false;
  5408. return super.isExportDefaultSpecifier();
  5409. }
  5410. parseAssignableListItem(allowModifiers, decorators) {
  5411. const startPos = this.state.start;
  5412. const startLoc = this.state.startLoc;
  5413. let accessibility;
  5414. let readonly = false;
  5415. if (allowModifiers !== undefined) {
  5416. accessibility = this.parseAccessModifier();
  5417. readonly = !!this.tsParseModifier(["readonly"]);
  5418. if (allowModifiers === false && (accessibility || readonly)) {
  5419. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  5420. }
  5421. }
  5422. const left = this.parseMaybeDefault();
  5423. this.parseAssignableListItemTypes(left);
  5424. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  5425. if (accessibility || readonly) {
  5426. const pp = this.startNodeAt(startPos, startLoc);
  5427. if (decorators.length) {
  5428. pp.decorators = decorators;
  5429. }
  5430. if (accessibility) pp.accessibility = accessibility;
  5431. if (readonly) pp.readonly = readonly;
  5432. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  5433. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  5434. }
  5435. pp.parameter = elt;
  5436. return this.finishNode(pp, "TSParameterProperty");
  5437. }
  5438. if (decorators.length) {
  5439. left.decorators = decorators;
  5440. }
  5441. return elt;
  5442. }
  5443. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5444. if (this.match(types.colon)) {
  5445. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5446. }
  5447. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  5448. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  5449. this.finishNode(node, bodilessType);
  5450. return;
  5451. }
  5452. if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) {
  5453. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  5454. if (node.declare) {
  5455. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  5456. return;
  5457. }
  5458. }
  5459. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5460. }
  5461. registerFunctionStatementId(node) {
  5462. if (!node.body && node.id) {
  5463. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  5464. } else {
  5465. super.registerFunctionStatementId(...arguments);
  5466. }
  5467. }
  5468. tsCheckForInvalidTypeCasts(items) {
  5469. items.forEach(node => {
  5470. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  5471. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  5472. }
  5473. });
  5474. }
  5475. toReferencedList(exprList, isInParens) {
  5476. this.tsCheckForInvalidTypeCasts(exprList);
  5477. return exprList;
  5478. }
  5479. parseArrayLike(...args) {
  5480. const node = super.parseArrayLike(...args);
  5481. if (node.type === "ArrayExpression") {
  5482. this.tsCheckForInvalidTypeCasts(node.elements);
  5483. }
  5484. return node;
  5485. }
  5486. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5487. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5488. this.state.exprAllowed = false;
  5489. this.next();
  5490. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5491. nonNullExpression.expression = base;
  5492. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5493. }
  5494. if (this.isRelational("<")) {
  5495. const result = this.tsTryParseAndCatch(() => {
  5496. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5497. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5498. if (asyncArrowFn) {
  5499. return asyncArrowFn;
  5500. }
  5501. }
  5502. const node = this.startNodeAt(startPos, startLoc);
  5503. node.callee = base;
  5504. const typeArguments = this.tsParseTypeArguments();
  5505. if (typeArguments) {
  5506. if (!noCalls && this.eat(types.parenL)) {
  5507. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5508. this.tsCheckForInvalidTypeCasts(node.arguments);
  5509. node.typeParameters = typeArguments;
  5510. return this.finishCallExpression(node, state.optionalChainMember);
  5511. } else if (this.match(types.backQuote)) {
  5512. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  5513. result.typeParameters = typeArguments;
  5514. return result;
  5515. }
  5516. }
  5517. this.unexpected();
  5518. });
  5519. if (result) return result;
  5520. }
  5521. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5522. }
  5523. parseNewArguments(node) {
  5524. if (this.isRelational("<")) {
  5525. const typeParameters = this.tsTryParseAndCatch(() => {
  5526. const args = this.tsParseTypeArguments();
  5527. if (!this.match(types.parenL)) this.unexpected();
  5528. return args;
  5529. });
  5530. if (typeParameters) {
  5531. node.typeParameters = typeParameters;
  5532. }
  5533. }
  5534. super.parseNewArguments(node);
  5535. }
  5536. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  5537. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5538. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5539. node.expression = left;
  5540. const _const = this.tsTryNextParseConstantContext();
  5541. if (_const) {
  5542. node.typeAnnotation = _const;
  5543. } else {
  5544. node.typeAnnotation = this.tsNextThenParseType();
  5545. }
  5546. this.finishNode(node, "TSAsExpression");
  5547. this.reScan_lt_gt();
  5548. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  5549. }
  5550. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  5551. }
  5552. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5553. checkDuplicateExports() {}
  5554. parseImport(node) {
  5555. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5556. const ahead = this.lookahead();
  5557. if (this.match(types.name) && ahead.type === types.eq) {
  5558. return this.tsParseImportEqualsDeclaration(node);
  5559. }
  5560. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  5561. node.importKind = "type";
  5562. this.next();
  5563. }
  5564. }
  5565. if (!node.importKind) {
  5566. node.importKind = "value";
  5567. }
  5568. const importNode = super.parseImport(node);
  5569. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5570. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5571. }
  5572. return importNode;
  5573. }
  5574. parseExport(node) {
  5575. if (this.match(types._import)) {
  5576. this.expect(types._import);
  5577. return this.tsParseImportEqualsDeclaration(node, true);
  5578. } else if (this.eat(types.eq)) {
  5579. const assign = node;
  5580. assign.expression = this.parseExpression();
  5581. this.semicolon();
  5582. return this.finishNode(assign, "TSExportAssignment");
  5583. } else if (this.eatContextual("as")) {
  5584. const decl = node;
  5585. this.expectContextual("namespace");
  5586. decl.id = this.parseIdentifier();
  5587. this.semicolon();
  5588. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5589. } else {
  5590. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5591. this.next();
  5592. node.exportKind = "type";
  5593. } else {
  5594. node.exportKind = "value";
  5595. }
  5596. return super.parseExport(node);
  5597. }
  5598. }
  5599. isAbstractClass() {
  5600. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5601. }
  5602. parseExportDefaultExpression() {
  5603. if (this.isAbstractClass()) {
  5604. const cls = this.startNode();
  5605. this.next();
  5606. this.parseClass(cls, true, true);
  5607. cls.abstract = true;
  5608. return cls;
  5609. }
  5610. if (this.state.value === "interface") {
  5611. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5612. if (result) return result;
  5613. }
  5614. return super.parseExportDefaultExpression();
  5615. }
  5616. parseStatementContent(context, topLevel) {
  5617. if (this.state.type === types._const) {
  5618. const ahead = this.lookahead();
  5619. if (ahead.type === types.name && ahead.value === "enum") {
  5620. const node = this.startNode();
  5621. this.expect(types._const);
  5622. this.expectContextual("enum");
  5623. return this.tsParseEnumDeclaration(node, true);
  5624. }
  5625. }
  5626. return super.parseStatementContent(context, topLevel);
  5627. }
  5628. parseAccessModifier() {
  5629. return this.tsParseModifier(["public", "protected", "private"]);
  5630. }
  5631. parseClassMember(classBody, member, state) {
  5632. this.tsParseModifiers(member, ["declare"]);
  5633. const accessibility = this.parseAccessModifier();
  5634. if (accessibility) member.accessibility = accessibility;
  5635. this.tsParseModifiers(member, ["declare"]);
  5636. const callParseClassMember = () => {
  5637. super.parseClassMember(classBody, member, state);
  5638. };
  5639. if (member.declare) {
  5640. this.tsInDeclareContext(callParseClassMember);
  5641. } else {
  5642. callParseClassMember();
  5643. }
  5644. }
  5645. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  5646. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5647. const idx = this.tsTryParseIndexSignature(member);
  5648. if (idx) {
  5649. classBody.body.push(idx);
  5650. if (member.abstract) {
  5651. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5652. }
  5653. if (isStatic) {
  5654. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5655. }
  5656. if (member.accessibility) {
  5657. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5658. }
  5659. if (member.declare) {
  5660. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  5661. }
  5662. return;
  5663. }
  5664. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  5665. }
  5666. parsePostMemberNameModifiers(methodOrProp) {
  5667. const optional = this.eat(types.question);
  5668. if (optional) methodOrProp.optional = true;
  5669. if (methodOrProp.readonly && this.match(types.parenL)) {
  5670. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5671. }
  5672. if (methodOrProp.declare && this.match(types.parenL)) {
  5673. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5674. }
  5675. }
  5676. parseExpressionStatement(node, expr) {
  5677. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5678. return decl || super.parseExpressionStatement(node, expr);
  5679. }
  5680. shouldParseExportDeclaration() {
  5681. if (this.tsIsDeclarationStart()) return true;
  5682. return super.shouldParseExportDeclaration();
  5683. }
  5684. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  5685. if (!refNeedsArrowPos || !this.match(types.question)) {
  5686. return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  5687. }
  5688. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  5689. if (!result.node) {
  5690. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5691. return expr;
  5692. }
  5693. if (result.error) this.state = result.failState;
  5694. return result.node;
  5695. }
  5696. parseParenItem(node, startPos, startLoc) {
  5697. node = super.parseParenItem(node, startPos, startLoc);
  5698. if (this.eat(types.question)) {
  5699. node.optional = true;
  5700. this.resetEndLocation(node);
  5701. }
  5702. if (this.match(types.colon)) {
  5703. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5704. typeCastNode.expression = node;
  5705. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5706. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5707. }
  5708. return node;
  5709. }
  5710. parseExportDeclaration(node) {
  5711. const startPos = this.state.start;
  5712. const startLoc = this.state.startLoc;
  5713. const isDeclare = this.eatContextual("declare");
  5714. let declaration;
  5715. if (this.match(types.name)) {
  5716. declaration = this.tsTryParseExportDeclaration();
  5717. }
  5718. if (!declaration) {
  5719. declaration = super.parseExportDeclaration(node);
  5720. }
  5721. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5722. node.exportKind = "type";
  5723. }
  5724. if (declaration && isDeclare) {
  5725. this.resetStartLocation(declaration, startPos, startLoc);
  5726. declaration.declare = true;
  5727. }
  5728. return declaration;
  5729. }
  5730. parseClassId(node, isStatement, optionalId) {
  5731. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5732. return;
  5733. }
  5734. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5735. const typeParameters = this.tsTryParseTypeParameters();
  5736. if (typeParameters) node.typeParameters = typeParameters;
  5737. }
  5738. parseClassPropertyAnnotation(node) {
  5739. if (!node.optional && this.eat(types.bang)) {
  5740. node.definite = true;
  5741. }
  5742. const type = this.tsTryParseTypeAnnotation();
  5743. if (type) node.typeAnnotation = type;
  5744. }
  5745. parseClassProperty(node) {
  5746. this.parseClassPropertyAnnotation(node);
  5747. if (this.state.isDeclareContext && this.match(types.eq)) {
  5748. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5749. }
  5750. return super.parseClassProperty(node);
  5751. }
  5752. parseClassPrivateProperty(node) {
  5753. if (node.abstract) {
  5754. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  5755. }
  5756. if (node.accessibility) {
  5757. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  5758. }
  5759. this.parseClassPropertyAnnotation(node);
  5760. return super.parseClassPrivateProperty(node);
  5761. }
  5762. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5763. const typeParameters = this.tsTryParseTypeParameters();
  5764. if (typeParameters && isConstructor) {
  5765. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  5766. }
  5767. if (typeParameters) method.typeParameters = typeParameters;
  5768. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5769. }
  5770. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5771. const typeParameters = this.tsTryParseTypeParameters();
  5772. if (typeParameters) method.typeParameters = typeParameters;
  5773. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5774. }
  5775. parseClassSuper(node) {
  5776. super.parseClassSuper(node);
  5777. if (node.superClass && this.isRelational("<")) {
  5778. node.superTypeParameters = this.tsParseTypeArguments();
  5779. }
  5780. if (this.eatContextual("implements")) {
  5781. node.implements = this.tsParseHeritageClause("implements");
  5782. }
  5783. }
  5784. parseObjPropValue(prop, ...args) {
  5785. const typeParameters = this.tsTryParseTypeParameters();
  5786. if (typeParameters) prop.typeParameters = typeParameters;
  5787. super.parseObjPropValue(prop, ...args);
  5788. }
  5789. parseFunctionParams(node, allowModifiers) {
  5790. const typeParameters = this.tsTryParseTypeParameters();
  5791. if (typeParameters) node.typeParameters = typeParameters;
  5792. super.parseFunctionParams(node, allowModifiers);
  5793. }
  5794. parseVarId(decl, kind) {
  5795. super.parseVarId(decl, kind);
  5796. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5797. decl.definite = true;
  5798. }
  5799. const type = this.tsTryParseTypeAnnotation();
  5800. if (type) {
  5801. decl.id.typeAnnotation = type;
  5802. this.resetEndLocation(decl.id);
  5803. }
  5804. }
  5805. parseAsyncArrowFromCallExpression(node, call) {
  5806. if (this.match(types.colon)) {
  5807. node.returnType = this.tsParseTypeAnnotation();
  5808. }
  5809. return super.parseAsyncArrowFromCallExpression(node, call);
  5810. }
  5811. parseMaybeAssign(...args) {
  5812. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  5813. let state;
  5814. let jsx;
  5815. let typeCast;
  5816. if (this.match(types.jsxTagStart)) {
  5817. state = this.state.clone();
  5818. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5819. if (!jsx.error) return jsx.node;
  5820. const {
  5821. context
  5822. } = this.state;
  5823. if (context[context.length - 1] === types$1.j_oTag) {
  5824. context.length -= 2;
  5825. } else if (context[context.length - 1] === types$1.j_expr) {
  5826. context.length -= 1;
  5827. }
  5828. }
  5829. if (!((_jsx = jsx) == null ? void 0 : _jsx.error) && !this.isRelational("<")) {
  5830. return super.parseMaybeAssign(...args);
  5831. }
  5832. let typeParameters;
  5833. state = state || this.state.clone();
  5834. const arrow = this.tryParse(abort => {
  5835. var _typeParameters;
  5836. typeParameters = this.tsParseTypeParameters();
  5837. const expr = super.parseMaybeAssign(...args);
  5838. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5839. abort();
  5840. }
  5841. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  5842. this.resetStartLocationFromNode(expr, typeParameters);
  5843. }
  5844. expr.typeParameters = typeParameters;
  5845. return expr;
  5846. }, state);
  5847. if (!arrow.error && !arrow.aborted) return arrow.node;
  5848. if (!jsx) {
  5849. assert(!this.hasPlugin("jsx"));
  5850. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5851. if (!typeCast.error) return typeCast.node;
  5852. }
  5853. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  5854. this.state = jsx.failState;
  5855. return jsx.node;
  5856. }
  5857. if (arrow.node) {
  5858. this.state = arrow.failState;
  5859. return arrow.node;
  5860. }
  5861. if ((_typeCast = typeCast) == null ? void 0 : _typeCast.node) {
  5862. this.state = typeCast.failState;
  5863. return typeCast.node;
  5864. }
  5865. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  5866. if (arrow.thrown) throw arrow.error;
  5867. if ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.thrown) throw typeCast.error;
  5868. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  5869. }
  5870. parseMaybeUnary(refExpressionErrors) {
  5871. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5872. return this.tsParseTypeAssertion();
  5873. } else {
  5874. return super.parseMaybeUnary(refExpressionErrors);
  5875. }
  5876. }
  5877. parseArrow(node) {
  5878. if (this.match(types.colon)) {
  5879. const result = this.tryParse(abort => {
  5880. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5881. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5882. return returnType;
  5883. });
  5884. if (result.aborted) return;
  5885. if (!result.thrown) {
  5886. if (result.error) this.state = result.failState;
  5887. node.returnType = result.node;
  5888. }
  5889. }
  5890. return super.parseArrow(node);
  5891. }
  5892. parseAssignableListItemTypes(param) {
  5893. if (this.eat(types.question)) {
  5894. if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) {
  5895. this.raise(param.start, TSErrors.PatternIsOptional);
  5896. }
  5897. param.optional = true;
  5898. }
  5899. const type = this.tsTryParseTypeAnnotation();
  5900. if (type) param.typeAnnotation = type;
  5901. this.resetEndLocation(param);
  5902. return param;
  5903. }
  5904. toAssignable(node, isLHS = false) {
  5905. switch (node.type) {
  5906. case "TSTypeCastExpression":
  5907. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  5908. case "TSParameterProperty":
  5909. return super.toAssignable(node, isLHS);
  5910. case "TSAsExpression":
  5911. case "TSNonNullExpression":
  5912. case "TSTypeAssertion":
  5913. node.expression = this.toAssignable(node.expression, isLHS);
  5914. return node;
  5915. default:
  5916. return super.toAssignable(node, isLHS);
  5917. }
  5918. }
  5919. checkLVal(expr, contextDescription, ...args) {
  5920. switch (expr.type) {
  5921. case "TSTypeCastExpression":
  5922. return;
  5923. case "TSParameterProperty":
  5924. this.checkLVal(expr.parameter, "parameter property", ...args);
  5925. return;
  5926. case "TSAsExpression":
  5927. case "TSNonNullExpression":
  5928. case "TSTypeAssertion":
  5929. this.checkLVal(expr.expression, contextDescription, ...args);
  5930. return;
  5931. default:
  5932. super.checkLVal(expr, contextDescription, ...args);
  5933. return;
  5934. }
  5935. }
  5936. parseBindingAtom() {
  5937. switch (this.state.type) {
  5938. case types._this:
  5939. return this.parseIdentifier(true);
  5940. default:
  5941. return super.parseBindingAtom();
  5942. }
  5943. }
  5944. parseMaybeDecoratorArguments(expr) {
  5945. if (this.isRelational("<")) {
  5946. const typeArguments = this.tsParseTypeArguments();
  5947. if (this.match(types.parenL)) {
  5948. const call = super.parseMaybeDecoratorArguments(expr);
  5949. call.typeParameters = typeArguments;
  5950. return call;
  5951. }
  5952. this.unexpected(this.state.start, types.parenL);
  5953. }
  5954. return super.parseMaybeDecoratorArguments(expr);
  5955. }
  5956. isClassMethod() {
  5957. return this.isRelational("<") || super.isClassMethod();
  5958. }
  5959. isClassProperty() {
  5960. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5961. }
  5962. parseMaybeDefault(...args) {
  5963. const node = super.parseMaybeDefault(...args);
  5964. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5965. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  5966. }
  5967. return node;
  5968. }
  5969. getTokenFromCode(code) {
  5970. if (this.state.inType && (code === 62 || code === 60)) {
  5971. return this.finishOp(types.relational, 1);
  5972. } else {
  5973. return super.getTokenFromCode(code);
  5974. }
  5975. }
  5976. reScan_lt_gt() {
  5977. if (this.match(types.relational)) {
  5978. const code = this.input.charCodeAt(this.state.start);
  5979. if (code === 60 || code === 62) {
  5980. this.state.pos -= 1;
  5981. this.readToken_lt_gt(code);
  5982. }
  5983. }
  5984. }
  5985. toAssignableList(exprList) {
  5986. for (let i = 0; i < exprList.length; i++) {
  5987. const expr = exprList[i];
  5988. if (!expr) continue;
  5989. switch (expr.type) {
  5990. case "TSTypeCastExpression":
  5991. exprList[i] = this.typeCastToParameter(expr);
  5992. break;
  5993. case "TSAsExpression":
  5994. case "TSTypeAssertion":
  5995. if (!this.state.maybeInArrowParameters) {
  5996. exprList[i] = this.typeCastToParameter(expr);
  5997. } else {
  5998. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  5999. }
  6000. break;
  6001. }
  6002. }
  6003. return super.toAssignableList(...arguments);
  6004. }
  6005. typeCastToParameter(node) {
  6006. node.expression.typeAnnotation = node.typeAnnotation;
  6007. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  6008. return node.expression;
  6009. }
  6010. shouldParseArrow() {
  6011. return this.match(types.colon) || super.shouldParseArrow();
  6012. }
  6013. shouldParseAsyncArrow() {
  6014. return this.match(types.colon) || super.shouldParseAsyncArrow();
  6015. }
  6016. canHaveLeadingDecorator() {
  6017. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  6018. }
  6019. jsxParseOpeningElementAfterName(node) {
  6020. if (this.isRelational("<")) {
  6021. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  6022. if (typeArguments) node.typeParameters = typeArguments;
  6023. }
  6024. return super.jsxParseOpeningElementAfterName(node);
  6025. }
  6026. getGetterSetterExpectedParamCount(method) {
  6027. const baseCount = super.getGetterSetterExpectedParamCount(method);
  6028. const params = this.getObjectOrClassMethodParams(method);
  6029. const firstParam = params[0];
  6030. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  6031. return hasContextParam ? baseCount + 1 : baseCount;
  6032. }
  6033. parseCatchClauseParam() {
  6034. const param = super.parseCatchClauseParam();
  6035. const type = this.tsTryParseTypeAnnotation();
  6036. if (type) {
  6037. param.typeAnnotation = type;
  6038. this.resetEndLocation(param);
  6039. }
  6040. return param;
  6041. }
  6042. tsInDeclareContext(cb) {
  6043. const oldIsDeclareContext = this.state.isDeclareContext;
  6044. this.state.isDeclareContext = true;
  6045. try {
  6046. return cb();
  6047. } finally {
  6048. this.state.isDeclareContext = oldIsDeclareContext;
  6049. }
  6050. }
  6051. });
  6052. types.placeholder = new TokenType("%%", {
  6053. startsExpr: true
  6054. });
  6055. var placeholders = (superClass => class extends superClass {
  6056. parsePlaceholder(expectedNode) {
  6057. if (this.match(types.placeholder)) {
  6058. const node = this.startNode();
  6059. this.next();
  6060. this.assertNoSpace("Unexpected space in placeholder.");
  6061. node.name = super.parseIdentifier(true);
  6062. this.assertNoSpace("Unexpected space in placeholder.");
  6063. this.expect(types.placeholder);
  6064. return this.finishPlaceholder(node, expectedNode);
  6065. }
  6066. }
  6067. finishPlaceholder(node, expectedNode) {
  6068. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  6069. node.expectedNode = expectedNode;
  6070. return isFinished ? node : this.finishNode(node, "Placeholder");
  6071. }
  6072. getTokenFromCode(code) {
  6073. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  6074. return this.finishOp(types.placeholder, 2);
  6075. }
  6076. return super.getTokenFromCode(...arguments);
  6077. }
  6078. parseExprAtom() {
  6079. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  6080. }
  6081. parseIdentifier() {
  6082. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  6083. }
  6084. checkReservedWord(word) {
  6085. if (word !== undefined) super.checkReservedWord(...arguments);
  6086. }
  6087. parseBindingAtom() {
  6088. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  6089. }
  6090. checkLVal(expr) {
  6091. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  6092. }
  6093. toAssignable(node) {
  6094. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  6095. node.expectedNode = "Pattern";
  6096. return node;
  6097. }
  6098. return super.toAssignable(...arguments);
  6099. }
  6100. verifyBreakContinue(node) {
  6101. if (node.label && node.label.type === "Placeholder") return;
  6102. super.verifyBreakContinue(...arguments);
  6103. }
  6104. parseExpressionStatement(node, expr) {
  6105. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  6106. return super.parseExpressionStatement(...arguments);
  6107. }
  6108. if (this.match(types.colon)) {
  6109. const stmt = node;
  6110. stmt.label = this.finishPlaceholder(expr, "Identifier");
  6111. this.next();
  6112. stmt.body = this.parseStatement("label");
  6113. return this.finishNode(stmt, "LabeledStatement");
  6114. }
  6115. this.semicolon();
  6116. node.name = expr.name;
  6117. return this.finishPlaceholder(node, "Statement");
  6118. }
  6119. parseBlock() {
  6120. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  6121. }
  6122. parseFunctionId() {
  6123. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  6124. }
  6125. parseClass(node, isStatement, optionalId) {
  6126. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  6127. this.next();
  6128. this.takeDecorators(node);
  6129. const oldStrict = this.state.strict;
  6130. const placeholder = this.parsePlaceholder("Identifier");
  6131. if (placeholder) {
  6132. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  6133. node.id = placeholder;
  6134. } else if (optionalId || !isStatement) {
  6135. node.id = null;
  6136. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  6137. return this.finishNode(node, type);
  6138. } else {
  6139. this.unexpected(null, "A class name is required");
  6140. }
  6141. } else {
  6142. this.parseClassId(node, isStatement, optionalId);
  6143. }
  6144. this.parseClassSuper(node);
  6145. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  6146. return this.finishNode(node, type);
  6147. }
  6148. parseExport(node) {
  6149. const placeholder = this.parsePlaceholder("Identifier");
  6150. if (!placeholder) return super.parseExport(...arguments);
  6151. if (!this.isContextual("from") && !this.match(types.comma)) {
  6152. node.specifiers = [];
  6153. node.source = null;
  6154. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  6155. return this.finishNode(node, "ExportNamedDeclaration");
  6156. }
  6157. this.expectPlugin("exportDefaultFrom");
  6158. const specifier = this.startNode();
  6159. specifier.exported = placeholder;
  6160. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  6161. return super.parseExport(node);
  6162. }
  6163. isExportDefaultSpecifier() {
  6164. if (this.match(types._default)) {
  6165. const next = this.nextTokenStart();
  6166. if (this.isUnparsedContextual(next, "from")) {
  6167. if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
  6168. return true;
  6169. }
  6170. }
  6171. }
  6172. return super.isExportDefaultSpecifier();
  6173. }
  6174. maybeParseExportDefaultSpecifier(node) {
  6175. if (node.specifiers && node.specifiers.length > 0) {
  6176. return true;
  6177. }
  6178. return super.maybeParseExportDefaultSpecifier(...arguments);
  6179. }
  6180. checkExport(node) {
  6181. const {
  6182. specifiers
  6183. } = node;
  6184. if (specifiers == null ? void 0 : specifiers.length) {
  6185. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  6186. }
  6187. super.checkExport(node);
  6188. node.specifiers = specifiers;
  6189. }
  6190. parseImport(node) {
  6191. const placeholder = this.parsePlaceholder("Identifier");
  6192. if (!placeholder) return super.parseImport(...arguments);
  6193. node.specifiers = [];
  6194. if (!this.isContextual("from") && !this.match(types.comma)) {
  6195. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  6196. this.semicolon();
  6197. return this.finishNode(node, "ImportDeclaration");
  6198. }
  6199. const specifier = this.startNodeAtNode(placeholder);
  6200. specifier.local = placeholder;
  6201. this.finishNode(specifier, "ImportDefaultSpecifier");
  6202. node.specifiers.push(specifier);
  6203. if (this.eat(types.comma)) {
  6204. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  6205. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  6206. }
  6207. this.expectContextual("from");
  6208. node.source = this.parseImportSource();
  6209. this.semicolon();
  6210. return this.finishNode(node, "ImportDeclaration");
  6211. }
  6212. parseImportSource() {
  6213. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  6214. }
  6215. });
  6216. var v8intrinsic = (superClass => class extends superClass {
  6217. parseV8Intrinsic() {
  6218. if (this.match(types.modulo)) {
  6219. const v8IntrinsicStart = this.state.start;
  6220. const node = this.startNode();
  6221. this.eat(types.modulo);
  6222. if (this.match(types.name)) {
  6223. const name = this.parseIdentifierName(this.state.start);
  6224. const identifier = this.createIdentifier(node, name);
  6225. identifier.type = "V8IntrinsicIdentifier";
  6226. if (this.match(types.parenL)) {
  6227. return identifier;
  6228. }
  6229. }
  6230. this.unexpected(v8IntrinsicStart);
  6231. }
  6232. }
  6233. parseExprAtom() {
  6234. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  6235. }
  6236. });
  6237. function hasPlugin(plugins, name) {
  6238. return plugins.some(plugin => {
  6239. if (Array.isArray(plugin)) {
  6240. return plugin[0] === name;
  6241. } else {
  6242. return plugin === name;
  6243. }
  6244. });
  6245. }
  6246. function getPluginOption(plugins, name, option) {
  6247. const plugin = plugins.find(plugin => {
  6248. if (Array.isArray(plugin)) {
  6249. return plugin[0] === name;
  6250. } else {
  6251. return plugin === name;
  6252. }
  6253. });
  6254. if (plugin && Array.isArray(plugin)) {
  6255. return plugin[1][option];
  6256. }
  6257. return null;
  6258. }
  6259. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6260. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6261. function validatePlugins(plugins) {
  6262. if (hasPlugin(plugins, "decorators")) {
  6263. if (hasPlugin(plugins, "decorators-legacy")) {
  6264. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6265. }
  6266. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6267. if (decoratorsBeforeExport == null) {
  6268. 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'.");
  6269. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6270. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6271. }
  6272. }
  6273. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6274. throw new Error("Cannot combine flow and typescript plugins.");
  6275. }
  6276. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6277. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6278. }
  6279. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6280. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6281. }
  6282. if (hasPlugin(plugins, "moduleAttributes")) {
  6283. if (hasPlugin(plugins, "importAssertions")) {
  6284. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  6285. }
  6286. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  6287. if (moduleAttributesVerionPluginOption !== "may-2020") {
  6288. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  6289. }
  6290. }
  6291. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6292. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6293. }
  6294. }
  6295. const mixinPlugins = {
  6296. estree,
  6297. jsx,
  6298. flow,
  6299. typescript,
  6300. v8intrinsic,
  6301. placeholders
  6302. };
  6303. const mixinPluginNames = Object.keys(mixinPlugins);
  6304. const defaultOptions = {
  6305. sourceType: "script",
  6306. sourceFilename: undefined,
  6307. startLine: 1,
  6308. allowAwaitOutsideFunction: false,
  6309. allowReturnOutsideFunction: false,
  6310. allowImportExportEverywhere: false,
  6311. allowSuperOutsideMethod: false,
  6312. allowUndeclaredExports: false,
  6313. plugins: [],
  6314. strictMode: null,
  6315. ranges: false,
  6316. tokens: false,
  6317. createParenthesizedExpressions: false,
  6318. errorRecovery: false
  6319. };
  6320. function getOptions(opts) {
  6321. const options = {};
  6322. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  6323. const key = _Object$keys[_i];
  6324. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6325. }
  6326. return options;
  6327. }
  6328. class State {
  6329. constructor() {
  6330. this.strict = void 0;
  6331. this.curLine = void 0;
  6332. this.startLoc = void 0;
  6333. this.endLoc = void 0;
  6334. this.errors = [];
  6335. this.potentialArrowAt = -1;
  6336. this.noArrowAt = [];
  6337. this.noArrowParamsConversionAt = [];
  6338. this.maybeInArrowParameters = false;
  6339. this.inPipeline = false;
  6340. this.inType = false;
  6341. this.noAnonFunctionType = false;
  6342. this.inPropertyName = false;
  6343. this.hasFlowComment = false;
  6344. this.isIterator = false;
  6345. this.isDeclareContext = false;
  6346. this.topicContext = {
  6347. maxNumOfResolvableTopics: 0,
  6348. maxTopicIndex: null
  6349. };
  6350. this.soloAwait = false;
  6351. this.inFSharpPipelineDirectBody = false;
  6352. this.labels = [];
  6353. this.decoratorStack = [[]];
  6354. this.comments = [];
  6355. this.trailingComments = [];
  6356. this.leadingComments = [];
  6357. this.commentStack = [];
  6358. this.commentPreviousNode = null;
  6359. this.pos = 0;
  6360. this.lineStart = 0;
  6361. this.type = types.eof;
  6362. this.value = null;
  6363. this.start = 0;
  6364. this.end = 0;
  6365. this.lastTokEndLoc = null;
  6366. this.lastTokStartLoc = null;
  6367. this.lastTokStart = 0;
  6368. this.lastTokEnd = 0;
  6369. this.context = [types$1.braceStatement];
  6370. this.exprAllowed = true;
  6371. this.containsEsc = false;
  6372. this.strictErrors = new Map();
  6373. this.exportedIdentifiers = [];
  6374. this.tokensLength = 0;
  6375. }
  6376. init(options) {
  6377. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6378. this.curLine = options.startLine;
  6379. this.startLoc = this.endLoc = this.curPosition();
  6380. }
  6381. curPosition() {
  6382. return new Position(this.curLine, this.pos - this.lineStart);
  6383. }
  6384. clone(skipArrays) {
  6385. const state = new State();
  6386. const keys = Object.keys(this);
  6387. for (let i = 0, length = keys.length; i < length; i++) {
  6388. const key = keys[i];
  6389. let val = this[key];
  6390. if (!skipArrays && Array.isArray(val)) {
  6391. val = val.slice();
  6392. }
  6393. state[key] = val;
  6394. }
  6395. return state;
  6396. }
  6397. }
  6398. var _isDigit = function isDigit(code) {
  6399. return code >= 48 && code <= 57;
  6400. };
  6401. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6402. const forbiddenNumericSeparatorSiblings = {
  6403. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6404. hex: [46, 88, 95, 120]
  6405. };
  6406. const allowedNumericSeparatorSiblings = {};
  6407. allowedNumericSeparatorSiblings.bin = [48, 49];
  6408. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6409. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6410. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6411. class Token {
  6412. constructor(state) {
  6413. this.type = state.type;
  6414. this.value = state.value;
  6415. this.start = state.start;
  6416. this.end = state.end;
  6417. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  6418. }
  6419. }
  6420. class Tokenizer extends ParserError {
  6421. constructor(options, input) {
  6422. super();
  6423. this.isLookahead = void 0;
  6424. this.tokens = [];
  6425. this.state = new State();
  6426. this.state.init(options);
  6427. this.input = input;
  6428. this.length = input.length;
  6429. this.isLookahead = false;
  6430. }
  6431. pushToken(token) {
  6432. this.tokens.length = this.state.tokensLength;
  6433. this.tokens.push(token);
  6434. ++this.state.tokensLength;
  6435. }
  6436. next() {
  6437. if (!this.isLookahead) {
  6438. this.checkKeywordEscapes();
  6439. if (this.options.tokens) {
  6440. this.pushToken(new Token(this.state));
  6441. }
  6442. }
  6443. this.state.lastTokEnd = this.state.end;
  6444. this.state.lastTokStart = this.state.start;
  6445. this.state.lastTokEndLoc = this.state.endLoc;
  6446. this.state.lastTokStartLoc = this.state.startLoc;
  6447. this.nextToken();
  6448. }
  6449. eat(type) {
  6450. if (this.match(type)) {
  6451. this.next();
  6452. return true;
  6453. } else {
  6454. return false;
  6455. }
  6456. }
  6457. match(type) {
  6458. return this.state.type === type;
  6459. }
  6460. lookahead() {
  6461. const old = this.state;
  6462. this.state = old.clone(true);
  6463. this.isLookahead = true;
  6464. this.next();
  6465. this.isLookahead = false;
  6466. const curr = this.state;
  6467. this.state = old;
  6468. return curr;
  6469. }
  6470. nextTokenStart() {
  6471. return this.nextTokenStartSince(this.state.pos);
  6472. }
  6473. nextTokenStartSince(pos) {
  6474. skipWhiteSpace.lastIndex = pos;
  6475. const skip = skipWhiteSpace.exec(this.input);
  6476. return pos + skip[0].length;
  6477. }
  6478. lookaheadCharCode() {
  6479. return this.input.charCodeAt(this.nextTokenStart());
  6480. }
  6481. setStrict(strict) {
  6482. this.state.strict = strict;
  6483. if (strict) {
  6484. this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
  6485. this.state.strictErrors.clear();
  6486. }
  6487. }
  6488. curContext() {
  6489. return this.state.context[this.state.context.length - 1];
  6490. }
  6491. nextToken() {
  6492. const curContext = this.curContext();
  6493. if (!(curContext == null ? void 0 : curContext.preserveSpace)) this.skipSpace();
  6494. this.state.start = this.state.pos;
  6495. this.state.startLoc = this.state.curPosition();
  6496. if (this.state.pos >= this.length) {
  6497. this.finishToken(types.eof);
  6498. return;
  6499. }
  6500. const override = curContext == null ? void 0 : curContext.override;
  6501. if (override) {
  6502. override(this);
  6503. } else {
  6504. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6505. }
  6506. }
  6507. pushComment(block, text, start, end, startLoc, endLoc) {
  6508. const comment = {
  6509. type: block ? "CommentBlock" : "CommentLine",
  6510. value: text,
  6511. start: start,
  6512. end: end,
  6513. loc: new SourceLocation(startLoc, endLoc)
  6514. };
  6515. if (this.options.tokens) this.pushToken(comment);
  6516. this.state.comments.push(comment);
  6517. this.addComment(comment);
  6518. }
  6519. skipBlockComment() {
  6520. const startLoc = this.state.curPosition();
  6521. const start = this.state.pos;
  6522. const end = this.input.indexOf("*/", this.state.pos + 2);
  6523. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  6524. this.state.pos = end + 2;
  6525. lineBreakG.lastIndex = start;
  6526. let match;
  6527. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6528. ++this.state.curLine;
  6529. this.state.lineStart = match.index + match[0].length;
  6530. }
  6531. if (this.isLookahead) return;
  6532. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6533. }
  6534. skipLineComment(startSkip) {
  6535. const start = this.state.pos;
  6536. const startLoc = this.state.curPosition();
  6537. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6538. if (this.state.pos < this.length) {
  6539. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6540. ch = this.input.charCodeAt(this.state.pos);
  6541. }
  6542. }
  6543. if (this.isLookahead) return;
  6544. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6545. }
  6546. skipSpace() {
  6547. loop: while (this.state.pos < this.length) {
  6548. const ch = this.input.charCodeAt(this.state.pos);
  6549. switch (ch) {
  6550. case 32:
  6551. case 160:
  6552. case 9:
  6553. ++this.state.pos;
  6554. break;
  6555. case 13:
  6556. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6557. ++this.state.pos;
  6558. }
  6559. case 10:
  6560. case 8232:
  6561. case 8233:
  6562. ++this.state.pos;
  6563. ++this.state.curLine;
  6564. this.state.lineStart = this.state.pos;
  6565. break;
  6566. case 47:
  6567. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6568. case 42:
  6569. this.skipBlockComment();
  6570. break;
  6571. case 47:
  6572. this.skipLineComment(2);
  6573. break;
  6574. default:
  6575. break loop;
  6576. }
  6577. break;
  6578. default:
  6579. if (isWhitespace(ch)) {
  6580. ++this.state.pos;
  6581. } else {
  6582. break loop;
  6583. }
  6584. }
  6585. }
  6586. }
  6587. finishToken(type, val) {
  6588. this.state.end = this.state.pos;
  6589. this.state.endLoc = this.state.curPosition();
  6590. const prevType = this.state.type;
  6591. this.state.type = type;
  6592. this.state.value = val;
  6593. if (!this.isLookahead) this.updateContext(prevType);
  6594. }
  6595. readToken_numberSign() {
  6596. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6597. return;
  6598. }
  6599. const nextPos = this.state.pos + 1;
  6600. const next = this.input.charCodeAt(nextPos);
  6601. if (next >= 48 && next <= 57) {
  6602. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  6603. }
  6604. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  6605. this.expectPlugin("recordAndTuple");
  6606. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6607. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  6608. }
  6609. if (next === 123) {
  6610. this.finishToken(types.braceHashL);
  6611. } else {
  6612. this.finishToken(types.bracketHashL);
  6613. }
  6614. this.state.pos += 2;
  6615. } else {
  6616. this.finishOp(types.hash, 1);
  6617. }
  6618. }
  6619. readToken_dot() {
  6620. const next = this.input.charCodeAt(this.state.pos + 1);
  6621. if (next >= 48 && next <= 57) {
  6622. this.readNumber(true);
  6623. return;
  6624. }
  6625. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6626. this.state.pos += 3;
  6627. this.finishToken(types.ellipsis);
  6628. } else {
  6629. ++this.state.pos;
  6630. this.finishToken(types.dot);
  6631. }
  6632. }
  6633. readToken_slash() {
  6634. if (this.state.exprAllowed && !this.state.inType) {
  6635. ++this.state.pos;
  6636. this.readRegexp();
  6637. return;
  6638. }
  6639. const next = this.input.charCodeAt(this.state.pos + 1);
  6640. if (next === 61) {
  6641. this.finishOp(types.assign, 2);
  6642. } else {
  6643. this.finishOp(types.slash, 1);
  6644. }
  6645. }
  6646. readToken_interpreter() {
  6647. if (this.state.pos !== 0 || this.length < 2) return false;
  6648. let ch = this.input.charCodeAt(this.state.pos + 1);
  6649. if (ch !== 33) return false;
  6650. const start = this.state.pos;
  6651. this.state.pos += 1;
  6652. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6653. ch = this.input.charCodeAt(this.state.pos);
  6654. }
  6655. const value = this.input.slice(start + 2, this.state.pos);
  6656. this.finishToken(types.interpreterDirective, value);
  6657. return true;
  6658. }
  6659. readToken_mult_modulo(code) {
  6660. let type = code === 42 ? types.star : types.modulo;
  6661. let width = 1;
  6662. let next = this.input.charCodeAt(this.state.pos + 1);
  6663. const exprAllowed = this.state.exprAllowed;
  6664. if (code === 42 && next === 42) {
  6665. width++;
  6666. next = this.input.charCodeAt(this.state.pos + 2);
  6667. type = types.exponent;
  6668. }
  6669. if (next === 61 && !exprAllowed) {
  6670. width++;
  6671. type = types.assign;
  6672. }
  6673. this.finishOp(type, width);
  6674. }
  6675. readToken_pipe_amp(code) {
  6676. const next = this.input.charCodeAt(this.state.pos + 1);
  6677. if (next === code) {
  6678. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6679. this.finishOp(types.assign, 3);
  6680. } else {
  6681. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6682. }
  6683. return;
  6684. }
  6685. if (code === 124) {
  6686. if (next === 62) {
  6687. this.finishOp(types.pipeline, 2);
  6688. return;
  6689. }
  6690. if (this.hasPlugin("recordAndTuple") && next === 125) {
  6691. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6692. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  6693. }
  6694. this.finishOp(types.braceBarR, 2);
  6695. return;
  6696. }
  6697. if (this.hasPlugin("recordAndTuple") && next === 93) {
  6698. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6699. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  6700. }
  6701. this.finishOp(types.bracketBarR, 2);
  6702. return;
  6703. }
  6704. }
  6705. if (next === 61) {
  6706. this.finishOp(types.assign, 2);
  6707. return;
  6708. }
  6709. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6710. }
  6711. readToken_caret() {
  6712. const next = this.input.charCodeAt(this.state.pos + 1);
  6713. if (next === 61) {
  6714. this.finishOp(types.assign, 2);
  6715. } else {
  6716. this.finishOp(types.bitwiseXOR, 1);
  6717. }
  6718. }
  6719. readToken_plus_min(code) {
  6720. const next = this.input.charCodeAt(this.state.pos + 1);
  6721. if (next === code) {
  6722. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
  6723. this.skipLineComment(3);
  6724. this.skipSpace();
  6725. this.nextToken();
  6726. return;
  6727. }
  6728. this.finishOp(types.incDec, 2);
  6729. return;
  6730. }
  6731. if (next === 61) {
  6732. this.finishOp(types.assign, 2);
  6733. } else {
  6734. this.finishOp(types.plusMin, 1);
  6735. }
  6736. }
  6737. readToken_lt_gt(code) {
  6738. const next = this.input.charCodeAt(this.state.pos + 1);
  6739. let size = 1;
  6740. if (next === code) {
  6741. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6742. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6743. this.finishOp(types.assign, size + 1);
  6744. return;
  6745. }
  6746. this.finishOp(types.bitShift, size);
  6747. return;
  6748. }
  6749. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6750. this.skipLineComment(4);
  6751. this.skipSpace();
  6752. this.nextToken();
  6753. return;
  6754. }
  6755. if (next === 61) {
  6756. size = 2;
  6757. }
  6758. this.finishOp(types.relational, size);
  6759. }
  6760. readToken_eq_excl(code) {
  6761. const next = this.input.charCodeAt(this.state.pos + 1);
  6762. if (next === 61) {
  6763. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6764. return;
  6765. }
  6766. if (code === 61 && next === 62) {
  6767. this.state.pos += 2;
  6768. this.finishToken(types.arrow);
  6769. return;
  6770. }
  6771. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6772. }
  6773. readToken_question() {
  6774. const next = this.input.charCodeAt(this.state.pos + 1);
  6775. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6776. if (next === 63) {
  6777. if (next2 === 61) {
  6778. this.finishOp(types.assign, 3);
  6779. } else {
  6780. this.finishOp(types.nullishCoalescing, 2);
  6781. }
  6782. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6783. this.state.pos += 2;
  6784. this.finishToken(types.questionDot);
  6785. } else {
  6786. ++this.state.pos;
  6787. this.finishToken(types.question);
  6788. }
  6789. }
  6790. getTokenFromCode(code) {
  6791. switch (code) {
  6792. case 46:
  6793. this.readToken_dot();
  6794. return;
  6795. case 40:
  6796. ++this.state.pos;
  6797. this.finishToken(types.parenL);
  6798. return;
  6799. case 41:
  6800. ++this.state.pos;
  6801. this.finishToken(types.parenR);
  6802. return;
  6803. case 59:
  6804. ++this.state.pos;
  6805. this.finishToken(types.semi);
  6806. return;
  6807. case 44:
  6808. ++this.state.pos;
  6809. this.finishToken(types.comma);
  6810. return;
  6811. case 91:
  6812. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6813. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6814. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  6815. }
  6816. this.finishToken(types.bracketBarL);
  6817. this.state.pos += 2;
  6818. } else {
  6819. ++this.state.pos;
  6820. this.finishToken(types.bracketL);
  6821. }
  6822. return;
  6823. case 93:
  6824. ++this.state.pos;
  6825. this.finishToken(types.bracketR);
  6826. return;
  6827. case 123:
  6828. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6829. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6830. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  6831. }
  6832. this.finishToken(types.braceBarL);
  6833. this.state.pos += 2;
  6834. } else {
  6835. ++this.state.pos;
  6836. this.finishToken(types.braceL);
  6837. }
  6838. return;
  6839. case 125:
  6840. ++this.state.pos;
  6841. this.finishToken(types.braceR);
  6842. return;
  6843. case 58:
  6844. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6845. this.finishOp(types.doubleColon, 2);
  6846. } else {
  6847. ++this.state.pos;
  6848. this.finishToken(types.colon);
  6849. }
  6850. return;
  6851. case 63:
  6852. this.readToken_question();
  6853. return;
  6854. case 96:
  6855. ++this.state.pos;
  6856. this.finishToken(types.backQuote);
  6857. return;
  6858. case 48:
  6859. {
  6860. const next = this.input.charCodeAt(this.state.pos + 1);
  6861. if (next === 120 || next === 88) {
  6862. this.readRadixNumber(16);
  6863. return;
  6864. }
  6865. if (next === 111 || next === 79) {
  6866. this.readRadixNumber(8);
  6867. return;
  6868. }
  6869. if (next === 98 || next === 66) {
  6870. this.readRadixNumber(2);
  6871. return;
  6872. }
  6873. }
  6874. case 49:
  6875. case 50:
  6876. case 51:
  6877. case 52:
  6878. case 53:
  6879. case 54:
  6880. case 55:
  6881. case 56:
  6882. case 57:
  6883. this.readNumber(false);
  6884. return;
  6885. case 34:
  6886. case 39:
  6887. this.readString(code);
  6888. return;
  6889. case 47:
  6890. this.readToken_slash();
  6891. return;
  6892. case 37:
  6893. case 42:
  6894. this.readToken_mult_modulo(code);
  6895. return;
  6896. case 124:
  6897. case 38:
  6898. this.readToken_pipe_amp(code);
  6899. return;
  6900. case 94:
  6901. this.readToken_caret();
  6902. return;
  6903. case 43:
  6904. case 45:
  6905. this.readToken_plus_min(code);
  6906. return;
  6907. case 60:
  6908. case 62:
  6909. this.readToken_lt_gt(code);
  6910. return;
  6911. case 61:
  6912. case 33:
  6913. this.readToken_eq_excl(code);
  6914. return;
  6915. case 126:
  6916. this.finishOp(types.tilde, 1);
  6917. return;
  6918. case 64:
  6919. ++this.state.pos;
  6920. this.finishToken(types.at);
  6921. return;
  6922. case 35:
  6923. this.readToken_numberSign();
  6924. return;
  6925. case 92:
  6926. this.readWord();
  6927. return;
  6928. default:
  6929. if (isIdentifierStart(code)) {
  6930. this.readWord();
  6931. return;
  6932. }
  6933. }
  6934. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  6935. }
  6936. finishOp(type, size) {
  6937. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6938. this.state.pos += size;
  6939. this.finishToken(type, str);
  6940. }
  6941. readRegexp() {
  6942. const start = this.state.pos;
  6943. let escaped, inClass;
  6944. for (;;) {
  6945. if (this.state.pos >= this.length) {
  6946. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  6947. }
  6948. const ch = this.input.charAt(this.state.pos);
  6949. if (lineBreak.test(ch)) {
  6950. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  6951. }
  6952. if (escaped) {
  6953. escaped = false;
  6954. } else {
  6955. if (ch === "[") {
  6956. inClass = true;
  6957. } else if (ch === "]" && inClass) {
  6958. inClass = false;
  6959. } else if (ch === "/" && !inClass) {
  6960. break;
  6961. }
  6962. escaped = ch === "\\";
  6963. }
  6964. ++this.state.pos;
  6965. }
  6966. const content = this.input.slice(start, this.state.pos);
  6967. ++this.state.pos;
  6968. let mods = "";
  6969. while (this.state.pos < this.length) {
  6970. const char = this.input[this.state.pos];
  6971. const charCode = this.input.codePointAt(this.state.pos);
  6972. if (VALID_REGEX_FLAGS.has(char)) {
  6973. if (mods.indexOf(char) > -1) {
  6974. this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
  6975. }
  6976. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6977. this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
  6978. } else {
  6979. break;
  6980. }
  6981. ++this.state.pos;
  6982. mods += char;
  6983. }
  6984. this.finishToken(types.regexp, {
  6985. pattern: content,
  6986. flags: mods
  6987. });
  6988. }
  6989. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6990. const start = this.state.pos;
  6991. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6992. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6993. let invalid = false;
  6994. let total = 0;
  6995. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  6996. const code = this.input.charCodeAt(this.state.pos);
  6997. let val;
  6998. if (code === 95) {
  6999. const prev = this.input.charCodeAt(this.state.pos - 1);
  7000. const next = this.input.charCodeAt(this.state.pos + 1);
  7001. if (allowedSiblings.indexOf(next) === -1) {
  7002. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7003. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  7004. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7005. }
  7006. if (!allowNumSeparator) {
  7007. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  7008. }
  7009. ++this.state.pos;
  7010. continue;
  7011. }
  7012. if (code >= 97) {
  7013. val = code - 97 + 10;
  7014. } else if (code >= 65) {
  7015. val = code - 65 + 10;
  7016. } else if (_isDigit(code)) {
  7017. val = code - 48;
  7018. } else {
  7019. val = Infinity;
  7020. }
  7021. if (val >= radix) {
  7022. if (this.options.errorRecovery && val <= 9) {
  7023. val = 0;
  7024. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  7025. } else if (forceLen) {
  7026. val = 0;
  7027. invalid = true;
  7028. } else {
  7029. break;
  7030. }
  7031. }
  7032. ++this.state.pos;
  7033. total = total * radix + val;
  7034. }
  7035. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  7036. return null;
  7037. }
  7038. return total;
  7039. }
  7040. readRadixNumber(radix) {
  7041. const start = this.state.pos;
  7042. let isBigInt = false;
  7043. this.state.pos += 2;
  7044. const val = this.readInt(radix);
  7045. if (val == null) {
  7046. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  7047. }
  7048. const next = this.input.charCodeAt(this.state.pos);
  7049. if (next === 110) {
  7050. ++this.state.pos;
  7051. isBigInt = true;
  7052. } else if (next === 109) {
  7053. throw this.raise(start, ErrorMessages.InvalidDecimal);
  7054. }
  7055. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7056. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7057. }
  7058. if (isBigInt) {
  7059. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  7060. this.finishToken(types.bigint, str);
  7061. return;
  7062. }
  7063. this.finishToken(types.num, val);
  7064. }
  7065. readNumber(startsWithDot) {
  7066. const start = this.state.pos;
  7067. let isFloat = false;
  7068. let isBigInt = false;
  7069. let isDecimal = false;
  7070. let hasExponent = false;
  7071. let isOctal = false;
  7072. if (!startsWithDot && this.readInt(10) === null) {
  7073. this.raise(start, ErrorMessages.InvalidNumber);
  7074. }
  7075. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  7076. if (hasLeadingZero) {
  7077. const integer = this.input.slice(start, this.state.pos);
  7078. this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
  7079. if (!this.state.strict) {
  7080. const underscorePos = integer.indexOf("_");
  7081. if (underscorePos > 0) {
  7082. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  7083. }
  7084. }
  7085. isOctal = hasLeadingZero && !/[89]/.test(integer);
  7086. }
  7087. let next = this.input.charCodeAt(this.state.pos);
  7088. if (next === 46 && !isOctal) {
  7089. ++this.state.pos;
  7090. this.readInt(10);
  7091. isFloat = true;
  7092. next = this.input.charCodeAt(this.state.pos);
  7093. }
  7094. if ((next === 69 || next === 101) && !isOctal) {
  7095. next = this.input.charCodeAt(++this.state.pos);
  7096. if (next === 43 || next === 45) {
  7097. ++this.state.pos;
  7098. }
  7099. if (this.readInt(10) === null) {
  7100. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  7101. }
  7102. isFloat = true;
  7103. hasExponent = true;
  7104. next = this.input.charCodeAt(this.state.pos);
  7105. }
  7106. if (next === 110) {
  7107. if (isFloat || hasLeadingZero) {
  7108. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  7109. }
  7110. ++this.state.pos;
  7111. isBigInt = true;
  7112. }
  7113. if (next === 109) {
  7114. this.expectPlugin("decimal", this.state.pos);
  7115. if (hasExponent || hasLeadingZero) {
  7116. this.raise(start, ErrorMessages.InvalidDecimal);
  7117. }
  7118. ++this.state.pos;
  7119. isDecimal = true;
  7120. }
  7121. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7122. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7123. }
  7124. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  7125. if (isBigInt) {
  7126. this.finishToken(types.bigint, str);
  7127. return;
  7128. }
  7129. if (isDecimal) {
  7130. this.finishToken(types.decimal, str);
  7131. return;
  7132. }
  7133. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  7134. this.finishToken(types.num, val);
  7135. }
  7136. readCodePoint(throwOnInvalid) {
  7137. const ch = this.input.charCodeAt(this.state.pos);
  7138. let code;
  7139. if (ch === 123) {
  7140. const codePos = ++this.state.pos;
  7141. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  7142. ++this.state.pos;
  7143. if (code !== null && code > 0x10ffff) {
  7144. if (throwOnInvalid) {
  7145. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  7146. } else {
  7147. return null;
  7148. }
  7149. }
  7150. } else {
  7151. code = this.readHexChar(4, false, throwOnInvalid);
  7152. }
  7153. return code;
  7154. }
  7155. readString(quote) {
  7156. let out = "",
  7157. chunkStart = ++this.state.pos;
  7158. for (;;) {
  7159. if (this.state.pos >= this.length) {
  7160. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7161. }
  7162. const ch = this.input.charCodeAt(this.state.pos);
  7163. if (ch === quote) break;
  7164. if (ch === 92) {
  7165. out += this.input.slice(chunkStart, this.state.pos);
  7166. out += this.readEscapedChar(false);
  7167. chunkStart = this.state.pos;
  7168. } else if (ch === 8232 || ch === 8233) {
  7169. ++this.state.pos;
  7170. ++this.state.curLine;
  7171. this.state.lineStart = this.state.pos;
  7172. } else if (isNewLine(ch)) {
  7173. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7174. } else {
  7175. ++this.state.pos;
  7176. }
  7177. }
  7178. out += this.input.slice(chunkStart, this.state.pos++);
  7179. this.finishToken(types.string, out);
  7180. }
  7181. readTmplToken() {
  7182. let out = "",
  7183. chunkStart = this.state.pos,
  7184. containsInvalid = false;
  7185. for (;;) {
  7186. if (this.state.pos >= this.length) {
  7187. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  7188. }
  7189. const ch = this.input.charCodeAt(this.state.pos);
  7190. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  7191. if (this.state.pos === this.state.start && this.match(types.template)) {
  7192. if (ch === 36) {
  7193. this.state.pos += 2;
  7194. this.finishToken(types.dollarBraceL);
  7195. return;
  7196. } else {
  7197. ++this.state.pos;
  7198. this.finishToken(types.backQuote);
  7199. return;
  7200. }
  7201. }
  7202. out += this.input.slice(chunkStart, this.state.pos);
  7203. this.finishToken(types.template, containsInvalid ? null : out);
  7204. return;
  7205. }
  7206. if (ch === 92) {
  7207. out += this.input.slice(chunkStart, this.state.pos);
  7208. const escaped = this.readEscapedChar(true);
  7209. if (escaped === null) {
  7210. containsInvalid = true;
  7211. } else {
  7212. out += escaped;
  7213. }
  7214. chunkStart = this.state.pos;
  7215. } else if (isNewLine(ch)) {
  7216. out += this.input.slice(chunkStart, this.state.pos);
  7217. ++this.state.pos;
  7218. switch (ch) {
  7219. case 13:
  7220. if (this.input.charCodeAt(this.state.pos) === 10) {
  7221. ++this.state.pos;
  7222. }
  7223. case 10:
  7224. out += "\n";
  7225. break;
  7226. default:
  7227. out += String.fromCharCode(ch);
  7228. break;
  7229. }
  7230. ++this.state.curLine;
  7231. this.state.lineStart = this.state.pos;
  7232. chunkStart = this.state.pos;
  7233. } else {
  7234. ++this.state.pos;
  7235. }
  7236. }
  7237. }
  7238. recordStrictModeErrors(pos, message) {
  7239. if (this.state.strict && !this.state.strictErrors.has(pos)) {
  7240. this.raise(pos, message);
  7241. } else {
  7242. this.state.strictErrors.set(pos, message);
  7243. }
  7244. }
  7245. readEscapedChar(inTemplate) {
  7246. const throwOnInvalid = !inTemplate;
  7247. const ch = this.input.charCodeAt(++this.state.pos);
  7248. ++this.state.pos;
  7249. switch (ch) {
  7250. case 110:
  7251. return "\n";
  7252. case 114:
  7253. return "\r";
  7254. case 120:
  7255. {
  7256. const code = this.readHexChar(2, false, throwOnInvalid);
  7257. return code === null ? null : String.fromCharCode(code);
  7258. }
  7259. case 117:
  7260. {
  7261. const code = this.readCodePoint(throwOnInvalid);
  7262. return code === null ? null : String.fromCodePoint(code);
  7263. }
  7264. case 116:
  7265. return "\t";
  7266. case 98:
  7267. return "\b";
  7268. case 118:
  7269. return "\u000b";
  7270. case 102:
  7271. return "\f";
  7272. case 13:
  7273. if (this.input.charCodeAt(this.state.pos) === 10) {
  7274. ++this.state.pos;
  7275. }
  7276. case 10:
  7277. this.state.lineStart = this.state.pos;
  7278. ++this.state.curLine;
  7279. case 8232:
  7280. case 8233:
  7281. return "";
  7282. case 56:
  7283. case 57:
  7284. if (inTemplate) {
  7285. return null;
  7286. } else {
  7287. this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  7288. }
  7289. default:
  7290. if (ch >= 48 && ch <= 55) {
  7291. const codePos = this.state.pos - 1;
  7292. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  7293. let octalStr = match[0];
  7294. let octal = parseInt(octalStr, 8);
  7295. if (octal > 255) {
  7296. octalStr = octalStr.slice(0, -1);
  7297. octal = parseInt(octalStr, 8);
  7298. }
  7299. this.state.pos += octalStr.length - 1;
  7300. const next = this.input.charCodeAt(this.state.pos);
  7301. if (octalStr !== "0" || next === 56 || next === 57) {
  7302. if (inTemplate) {
  7303. return null;
  7304. } else {
  7305. this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
  7306. }
  7307. }
  7308. return String.fromCharCode(octal);
  7309. }
  7310. return String.fromCharCode(ch);
  7311. }
  7312. }
  7313. readHexChar(len, forceLen, throwOnInvalid) {
  7314. const codePos = this.state.pos;
  7315. const n = this.readInt(16, len, forceLen, false);
  7316. if (n === null) {
  7317. if (throwOnInvalid) {
  7318. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  7319. } else {
  7320. this.state.pos = codePos - 1;
  7321. }
  7322. }
  7323. return n;
  7324. }
  7325. readWord1() {
  7326. let word = "";
  7327. this.state.containsEsc = false;
  7328. const start = this.state.pos;
  7329. let chunkStart = this.state.pos;
  7330. while (this.state.pos < this.length) {
  7331. const ch = this.input.codePointAt(this.state.pos);
  7332. if (isIdentifierChar(ch)) {
  7333. this.state.pos += ch <= 0xffff ? 1 : 2;
  7334. } else if (this.state.isIterator && ch === 64) {
  7335. ++this.state.pos;
  7336. } else if (ch === 92) {
  7337. this.state.containsEsc = true;
  7338. word += this.input.slice(chunkStart, this.state.pos);
  7339. const escStart = this.state.pos;
  7340. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  7341. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  7342. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  7343. continue;
  7344. }
  7345. ++this.state.pos;
  7346. const esc = this.readCodePoint(true);
  7347. if (esc !== null) {
  7348. if (!identifierCheck(esc)) {
  7349. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  7350. }
  7351. word += String.fromCodePoint(esc);
  7352. }
  7353. chunkStart = this.state.pos;
  7354. } else {
  7355. break;
  7356. }
  7357. }
  7358. return word + this.input.slice(chunkStart, this.state.pos);
  7359. }
  7360. isIterator(word) {
  7361. return word === "@@iterator" || word === "@@asyncIterator";
  7362. }
  7363. readWord() {
  7364. const word = this.readWord1();
  7365. const type = keywords.get(word) || types.name;
  7366. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  7367. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word);
  7368. }
  7369. this.finishToken(type, word);
  7370. }
  7371. checkKeywordEscapes() {
  7372. const kw = this.state.type.keyword;
  7373. if (kw && this.state.containsEsc) {
  7374. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
  7375. }
  7376. }
  7377. braceIsBlock(prevType) {
  7378. const parent = this.curContext();
  7379. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  7380. return true;
  7381. }
  7382. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  7383. return !parent.isExpr;
  7384. }
  7385. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  7386. return this.hasPrecedingLineBreak();
  7387. }
  7388. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  7389. return true;
  7390. }
  7391. if (prevType === types.braceL) {
  7392. return parent === types$1.braceStatement;
  7393. }
  7394. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  7395. return false;
  7396. }
  7397. if (prevType === types.relational) {
  7398. return true;
  7399. }
  7400. return !this.state.exprAllowed;
  7401. }
  7402. updateContext(prevType) {
  7403. const type = this.state.type;
  7404. let update;
  7405. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  7406. this.state.exprAllowed = false;
  7407. } else if (update = type.updateContext) {
  7408. update.call(this, prevType);
  7409. } else {
  7410. this.state.exprAllowed = type.beforeExpr;
  7411. }
  7412. }
  7413. }
  7414. class UtilParser extends Tokenizer {
  7415. addExtra(node, key, val) {
  7416. if (!node) return;
  7417. const extra = node.extra = node.extra || {};
  7418. extra[key] = val;
  7419. }
  7420. isRelational(op) {
  7421. return this.match(types.relational) && this.state.value === op;
  7422. }
  7423. expectRelational(op) {
  7424. if (this.isRelational(op)) {
  7425. this.next();
  7426. } else {
  7427. this.unexpected(null, types.relational);
  7428. }
  7429. }
  7430. isContextual(name) {
  7431. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  7432. }
  7433. isUnparsedContextual(nameStart, name) {
  7434. const nameEnd = nameStart + name.length;
  7435. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  7436. }
  7437. isLookaheadContextual(name) {
  7438. const next = this.nextTokenStart();
  7439. return this.isUnparsedContextual(next, name);
  7440. }
  7441. eatContextual(name) {
  7442. return this.isContextual(name) && this.eat(types.name);
  7443. }
  7444. expectContextual(name, message) {
  7445. if (!this.eatContextual(name)) this.unexpected(null, message);
  7446. }
  7447. canInsertSemicolon() {
  7448. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  7449. }
  7450. hasPrecedingLineBreak() {
  7451. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7452. }
  7453. isLineTerminator() {
  7454. return this.eat(types.semi) || this.canInsertSemicolon();
  7455. }
  7456. semicolon() {
  7457. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  7458. }
  7459. expect(type, pos) {
  7460. this.eat(type) || this.unexpected(pos, type);
  7461. }
  7462. assertNoSpace(message = "Unexpected space.") {
  7463. if (this.state.start > this.state.lastTokEnd) {
  7464. this.raise(this.state.lastTokEnd, message);
  7465. }
  7466. }
  7467. unexpected(pos, messageOrType = "Unexpected token") {
  7468. if (typeof messageOrType !== "string") {
  7469. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  7470. }
  7471. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  7472. }
  7473. expectPlugin(name, pos) {
  7474. if (!this.hasPlugin(name)) {
  7475. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7476. missingPlugin: [name]
  7477. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  7478. }
  7479. return true;
  7480. }
  7481. expectOnePlugin(names, pos) {
  7482. if (!names.some(n => this.hasPlugin(n))) {
  7483. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7484. missingPlugin: names
  7485. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  7486. }
  7487. }
  7488. tryParse(fn, oldState = this.state.clone()) {
  7489. const abortSignal = {
  7490. node: null
  7491. };
  7492. try {
  7493. const node = fn((node = null) => {
  7494. abortSignal.node = node;
  7495. throw abortSignal;
  7496. });
  7497. if (this.state.errors.length > oldState.errors.length) {
  7498. const failState = this.state;
  7499. this.state = oldState;
  7500. return {
  7501. node,
  7502. error: failState.errors[oldState.errors.length],
  7503. thrown: false,
  7504. aborted: false,
  7505. failState
  7506. };
  7507. }
  7508. return {
  7509. node,
  7510. error: null,
  7511. thrown: false,
  7512. aborted: false,
  7513. failState: null
  7514. };
  7515. } catch (error) {
  7516. const failState = this.state;
  7517. this.state = oldState;
  7518. if (error instanceof SyntaxError) {
  7519. return {
  7520. node: null,
  7521. error,
  7522. thrown: true,
  7523. aborted: false,
  7524. failState
  7525. };
  7526. }
  7527. if (error === abortSignal) {
  7528. return {
  7529. node: abortSignal.node,
  7530. error: null,
  7531. thrown: false,
  7532. aborted: true,
  7533. failState
  7534. };
  7535. }
  7536. throw error;
  7537. }
  7538. }
  7539. checkExpressionErrors(refExpressionErrors, andThrow) {
  7540. if (!refExpressionErrors) return false;
  7541. const {
  7542. shorthandAssign,
  7543. doubleProto
  7544. } = refExpressionErrors;
  7545. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  7546. if (shorthandAssign >= 0) {
  7547. this.unexpected(shorthandAssign);
  7548. }
  7549. if (doubleProto >= 0) {
  7550. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  7551. }
  7552. }
  7553. isLiteralPropertyName() {
  7554. 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);
  7555. }
  7556. isPrivateName(node) {
  7557. return node.type === "PrivateName";
  7558. }
  7559. getPrivateNameSV(node) {
  7560. return node.id.name;
  7561. }
  7562. hasPropertyAsPrivateName(node) {
  7563. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  7564. }
  7565. isOptionalChain(node) {
  7566. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  7567. }
  7568. isObjectProperty(node) {
  7569. return node.type === "ObjectProperty";
  7570. }
  7571. isObjectMethod(node) {
  7572. return node.type === "ObjectMethod";
  7573. }
  7574. }
  7575. class ExpressionErrors {
  7576. constructor() {
  7577. this.shorthandAssign = -1;
  7578. this.doubleProto = -1;
  7579. }
  7580. }
  7581. class Node {
  7582. constructor(parser, pos, loc) {
  7583. this.type = void 0;
  7584. this.start = void 0;
  7585. this.end = void 0;
  7586. this.loc = void 0;
  7587. this.range = void 0;
  7588. this.leadingComments = void 0;
  7589. this.trailingComments = void 0;
  7590. this.innerComments = void 0;
  7591. this.extra = void 0;
  7592. this.type = "";
  7593. this.start = pos;
  7594. this.end = 0;
  7595. this.loc = new SourceLocation(loc);
  7596. if (parser == null ? void 0 : parser.options.ranges) this.range = [pos, 0];
  7597. if (parser == null ? void 0 : parser.filename) this.loc.filename = parser.filename;
  7598. }
  7599. __clone() {
  7600. const newNode = new Node();
  7601. const keys = Object.keys(this);
  7602. for (let i = 0, length = keys.length; i < length; i++) {
  7603. const key = keys[i];
  7604. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  7605. newNode[key] = this[key];
  7606. }
  7607. }
  7608. return newNode;
  7609. }
  7610. }
  7611. class NodeUtils extends UtilParser {
  7612. startNode() {
  7613. return new Node(this, this.state.start, this.state.startLoc);
  7614. }
  7615. startNodeAt(pos, loc) {
  7616. return new Node(this, pos, loc);
  7617. }
  7618. startNodeAtNode(type) {
  7619. return this.startNodeAt(type.start, type.loc.start);
  7620. }
  7621. finishNode(node, type) {
  7622. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  7623. }
  7624. finishNodeAt(node, type, pos, loc) {
  7625. node.type = type;
  7626. node.end = pos;
  7627. node.loc.end = loc;
  7628. if (this.options.ranges) node.range[1] = pos;
  7629. this.processComment(node);
  7630. return node;
  7631. }
  7632. resetStartLocation(node, start, startLoc) {
  7633. node.start = start;
  7634. node.loc.start = startLoc;
  7635. if (this.options.ranges) node.range[0] = start;
  7636. }
  7637. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  7638. node.end = end;
  7639. node.loc.end = endLoc;
  7640. if (this.options.ranges) node.range[1] = end;
  7641. }
  7642. resetStartLocationFromNode(node, locationNode) {
  7643. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  7644. }
  7645. }
  7646. const unwrapParenthesizedExpression = node => {
  7647. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7648. };
  7649. class LValParser extends NodeUtils {
  7650. toAssignable(node, isLHS = false) {
  7651. var _node$extra, _node$extra3;
  7652. let parenthesized = undefined;
  7653. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  7654. parenthesized = unwrapParenthesizedExpression(node);
  7655. if (isLHS) {
  7656. if (parenthesized.type === "Identifier") {
  7657. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  7658. } else if (parenthesized.type !== "MemberExpression") {
  7659. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  7660. }
  7661. } else {
  7662. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  7663. }
  7664. }
  7665. switch (node.type) {
  7666. case "Identifier":
  7667. case "ObjectPattern":
  7668. case "ArrayPattern":
  7669. case "AssignmentPattern":
  7670. break;
  7671. case "ObjectExpression":
  7672. node.type = "ObjectPattern";
  7673. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7674. var _node$extra2;
  7675. const prop = node.properties[i];
  7676. const isLast = i === last;
  7677. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  7678. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  7679. this.raiseRestNotLast(node.extra.trailingComma);
  7680. }
  7681. }
  7682. break;
  7683. case "ObjectProperty":
  7684. this.toAssignable(node.value, isLHS);
  7685. break;
  7686. case "SpreadElement":
  7687. {
  7688. this.checkToRestConversion(node);
  7689. node.type = "RestElement";
  7690. const arg = node.argument;
  7691. this.toAssignable(arg, isLHS);
  7692. break;
  7693. }
  7694. case "ArrayExpression":
  7695. node.type = "ArrayPattern";
  7696. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  7697. break;
  7698. case "AssignmentExpression":
  7699. if (node.operator !== "=") {
  7700. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  7701. }
  7702. node.type = "AssignmentPattern";
  7703. delete node.operator;
  7704. this.toAssignable(node.left, isLHS);
  7705. break;
  7706. case "ParenthesizedExpression":
  7707. this.toAssignable(parenthesized, isLHS);
  7708. break;
  7709. }
  7710. return node;
  7711. }
  7712. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  7713. if (prop.type === "ObjectMethod") {
  7714. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  7715. this.raise(prop.key.start, error);
  7716. } else if (prop.type === "SpreadElement" && !isLast) {
  7717. this.raiseRestNotLast(prop.start);
  7718. } else {
  7719. this.toAssignable(prop, isLHS);
  7720. }
  7721. }
  7722. toAssignableList(exprList, trailingCommaPos, isLHS) {
  7723. let end = exprList.length;
  7724. if (end) {
  7725. const last = exprList[end - 1];
  7726. if ((last == null ? void 0 : last.type) === "RestElement") {
  7727. --end;
  7728. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  7729. last.type = "RestElement";
  7730. let arg = last.argument;
  7731. this.toAssignable(arg, isLHS);
  7732. arg = unwrapParenthesizedExpression(arg);
  7733. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7734. this.unexpected(arg.start);
  7735. }
  7736. if (trailingCommaPos) {
  7737. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7738. }
  7739. --end;
  7740. }
  7741. }
  7742. for (let i = 0; i < end; i++) {
  7743. const elt = exprList[i];
  7744. if (elt) {
  7745. this.toAssignable(elt, isLHS);
  7746. if (elt.type === "RestElement") {
  7747. this.raiseRestNotLast(elt.start);
  7748. }
  7749. }
  7750. }
  7751. return exprList;
  7752. }
  7753. toReferencedList(exprList, isParenthesizedExpr) {
  7754. return exprList;
  7755. }
  7756. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7757. this.toReferencedList(exprList, isParenthesizedExpr);
  7758. for (let _i = 0; _i < exprList.length; _i++) {
  7759. const expr = exprList[_i];
  7760. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  7761. this.toReferencedListDeep(expr.elements);
  7762. }
  7763. }
  7764. }
  7765. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  7766. const node = this.startNode();
  7767. this.next();
  7768. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  7769. return this.finishNode(node, "SpreadElement");
  7770. }
  7771. parseRestBinding() {
  7772. const node = this.startNode();
  7773. this.next();
  7774. node.argument = this.parseBindingAtom();
  7775. return this.finishNode(node, "RestElement");
  7776. }
  7777. parseBindingAtom() {
  7778. switch (this.state.type) {
  7779. case types.bracketL:
  7780. {
  7781. const node = this.startNode();
  7782. this.next();
  7783. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7784. return this.finishNode(node, "ArrayPattern");
  7785. }
  7786. case types.braceL:
  7787. return this.parseObjectLike(types.braceR, true);
  7788. }
  7789. return this.parseIdentifier();
  7790. }
  7791. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7792. const elts = [];
  7793. let first = true;
  7794. while (!this.eat(close)) {
  7795. if (first) {
  7796. first = false;
  7797. } else {
  7798. this.expect(types.comma);
  7799. }
  7800. if (allowEmpty && this.match(types.comma)) {
  7801. elts.push(null);
  7802. } else if (this.eat(close)) {
  7803. break;
  7804. } else if (this.match(types.ellipsis)) {
  7805. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7806. this.checkCommaAfterRest(closeCharCode);
  7807. this.expect(close);
  7808. break;
  7809. } else {
  7810. const decorators = [];
  7811. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7812. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  7813. }
  7814. while (this.match(types.at)) {
  7815. decorators.push(this.parseDecorator());
  7816. }
  7817. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7818. }
  7819. }
  7820. return elts;
  7821. }
  7822. parseAssignableListItem(allowModifiers, decorators) {
  7823. const left = this.parseMaybeDefault();
  7824. this.parseAssignableListItemTypes(left);
  7825. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7826. if (decorators.length) {
  7827. left.decorators = decorators;
  7828. }
  7829. return elt;
  7830. }
  7831. parseAssignableListItemTypes(param) {
  7832. return param;
  7833. }
  7834. parseMaybeDefault(startPos, startLoc, left) {
  7835. var _startLoc, _startPos, _left;
  7836. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  7837. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  7838. left = (_left = left) != null ? _left : this.parseBindingAtom();
  7839. if (!this.eat(types.eq)) return left;
  7840. const node = this.startNodeAt(startPos, startLoc);
  7841. node.left = left;
  7842. node.right = this.parseMaybeAssignAllowIn();
  7843. return this.finishNode(node, "AssignmentPattern");
  7844. }
  7845. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  7846. switch (expr.type) {
  7847. case "Identifier":
  7848. {
  7849. const {
  7850. name
  7851. } = expr;
  7852. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  7853. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  7854. }
  7855. if (checkClashes) {
  7856. if (checkClashes.has(name)) {
  7857. this.raise(expr.start, ErrorMessages.ParamDupe);
  7858. } else {
  7859. checkClashes.add(name);
  7860. }
  7861. }
  7862. if (disallowLetBinding && name === "let") {
  7863. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  7864. }
  7865. if (!(bindingType & BIND_NONE)) {
  7866. this.scope.declareName(name, bindingType, expr.start);
  7867. }
  7868. break;
  7869. }
  7870. case "MemberExpression":
  7871. if (bindingType !== BIND_NONE) {
  7872. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  7873. }
  7874. break;
  7875. case "ObjectPattern":
  7876. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7877. let prop = _expr$properties[_i2];
  7878. if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
  7879. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  7880. }
  7881. break;
  7882. case "ArrayPattern":
  7883. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7884. const elem = _expr$elements[_i3];
  7885. if (elem) {
  7886. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  7887. }
  7888. }
  7889. break;
  7890. case "AssignmentPattern":
  7891. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  7892. break;
  7893. case "RestElement":
  7894. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  7895. break;
  7896. case "ParenthesizedExpression":
  7897. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  7898. break;
  7899. default:
  7900. {
  7901. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  7902. }
  7903. }
  7904. }
  7905. checkToRestConversion(node) {
  7906. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7907. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  7908. }
  7909. }
  7910. checkCommaAfterRest(close) {
  7911. if (this.match(types.comma)) {
  7912. if (this.lookaheadCharCode() === close) {
  7913. this.raiseTrailingCommaAfterRest(this.state.start);
  7914. } else {
  7915. this.raiseRestNotLast(this.state.start);
  7916. }
  7917. }
  7918. }
  7919. raiseRestNotLast(pos) {
  7920. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  7921. }
  7922. raiseTrailingCommaAfterRest(pos) {
  7923. this.raise(pos, ErrorMessages.RestTrailingComma);
  7924. }
  7925. }
  7926. const kExpression = 0,
  7927. kMaybeArrowParameterDeclaration = 1,
  7928. kMaybeAsyncArrowParameterDeclaration = 2,
  7929. kParameterDeclaration = 3;
  7930. class ExpressionScope {
  7931. constructor(type = kExpression) {
  7932. this.type = void 0;
  7933. this.type = type;
  7934. }
  7935. canBeArrowParameterDeclaration() {
  7936. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  7937. }
  7938. isCertainlyParameterDeclaration() {
  7939. return this.type === kParameterDeclaration;
  7940. }
  7941. }
  7942. class ArrowHeadParsingScope extends ExpressionScope {
  7943. constructor(type) {
  7944. super(type);
  7945. this.errors = new Map();
  7946. }
  7947. recordDeclarationError(pos, message) {
  7948. this.errors.set(pos, message);
  7949. }
  7950. clearDeclarationError(pos) {
  7951. this.errors.delete(pos);
  7952. }
  7953. iterateErrors(iterator) {
  7954. this.errors.forEach(iterator);
  7955. }
  7956. }
  7957. class ExpressionScopeHandler {
  7958. constructor(raise) {
  7959. this.stack = [new ExpressionScope()];
  7960. this.raise = raise;
  7961. }
  7962. enter(scope) {
  7963. this.stack.push(scope);
  7964. }
  7965. exit() {
  7966. this.stack.pop();
  7967. }
  7968. recordParameterInitializerError(pos, message) {
  7969. const {
  7970. stack
  7971. } = this;
  7972. let i = stack.length - 1;
  7973. let scope = stack[i];
  7974. while (!scope.isCertainlyParameterDeclaration()) {
  7975. if (scope.canBeArrowParameterDeclaration()) {
  7976. scope.recordDeclarationError(pos, message);
  7977. } else {
  7978. return;
  7979. }
  7980. scope = stack[--i];
  7981. }
  7982. this.raise(pos, message);
  7983. }
  7984. recordParenthesizedIdentifierError(pos, message) {
  7985. const {
  7986. stack
  7987. } = this;
  7988. const scope = stack[stack.length - 1];
  7989. if (scope.isCertainlyParameterDeclaration()) {
  7990. this.raise(pos, message);
  7991. } else if (scope.canBeArrowParameterDeclaration()) {
  7992. scope.recordDeclarationError(pos, message);
  7993. } else {
  7994. return;
  7995. }
  7996. }
  7997. recordAsyncArrowParametersError(pos, message) {
  7998. const {
  7999. stack
  8000. } = this;
  8001. let i = stack.length - 1;
  8002. let scope = stack[i];
  8003. while (scope.canBeArrowParameterDeclaration()) {
  8004. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  8005. scope.recordDeclarationError(pos, message);
  8006. }
  8007. scope = stack[--i];
  8008. }
  8009. }
  8010. validateAsPattern() {
  8011. const {
  8012. stack
  8013. } = this;
  8014. const currentScope = stack[stack.length - 1];
  8015. if (!currentScope.canBeArrowParameterDeclaration()) return;
  8016. currentScope.iterateErrors((message, pos) => {
  8017. this.raise(pos, message);
  8018. let i = stack.length - 2;
  8019. let scope = stack[i];
  8020. while (scope.canBeArrowParameterDeclaration()) {
  8021. scope.clearDeclarationError(pos);
  8022. scope = stack[--i];
  8023. }
  8024. });
  8025. }
  8026. }
  8027. function newParameterDeclarationScope() {
  8028. return new ExpressionScope(kParameterDeclaration);
  8029. }
  8030. function newArrowHeadScope() {
  8031. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  8032. }
  8033. function newAsyncArrowScope() {
  8034. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  8035. }
  8036. function newExpressionScope() {
  8037. return new ExpressionScope();
  8038. }
  8039. class ExpressionParser extends LValParser {
  8040. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  8041. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  8042. return;
  8043. }
  8044. const key = prop.key;
  8045. const name = key.type === "Identifier" ? key.name : key.value;
  8046. if (name === "__proto__") {
  8047. if (isRecord) {
  8048. this.raise(key.start, ErrorMessages.RecordNoProto);
  8049. return;
  8050. }
  8051. if (protoRef.used) {
  8052. if (refExpressionErrors) {
  8053. if (refExpressionErrors.doubleProto === -1) {
  8054. refExpressionErrors.doubleProto = key.start;
  8055. }
  8056. } else {
  8057. this.raise(key.start, ErrorMessages.DuplicateProto);
  8058. }
  8059. }
  8060. protoRef.used = true;
  8061. }
  8062. }
  8063. shouldExitDescending(expr, potentialArrowAt) {
  8064. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  8065. }
  8066. getExpression() {
  8067. let paramFlags = PARAM;
  8068. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  8069. paramFlags |= PARAM_AWAIT;
  8070. }
  8071. this.scope.enter(SCOPE_PROGRAM);
  8072. this.prodParam.enter(paramFlags);
  8073. this.nextToken();
  8074. const expr = this.parseExpression();
  8075. if (!this.match(types.eof)) {
  8076. this.unexpected();
  8077. }
  8078. expr.comments = this.state.comments;
  8079. expr.errors = this.state.errors;
  8080. return expr;
  8081. }
  8082. parseExpression(disallowIn, refExpressionErrors) {
  8083. if (disallowIn) {
  8084. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8085. }
  8086. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8087. }
  8088. parseExpressionBase(refExpressionErrors) {
  8089. const startPos = this.state.start;
  8090. const startLoc = this.state.startLoc;
  8091. const expr = this.parseMaybeAssign(refExpressionErrors);
  8092. if (this.match(types.comma)) {
  8093. const node = this.startNodeAt(startPos, startLoc);
  8094. node.expressions = [expr];
  8095. while (this.eat(types.comma)) {
  8096. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  8097. }
  8098. this.toReferencedList(node.expressions);
  8099. return this.finishNode(node, "SequenceExpression");
  8100. }
  8101. return expr;
  8102. }
  8103. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8104. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8105. }
  8106. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8107. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8108. }
  8109. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8110. const startPos = this.state.start;
  8111. const startLoc = this.state.startLoc;
  8112. if (this.isContextual("yield")) {
  8113. if (this.prodParam.hasYield) {
  8114. this.state.exprAllowed = true;
  8115. let left = this.parseYield();
  8116. if (afterLeftParse) {
  8117. left = afterLeftParse.call(this, left, startPos, startLoc);
  8118. }
  8119. return left;
  8120. }
  8121. }
  8122. let ownExpressionErrors;
  8123. if (refExpressionErrors) {
  8124. ownExpressionErrors = false;
  8125. } else {
  8126. refExpressionErrors = new ExpressionErrors();
  8127. ownExpressionErrors = true;
  8128. }
  8129. if (this.match(types.parenL) || this.match(types.name)) {
  8130. this.state.potentialArrowAt = this.state.start;
  8131. }
  8132. let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
  8133. if (afterLeftParse) {
  8134. left = afterLeftParse.call(this, left, startPos, startLoc);
  8135. }
  8136. if (this.state.type.isAssign) {
  8137. const node = this.startNodeAt(startPos, startLoc);
  8138. const operator = this.state.value;
  8139. node.operator = operator;
  8140. if (this.match(types.eq)) {
  8141. node.left = this.toAssignable(left, true);
  8142. refExpressionErrors.doubleProto = -1;
  8143. } else {
  8144. node.left = left;
  8145. }
  8146. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  8147. refExpressionErrors.shorthandAssign = -1;
  8148. }
  8149. this.checkLVal(left, "assignment expression");
  8150. this.next();
  8151. node.right = this.parseMaybeAssign();
  8152. return this.finishNode(node, "AssignmentExpression");
  8153. } else if (ownExpressionErrors) {
  8154. this.checkExpressionErrors(refExpressionErrors, true);
  8155. }
  8156. return left;
  8157. }
  8158. parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
  8159. const startPos = this.state.start;
  8160. const startLoc = this.state.startLoc;
  8161. const potentialArrowAt = this.state.potentialArrowAt;
  8162. const expr = this.parseExprOps(refExpressionErrors);
  8163. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8164. return expr;
  8165. }
  8166. return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  8167. }
  8168. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  8169. if (this.eat(types.question)) {
  8170. const node = this.startNodeAt(startPos, startLoc);
  8171. node.test = expr;
  8172. node.consequent = this.parseMaybeAssignAllowIn();
  8173. this.expect(types.colon);
  8174. node.alternate = this.parseMaybeAssign();
  8175. return this.finishNode(node, "ConditionalExpression");
  8176. }
  8177. return expr;
  8178. }
  8179. parseExprOps(refExpressionErrors) {
  8180. const startPos = this.state.start;
  8181. const startLoc = this.state.startLoc;
  8182. const potentialArrowAt = this.state.potentialArrowAt;
  8183. const expr = this.parseMaybeUnary(refExpressionErrors);
  8184. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8185. return expr;
  8186. }
  8187. return this.parseExprOp(expr, startPos, startLoc, -1);
  8188. }
  8189. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8190. let prec = this.state.type.binop;
  8191. if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
  8192. if (prec > minPrec) {
  8193. const op = this.state.type;
  8194. if (op === types.pipeline) {
  8195. this.expectPlugin("pipelineOperator");
  8196. if (this.state.inFSharpPipelineDirectBody) {
  8197. return left;
  8198. }
  8199. this.state.inPipeline = true;
  8200. this.checkPipelineAtInfixOperator(left, leftStartPos);
  8201. }
  8202. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8203. node.left = left;
  8204. node.operator = this.state.value;
  8205. if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  8206. this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  8207. }
  8208. const logical = op === types.logicalOR || op === types.logicalAND;
  8209. const coalesce = op === types.nullishCoalescing;
  8210. if (coalesce) {
  8211. prec = types.logicalAND.binop;
  8212. }
  8213. this.next();
  8214. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  8215. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  8216. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  8217. }
  8218. }
  8219. node.right = this.parseExprOpRightExpr(op, prec);
  8220. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  8221. const nextOp = this.state.type;
  8222. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  8223. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  8224. }
  8225. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8226. }
  8227. }
  8228. return left;
  8229. }
  8230. parseExprOpRightExpr(op, prec) {
  8231. const startPos = this.state.start;
  8232. const startLoc = this.state.startLoc;
  8233. switch (op) {
  8234. case types.pipeline:
  8235. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  8236. case "smart":
  8237. return this.withTopicPermittingContext(() => {
  8238. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  8239. });
  8240. case "fsharp":
  8241. return this.withSoloAwaitPermittingContext(() => {
  8242. return this.parseFSharpPipelineBody(prec);
  8243. });
  8244. }
  8245. default:
  8246. return this.parseExprOpBaseRightExpr(op, prec);
  8247. }
  8248. }
  8249. parseExprOpBaseRightExpr(op, prec) {
  8250. const startPos = this.state.start;
  8251. const startLoc = this.state.startLoc;
  8252. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
  8253. }
  8254. parseMaybeUnary(refExpressionErrors) {
  8255. if (this.isContextual("await") && this.isAwaitAllowed()) {
  8256. return this.parseAwait();
  8257. }
  8258. const update = this.match(types.incDec);
  8259. const node = this.startNode();
  8260. if (this.state.type.prefix) {
  8261. node.operator = this.state.value;
  8262. node.prefix = true;
  8263. if (this.match(types._throw)) {
  8264. this.expectPlugin("throwExpressions");
  8265. }
  8266. const isDelete = this.match(types._delete);
  8267. this.next();
  8268. node.argument = this.parseMaybeUnary();
  8269. this.checkExpressionErrors(refExpressionErrors, true);
  8270. if (this.state.strict && isDelete) {
  8271. const arg = node.argument;
  8272. if (arg.type === "Identifier") {
  8273. this.raise(node.start, ErrorMessages.StrictDelete);
  8274. } else if (this.hasPropertyAsPrivateName(arg)) {
  8275. this.raise(node.start, ErrorMessages.DeletePrivateField);
  8276. }
  8277. }
  8278. if (!update) {
  8279. return this.finishNode(node, "UnaryExpression");
  8280. }
  8281. }
  8282. return this.parseUpdate(node, update, refExpressionErrors);
  8283. }
  8284. parseUpdate(node, update, refExpressionErrors) {
  8285. if (update) {
  8286. this.checkLVal(node.argument, "prefix operation");
  8287. return this.finishNode(node, "UpdateExpression");
  8288. }
  8289. const startPos = this.state.start;
  8290. const startLoc = this.state.startLoc;
  8291. let expr = this.parseExprSubscripts(refExpressionErrors);
  8292. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  8293. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  8294. const node = this.startNodeAt(startPos, startLoc);
  8295. node.operator = this.state.value;
  8296. node.prefix = false;
  8297. node.argument = expr;
  8298. this.checkLVal(expr, "postfix operation");
  8299. this.next();
  8300. expr = this.finishNode(node, "UpdateExpression");
  8301. }
  8302. return expr;
  8303. }
  8304. parseExprSubscripts(refExpressionErrors) {
  8305. const startPos = this.state.start;
  8306. const startLoc = this.state.startLoc;
  8307. const potentialArrowAt = this.state.potentialArrowAt;
  8308. const expr = this.parseExprAtom(refExpressionErrors);
  8309. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8310. return expr;
  8311. }
  8312. return this.parseSubscripts(expr, startPos, startLoc);
  8313. }
  8314. parseSubscripts(base, startPos, startLoc, noCalls) {
  8315. const state = {
  8316. optionalChainMember: false,
  8317. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  8318. stop: false
  8319. };
  8320. do {
  8321. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  8322. state.maybeAsyncArrow = false;
  8323. } while (!state.stop);
  8324. return base;
  8325. }
  8326. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8327. if (!noCalls && this.eat(types.doubleColon)) {
  8328. return this.parseBind(base, startPos, startLoc, noCalls, state);
  8329. } else if (this.match(types.backQuote)) {
  8330. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8331. }
  8332. let optional = false;
  8333. if (this.match(types.questionDot)) {
  8334. if (noCalls && this.lookaheadCharCode() === 40) {
  8335. state.stop = true;
  8336. return base;
  8337. }
  8338. state.optionalChainMember = optional = true;
  8339. this.next();
  8340. }
  8341. if (!noCalls && this.match(types.parenL)) {
  8342. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  8343. } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
  8344. return this.parseMember(base, startPos, startLoc, state, optional);
  8345. } else {
  8346. state.stop = true;
  8347. return base;
  8348. }
  8349. }
  8350. parseMember(base, startPos, startLoc, state, optional) {
  8351. const node = this.startNodeAt(startPos, startLoc);
  8352. const computed = this.eat(types.bracketL);
  8353. node.object = base;
  8354. node.computed = computed;
  8355. const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
  8356. if (this.isPrivateName(property)) {
  8357. if (node.object.type === "Super") {
  8358. this.raise(startPos, ErrorMessages.SuperPrivateField);
  8359. }
  8360. this.classScope.usePrivateName(this.getPrivateNameSV(property), property.start);
  8361. }
  8362. node.property = property;
  8363. if (computed) {
  8364. this.expect(types.bracketR);
  8365. }
  8366. if (state.optionalChainMember) {
  8367. node.optional = optional;
  8368. return this.finishNode(node, "OptionalMemberExpression");
  8369. } else {
  8370. return this.finishNode(node, "MemberExpression");
  8371. }
  8372. }
  8373. parseBind(base, startPos, startLoc, noCalls, state) {
  8374. const node = this.startNodeAt(startPos, startLoc);
  8375. node.object = base;
  8376. node.callee = this.parseNoCallExpr();
  8377. state.stop = true;
  8378. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  8379. }
  8380. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  8381. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8382. this.state.maybeInArrowParameters = true;
  8383. this.next();
  8384. let node = this.startNodeAt(startPos, startLoc);
  8385. node.callee = base;
  8386. if (state.maybeAsyncArrow) {
  8387. this.expressionScope.enter(newAsyncArrowScope());
  8388. }
  8389. if (state.optionalChainMember) {
  8390. node.optional = optional;
  8391. }
  8392. if (optional) {
  8393. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8394. } else {
  8395. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  8396. }
  8397. this.finishCallExpression(node, state.optionalChainMember);
  8398. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  8399. state.stop = true;
  8400. this.expressionScope.validateAsPattern();
  8401. this.expressionScope.exit();
  8402. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  8403. } else {
  8404. if (state.maybeAsyncArrow) {
  8405. this.expressionScope.exit();
  8406. }
  8407. this.toReferencedArguments(node);
  8408. }
  8409. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8410. return node;
  8411. }
  8412. toReferencedArguments(node, isParenthesizedExpr) {
  8413. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  8414. }
  8415. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  8416. const node = this.startNodeAt(startPos, startLoc);
  8417. node.tag = base;
  8418. node.quasi = this.parseTemplate(true);
  8419. if (state.optionalChainMember) {
  8420. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  8421. }
  8422. return this.finishNode(node, "TaggedTemplateExpression");
  8423. }
  8424. atPossibleAsyncArrow(base) {
  8425. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  8426. }
  8427. finishCallExpression(node, optional) {
  8428. if (node.callee.type === "Import") {
  8429. if (node.arguments.length === 2) {
  8430. if (!this.hasPlugin("moduleAttributes")) {
  8431. this.expectPlugin("importAssertions");
  8432. }
  8433. }
  8434. if (node.arguments.length === 0 || node.arguments.length > 2) {
  8435. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  8436. } else {
  8437. for (let _i = 0, _node$arguments = node.arguments; _i < _node$arguments.length; _i++) {
  8438. const arg = _node$arguments[_i];
  8439. if (arg.type === "SpreadElement") {
  8440. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  8441. }
  8442. }
  8443. }
  8444. }
  8445. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  8446. }
  8447. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  8448. const elts = [];
  8449. let first = true;
  8450. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8451. this.state.inFSharpPipelineDirectBody = false;
  8452. while (!this.eat(close)) {
  8453. if (first) {
  8454. first = false;
  8455. } else {
  8456. this.expect(types.comma);
  8457. if (this.match(close)) {
  8458. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  8459. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  8460. }
  8461. if (nodeForExtra) {
  8462. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8463. }
  8464. this.next();
  8465. break;
  8466. }
  8467. }
  8468. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8469. start: 0
  8470. } : undefined, allowPlaceholder));
  8471. }
  8472. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8473. return elts;
  8474. }
  8475. shouldParseAsyncArrow() {
  8476. return this.match(types.arrow) && !this.canInsertSemicolon();
  8477. }
  8478. parseAsyncArrowFromCallExpression(node, call) {
  8479. var _call$extra;
  8480. this.expect(types.arrow);
  8481. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8482. return node;
  8483. }
  8484. parseNoCallExpr() {
  8485. const startPos = this.state.start;
  8486. const startLoc = this.state.startLoc;
  8487. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8488. }
  8489. parseExprAtom(refExpressionErrors) {
  8490. if (this.state.type === types.slash) this.readRegexp();
  8491. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8492. let node;
  8493. switch (this.state.type) {
  8494. case types._super:
  8495. return this.parseSuper();
  8496. case types._import:
  8497. node = this.startNode();
  8498. this.next();
  8499. if (this.match(types.dot)) {
  8500. return this.parseImportMetaProperty(node);
  8501. }
  8502. if (!this.match(types.parenL)) {
  8503. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  8504. }
  8505. return this.finishNode(node, "Import");
  8506. case types._this:
  8507. node = this.startNode();
  8508. this.next();
  8509. return this.finishNode(node, "ThisExpression");
  8510. case types.name:
  8511. {
  8512. const containsEsc = this.state.containsEsc;
  8513. const id = this.parseIdentifier();
  8514. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  8515. if (this.match(types._function)) {
  8516. const last = this.state.context.length - 1;
  8517. if (this.state.context[last] !== types$1.functionStatement) {
  8518. throw new Error("Internal error");
  8519. }
  8520. this.state.context[last] = types$1.functionExpression;
  8521. this.next();
  8522. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  8523. } else if (this.match(types.name)) {
  8524. return this.parseAsyncArrowUnaryFunction(id);
  8525. }
  8526. }
  8527. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8528. this.next();
  8529. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  8530. }
  8531. return id;
  8532. }
  8533. case types._do:
  8534. {
  8535. return this.parseDo();
  8536. }
  8537. case types.regexp:
  8538. {
  8539. const value = this.state.value;
  8540. node = this.parseLiteral(value.value, "RegExpLiteral");
  8541. node.pattern = value.pattern;
  8542. node.flags = value.flags;
  8543. return node;
  8544. }
  8545. case types.num:
  8546. return this.parseLiteral(this.state.value, "NumericLiteral");
  8547. case types.bigint:
  8548. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8549. case types.decimal:
  8550. return this.parseLiteral(this.state.value, "DecimalLiteral");
  8551. case types.string:
  8552. return this.parseLiteral(this.state.value, "StringLiteral");
  8553. case types._null:
  8554. node = this.startNode();
  8555. this.next();
  8556. return this.finishNode(node, "NullLiteral");
  8557. case types._true:
  8558. case types._false:
  8559. return this.parseBooleanLiteral();
  8560. case types.parenL:
  8561. return this.parseParenAndDistinguishExpression(canBeArrow);
  8562. case types.bracketBarL:
  8563. case types.bracketHashL:
  8564. {
  8565. return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
  8566. }
  8567. case types.bracketL:
  8568. {
  8569. return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
  8570. }
  8571. case types.braceBarL:
  8572. case types.braceHashL:
  8573. {
  8574. return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
  8575. }
  8576. case types.braceL:
  8577. {
  8578. return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
  8579. }
  8580. case types._function:
  8581. return this.parseFunctionOrFunctionSent();
  8582. case types.at:
  8583. this.parseDecorators();
  8584. case types._class:
  8585. node = this.startNode();
  8586. this.takeDecorators(node);
  8587. return this.parseClass(node, false);
  8588. case types._new:
  8589. return this.parseNewOrNewTarget();
  8590. case types.backQuote:
  8591. return this.parseTemplate(false);
  8592. case types.doubleColon:
  8593. {
  8594. node = this.startNode();
  8595. this.next();
  8596. node.object = null;
  8597. const callee = node.callee = this.parseNoCallExpr();
  8598. if (callee.type === "MemberExpression") {
  8599. return this.finishNode(node, "BindExpression");
  8600. } else {
  8601. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  8602. }
  8603. }
  8604. case types.hash:
  8605. {
  8606. if (this.state.inPipeline) {
  8607. node = this.startNode();
  8608. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  8609. this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
  8610. }
  8611. this.next();
  8612. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  8613. this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
  8614. }
  8615. this.registerTopicReference();
  8616. return this.finishNode(node, "PipelinePrimaryTopicReference");
  8617. }
  8618. const nextCh = this.input.codePointAt(this.state.end);
  8619. if (isIdentifierStart(nextCh) || nextCh === 92) {
  8620. const start = this.state.start;
  8621. node = this.parseMaybePrivateName(true);
  8622. if (this.match(types._in)) {
  8623. this.expectPlugin("privateIn");
  8624. this.classScope.usePrivateName(node.id.name, node.start);
  8625. } else if (this.hasPlugin("privateIn")) {
  8626. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, node.id.name);
  8627. } else {
  8628. throw this.unexpected(start);
  8629. }
  8630. return node;
  8631. }
  8632. }
  8633. case types.relational:
  8634. {
  8635. if (this.state.value === "<") {
  8636. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  8637. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  8638. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  8639. }
  8640. }
  8641. }
  8642. default:
  8643. throw this.unexpected();
  8644. }
  8645. }
  8646. parseAsyncArrowUnaryFunction(id) {
  8647. const node = this.startNodeAtNode(id);
  8648. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  8649. const params = [this.parseIdentifier()];
  8650. this.prodParam.exit();
  8651. if (this.hasPrecedingLineBreak()) {
  8652. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  8653. }
  8654. this.expect(types.arrow);
  8655. this.parseArrowExpression(node, params, true);
  8656. return node;
  8657. }
  8658. parseDo() {
  8659. this.expectPlugin("doExpressions");
  8660. const node = this.startNode();
  8661. this.next();
  8662. const oldLabels = this.state.labels;
  8663. this.state.labels = [];
  8664. node.body = this.parseBlock();
  8665. this.state.labels = oldLabels;
  8666. return this.finishNode(node, "DoExpression");
  8667. }
  8668. parseSuper() {
  8669. const node = this.startNode();
  8670. this.next();
  8671. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  8672. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  8673. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  8674. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  8675. }
  8676. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  8677. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  8678. }
  8679. return this.finishNode(node, "Super");
  8680. }
  8681. parseBooleanLiteral() {
  8682. const node = this.startNode();
  8683. node.value = this.match(types._true);
  8684. this.next();
  8685. return this.finishNode(node, "BooleanLiteral");
  8686. }
  8687. parseMaybePrivateName(isPrivateNameAllowed) {
  8688. const isPrivate = this.match(types.hash);
  8689. if (isPrivate) {
  8690. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  8691. if (!isPrivateNameAllowed) {
  8692. this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
  8693. }
  8694. const node = this.startNode();
  8695. this.next();
  8696. this.assertNoSpace("Unexpected space between # and identifier");
  8697. node.id = this.parseIdentifier(true);
  8698. return this.finishNode(node, "PrivateName");
  8699. } else {
  8700. return this.parseIdentifier(true);
  8701. }
  8702. }
  8703. parseFunctionOrFunctionSent() {
  8704. const node = this.startNode();
  8705. this.next();
  8706. if (this.prodParam.hasYield && this.match(types.dot)) {
  8707. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  8708. this.next();
  8709. return this.parseMetaProperty(node, meta, "sent");
  8710. }
  8711. return this.parseFunction(node);
  8712. }
  8713. parseMetaProperty(node, meta, propertyName) {
  8714. node.meta = meta;
  8715. if (meta.name === "function" && propertyName === "sent") {
  8716. if (this.isContextual(propertyName)) {
  8717. this.expectPlugin("functionSent");
  8718. } else if (!this.hasPlugin("functionSent")) {
  8719. this.unexpected();
  8720. }
  8721. }
  8722. const containsEsc = this.state.containsEsc;
  8723. node.property = this.parseIdentifier(true);
  8724. if (node.property.name !== propertyName || containsEsc) {
  8725. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  8726. }
  8727. return this.finishNode(node, "MetaProperty");
  8728. }
  8729. parseImportMetaProperty(node) {
  8730. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  8731. this.next();
  8732. if (this.isContextual("meta")) {
  8733. if (!this.inModule) {
  8734. this.raiseWithData(id.start, {
  8735. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8736. }, ErrorMessages.ImportMetaOutsideModule);
  8737. }
  8738. this.sawUnambiguousESM = true;
  8739. }
  8740. return this.parseMetaProperty(node, id, "meta");
  8741. }
  8742. parseLiteral(value, type, startPos, startLoc) {
  8743. startPos = startPos || this.state.start;
  8744. startLoc = startLoc || this.state.startLoc;
  8745. const node = this.startNodeAt(startPos, startLoc);
  8746. this.addExtra(node, "rawValue", value);
  8747. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  8748. node.value = value;
  8749. this.next();
  8750. return this.finishNode(node, type);
  8751. }
  8752. parseParenAndDistinguishExpression(canBeArrow) {
  8753. const startPos = this.state.start;
  8754. const startLoc = this.state.startLoc;
  8755. let val;
  8756. this.next();
  8757. this.expressionScope.enter(newArrowHeadScope());
  8758. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8759. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8760. this.state.maybeInArrowParameters = true;
  8761. this.state.inFSharpPipelineDirectBody = false;
  8762. const innerStartPos = this.state.start;
  8763. const innerStartLoc = this.state.startLoc;
  8764. const exprList = [];
  8765. const refExpressionErrors = new ExpressionErrors();
  8766. const refNeedsArrowPos = {
  8767. start: 0
  8768. };
  8769. let first = true;
  8770. let spreadStart;
  8771. let optionalCommaStart;
  8772. while (!this.match(types.parenR)) {
  8773. if (first) {
  8774. first = false;
  8775. } else {
  8776. this.expect(types.comma, refNeedsArrowPos.start || null);
  8777. if (this.match(types.parenR)) {
  8778. optionalCommaStart = this.state.start;
  8779. break;
  8780. }
  8781. }
  8782. if (this.match(types.ellipsis)) {
  8783. const spreadNodeStartPos = this.state.start;
  8784. const spreadNodeStartLoc = this.state.startLoc;
  8785. spreadStart = this.state.start;
  8786. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  8787. this.checkCommaAfterRest(41);
  8788. break;
  8789. } else {
  8790. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  8791. }
  8792. }
  8793. const innerEndPos = this.state.lastTokEnd;
  8794. const innerEndLoc = this.state.lastTokEndLoc;
  8795. this.expect(types.parenR);
  8796. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8797. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8798. let arrowNode = this.startNodeAt(startPos, startLoc);
  8799. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  8800. this.expressionScope.validateAsPattern();
  8801. this.expressionScope.exit();
  8802. this.parseArrowExpression(arrowNode, exprList, false);
  8803. return arrowNode;
  8804. }
  8805. this.expressionScope.exit();
  8806. if (!exprList.length) {
  8807. this.unexpected(this.state.lastTokStart);
  8808. }
  8809. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8810. if (spreadStart) this.unexpected(spreadStart);
  8811. this.checkExpressionErrors(refExpressionErrors, true);
  8812. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8813. this.toReferencedListDeep(exprList, true);
  8814. if (exprList.length > 1) {
  8815. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8816. val.expressions = exprList;
  8817. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8818. } else {
  8819. val = exprList[0];
  8820. }
  8821. if (!this.options.createParenthesizedExpressions) {
  8822. this.addExtra(val, "parenthesized", true);
  8823. this.addExtra(val, "parenStart", startPos);
  8824. return val;
  8825. }
  8826. const parenExpression = this.startNodeAt(startPos, startLoc);
  8827. parenExpression.expression = val;
  8828. this.finishNode(parenExpression, "ParenthesizedExpression");
  8829. return parenExpression;
  8830. }
  8831. shouldParseArrow() {
  8832. return !this.canInsertSemicolon();
  8833. }
  8834. parseArrow(node) {
  8835. if (this.eat(types.arrow)) {
  8836. return node;
  8837. }
  8838. }
  8839. parseParenItem(node, startPos, startLoc) {
  8840. return node;
  8841. }
  8842. parseNewOrNewTarget() {
  8843. const node = this.startNode();
  8844. this.next();
  8845. if (this.match(types.dot)) {
  8846. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  8847. this.next();
  8848. const metaProp = this.parseMetaProperty(node, meta, "target");
  8849. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  8850. let error = ErrorMessages.UnexpectedNewTarget;
  8851. if (this.hasPlugin("classProperties")) {
  8852. error += " or class properties";
  8853. }
  8854. this.raise(metaProp.start, error);
  8855. }
  8856. return metaProp;
  8857. }
  8858. return this.parseNew(node);
  8859. }
  8860. parseNew(node) {
  8861. node.callee = this.parseNoCallExpr();
  8862. if (node.callee.type === "Import") {
  8863. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  8864. } else if (this.isOptionalChain(node.callee)) {
  8865. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  8866. } else if (this.eat(types.questionDot)) {
  8867. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  8868. }
  8869. this.parseNewArguments(node);
  8870. return this.finishNode(node, "NewExpression");
  8871. }
  8872. parseNewArguments(node) {
  8873. if (this.eat(types.parenL)) {
  8874. const args = this.parseExprList(types.parenR);
  8875. this.toReferencedList(args);
  8876. node.arguments = args;
  8877. } else {
  8878. node.arguments = [];
  8879. }
  8880. }
  8881. parseTemplateElement(isTagged) {
  8882. const elem = this.startNode();
  8883. if (this.state.value === null) {
  8884. if (!isTagged) {
  8885. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  8886. }
  8887. }
  8888. elem.value = {
  8889. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8890. cooked: this.state.value
  8891. };
  8892. this.next();
  8893. elem.tail = this.match(types.backQuote);
  8894. return this.finishNode(elem, "TemplateElement");
  8895. }
  8896. parseTemplate(isTagged) {
  8897. const node = this.startNode();
  8898. this.next();
  8899. node.expressions = [];
  8900. let curElt = this.parseTemplateElement(isTagged);
  8901. node.quasis = [curElt];
  8902. while (!curElt.tail) {
  8903. this.expect(types.dollarBraceL);
  8904. node.expressions.push(this.parseTemplateSubstitution());
  8905. this.expect(types.braceR);
  8906. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8907. }
  8908. this.next();
  8909. return this.finishNode(node, "TemplateLiteral");
  8910. }
  8911. parseTemplateSubstitution() {
  8912. return this.parseExpression();
  8913. }
  8914. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  8915. if (isRecord) {
  8916. this.expectPlugin("recordAndTuple");
  8917. }
  8918. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8919. this.state.inFSharpPipelineDirectBody = false;
  8920. const propHash = Object.create(null);
  8921. let first = true;
  8922. const node = this.startNode();
  8923. node.properties = [];
  8924. this.next();
  8925. while (!this.match(close)) {
  8926. if (first) {
  8927. first = false;
  8928. } else {
  8929. this.expect(types.comma);
  8930. if (this.match(close)) {
  8931. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8932. break;
  8933. }
  8934. }
  8935. const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
  8936. if (!isPattern) {
  8937. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  8938. }
  8939. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  8940. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  8941. }
  8942. if (prop.shorthand) {
  8943. this.addExtra(prop, "shorthand", true);
  8944. }
  8945. node.properties.push(prop);
  8946. }
  8947. this.state.exprAllowed = false;
  8948. this.next();
  8949. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8950. let type = "ObjectExpression";
  8951. if (isPattern) {
  8952. type = "ObjectPattern";
  8953. } else if (isRecord) {
  8954. type = "RecordExpression";
  8955. }
  8956. return this.finishNode(node, type);
  8957. }
  8958. maybeAsyncOrAccessorProp(prop) {
  8959. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
  8960. }
  8961. parsePropertyDefinition(isPattern, refExpressionErrors) {
  8962. let decorators = [];
  8963. if (this.match(types.at)) {
  8964. if (this.hasPlugin("decorators")) {
  8965. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  8966. }
  8967. while (this.match(types.at)) {
  8968. decorators.push(this.parseDecorator());
  8969. }
  8970. }
  8971. const prop = this.startNode();
  8972. let isGenerator = false;
  8973. let isAsync = false;
  8974. let isAccessor = false;
  8975. let startPos;
  8976. let startLoc;
  8977. if (this.match(types.ellipsis)) {
  8978. if (decorators.length) this.unexpected();
  8979. if (isPattern) {
  8980. this.next();
  8981. prop.argument = this.parseIdentifier();
  8982. this.checkCommaAfterRest(125);
  8983. return this.finishNode(prop, "RestElement");
  8984. }
  8985. return this.parseSpread();
  8986. }
  8987. if (decorators.length) {
  8988. prop.decorators = decorators;
  8989. decorators = [];
  8990. }
  8991. prop.method = false;
  8992. if (isPattern || refExpressionErrors) {
  8993. startPos = this.state.start;
  8994. startLoc = this.state.startLoc;
  8995. }
  8996. if (!isPattern) {
  8997. isGenerator = this.eat(types.star);
  8998. }
  8999. const containsEsc = this.state.containsEsc;
  9000. const key = this.parsePropertyName(prop, false);
  9001. if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  9002. const keyName = key.name;
  9003. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  9004. isAsync = true;
  9005. isGenerator = this.eat(types.star);
  9006. this.parsePropertyName(prop, false);
  9007. }
  9008. if (keyName === "get" || keyName === "set") {
  9009. isAccessor = true;
  9010. prop.kind = keyName;
  9011. if (this.match(types.star)) {
  9012. isGenerator = true;
  9013. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  9014. this.next();
  9015. }
  9016. this.parsePropertyName(prop, false);
  9017. }
  9018. }
  9019. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  9020. return prop;
  9021. }
  9022. getGetterSetterExpectedParamCount(method) {
  9023. return method.kind === "get" ? 0 : 1;
  9024. }
  9025. getObjectOrClassMethodParams(method) {
  9026. return method.params;
  9027. }
  9028. checkGetterSetterParams(method) {
  9029. var _params;
  9030. const paramCount = this.getGetterSetterExpectedParamCount(method);
  9031. const params = this.getObjectOrClassMethodParams(method);
  9032. const start = method.start;
  9033. if (params.length !== paramCount) {
  9034. if (method.kind === "get") {
  9035. this.raise(start, ErrorMessages.BadGetterArity);
  9036. } else {
  9037. this.raise(start, ErrorMessages.BadSetterArity);
  9038. }
  9039. }
  9040. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  9041. this.raise(start, ErrorMessages.BadSetterRestParameter);
  9042. }
  9043. }
  9044. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  9045. if (isAccessor) {
  9046. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  9047. this.checkGetterSetterParams(prop);
  9048. return prop;
  9049. }
  9050. if (isAsync || isGenerator || this.match(types.parenL)) {
  9051. if (isPattern) this.unexpected();
  9052. prop.kind = "method";
  9053. prop.method = true;
  9054. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  9055. }
  9056. }
  9057. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  9058. prop.shorthand = false;
  9059. if (this.eat(types.colon)) {
  9060. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  9061. return this.finishNode(prop, "ObjectProperty");
  9062. }
  9063. if (!prop.computed && prop.key.type === "Identifier") {
  9064. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  9065. if (isPattern) {
  9066. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9067. } else if (this.match(types.eq) && refExpressionErrors) {
  9068. if (refExpressionErrors.shorthandAssign === -1) {
  9069. refExpressionErrors.shorthandAssign = this.state.start;
  9070. }
  9071. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9072. } else {
  9073. prop.value = prop.key.__clone();
  9074. }
  9075. prop.shorthand = true;
  9076. return this.finishNode(prop, "ObjectProperty");
  9077. }
  9078. }
  9079. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9080. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  9081. if (!node) this.unexpected();
  9082. return node;
  9083. }
  9084. parsePropertyName(prop, isPrivateNameAllowed) {
  9085. if (this.eat(types.bracketL)) {
  9086. prop.computed = true;
  9087. prop.key = this.parseMaybeAssignAllowIn();
  9088. this.expect(types.bracketR);
  9089. } else {
  9090. const oldInPropertyName = this.state.inPropertyName;
  9091. this.state.inPropertyName = true;
  9092. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  9093. if (!this.isPrivateName(prop.key)) {
  9094. prop.computed = false;
  9095. }
  9096. this.state.inPropertyName = oldInPropertyName;
  9097. }
  9098. return prop.key;
  9099. }
  9100. initFunction(node, isAsync) {
  9101. node.id = null;
  9102. node.generator = false;
  9103. node.async = !!isAsync;
  9104. }
  9105. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  9106. this.initFunction(node, isAsync);
  9107. node.generator = !!isGenerator;
  9108. const allowModifiers = isConstructor;
  9109. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  9110. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9111. this.parseFunctionParams(node, allowModifiers);
  9112. this.parseFunctionBodyAndFinish(node, type, true);
  9113. this.prodParam.exit();
  9114. this.scope.exit();
  9115. return node;
  9116. }
  9117. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  9118. if (isTuple) {
  9119. this.expectPlugin("recordAndTuple");
  9120. }
  9121. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9122. this.state.inFSharpPipelineDirectBody = false;
  9123. const node = this.startNode();
  9124. this.next();
  9125. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  9126. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9127. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  9128. }
  9129. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  9130. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  9131. let flags = functionFlags(isAsync, false);
  9132. if (!this.match(types.bracketL) && this.prodParam.hasIn) {
  9133. flags |= PARAM_IN;
  9134. }
  9135. this.prodParam.enter(flags);
  9136. this.initFunction(node, isAsync);
  9137. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9138. if (params) {
  9139. this.state.maybeInArrowParameters = true;
  9140. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  9141. }
  9142. this.state.maybeInArrowParameters = false;
  9143. this.parseFunctionBody(node, true);
  9144. this.prodParam.exit();
  9145. this.scope.exit();
  9146. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9147. return this.finishNode(node, "ArrowFunctionExpression");
  9148. }
  9149. setArrowFunctionParameters(node, params, trailingCommaPos) {
  9150. node.params = this.toAssignableList(params, trailingCommaPos, false);
  9151. }
  9152. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  9153. this.parseFunctionBody(node, false, isMethod);
  9154. this.finishNode(node, type);
  9155. }
  9156. parseFunctionBody(node, allowExpression, isMethod = false) {
  9157. const isExpression = allowExpression && !this.match(types.braceL);
  9158. this.expressionScope.enter(newExpressionScope());
  9159. if (isExpression) {
  9160. node.body = this.parseMaybeAssign();
  9161. this.checkParams(node, false, allowExpression, false);
  9162. } else {
  9163. const oldStrict = this.state.strict;
  9164. const oldLabels = this.state.labels;
  9165. this.state.labels = [];
  9166. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  9167. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  9168. const nonSimple = !this.isSimpleParamList(node.params);
  9169. if (hasStrictModeDirective && nonSimple) {
  9170. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  9171. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  9172. }
  9173. const strictModeChanged = !oldStrict && this.state.strict;
  9174. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  9175. if (this.state.strict && node.id) {
  9176. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  9177. }
  9178. });
  9179. this.prodParam.exit();
  9180. this.expressionScope.exit();
  9181. this.state.labels = oldLabels;
  9182. }
  9183. }
  9184. isSimpleParamList(params) {
  9185. for (let i = 0, len = params.length; i < len; i++) {
  9186. if (params[i].type !== "Identifier") return false;
  9187. }
  9188. return true;
  9189. }
  9190. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  9191. const checkClashes = new Set();
  9192. for (let _i2 = 0, _node$params = node.params; _i2 < _node$params.length; _i2++) {
  9193. const param = _node$params[_i2];
  9194. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  9195. }
  9196. }
  9197. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  9198. const elts = [];
  9199. let first = true;
  9200. while (!this.eat(close)) {
  9201. if (first) {
  9202. first = false;
  9203. } else {
  9204. this.expect(types.comma);
  9205. if (this.match(close)) {
  9206. if (nodeForExtra) {
  9207. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  9208. }
  9209. this.next();
  9210. break;
  9211. }
  9212. }
  9213. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  9214. }
  9215. return elts;
  9216. }
  9217. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  9218. let elt;
  9219. if (this.match(types.comma)) {
  9220. if (!allowEmpty) {
  9221. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  9222. }
  9223. elt = null;
  9224. } else if (this.match(types.ellipsis)) {
  9225. const spreadNodeStartPos = this.state.start;
  9226. const spreadNodeStartLoc = this.state.startLoc;
  9227. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  9228. } else if (this.match(types.question)) {
  9229. this.expectPlugin("partialApplication");
  9230. if (!allowPlaceholder) {
  9231. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  9232. }
  9233. const node = this.startNode();
  9234. this.next();
  9235. elt = this.finishNode(node, "ArgumentPlaceholder");
  9236. } else {
  9237. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  9238. }
  9239. return elt;
  9240. }
  9241. parseIdentifier(liberal) {
  9242. const node = this.startNode();
  9243. const name = this.parseIdentifierName(node.start, liberal);
  9244. return this.createIdentifier(node, name);
  9245. }
  9246. createIdentifier(node, name) {
  9247. node.name = name;
  9248. node.loc.identifierName = name;
  9249. return this.finishNode(node, "Identifier");
  9250. }
  9251. parseIdentifierName(pos, liberal) {
  9252. let name;
  9253. const {
  9254. start,
  9255. type
  9256. } = this.state;
  9257. if (type === types.name) {
  9258. name = this.state.value;
  9259. } else if (type.keyword) {
  9260. name = type.keyword;
  9261. const curContext = this.curContext();
  9262. if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
  9263. this.state.context.pop();
  9264. }
  9265. } else {
  9266. throw this.unexpected();
  9267. }
  9268. if (liberal) {
  9269. this.state.type = types.name;
  9270. } else {
  9271. this.checkReservedWord(name, start, !!type.keyword, false);
  9272. }
  9273. this.next();
  9274. return name;
  9275. }
  9276. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9277. if (this.prodParam.hasYield && word === "yield") {
  9278. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  9279. return;
  9280. }
  9281. if (word === "await") {
  9282. if (this.prodParam.hasAwait) {
  9283. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9284. return;
  9285. } else {
  9286. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9287. }
  9288. }
  9289. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  9290. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  9291. return;
  9292. }
  9293. if (checkKeywords && isKeyword(word)) {
  9294. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  9295. return;
  9296. }
  9297. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  9298. if (reservedTest(word, this.inModule)) {
  9299. if (!this.prodParam.hasAwait && word === "await") {
  9300. this.raise(startLoc, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction);
  9301. } else {
  9302. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  9303. }
  9304. }
  9305. }
  9306. isAwaitAllowed() {
  9307. if (this.prodParam.hasAwait) return true;
  9308. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  9309. return true;
  9310. }
  9311. return false;
  9312. }
  9313. parseAwait() {
  9314. const node = this.startNode();
  9315. this.next();
  9316. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  9317. if (this.eat(types.star)) {
  9318. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  9319. }
  9320. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  9321. if (this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo)) {
  9322. this.ambiguousScriptDifferentAst = true;
  9323. } else {
  9324. this.sawUnambiguousESM = true;
  9325. }
  9326. }
  9327. if (!this.state.soloAwait) {
  9328. node.argument = this.parseMaybeUnary();
  9329. }
  9330. return this.finishNode(node, "AwaitExpression");
  9331. }
  9332. parseYield() {
  9333. const node = this.startNode();
  9334. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  9335. this.next();
  9336. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  9337. node.delegate = false;
  9338. node.argument = null;
  9339. } else {
  9340. node.delegate = this.eat(types.star);
  9341. node.argument = this.parseMaybeAssign();
  9342. }
  9343. return this.finishNode(node, "YieldExpression");
  9344. }
  9345. checkPipelineAtInfixOperator(left, leftStartPos) {
  9346. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  9347. if (left.type === "SequenceExpression") {
  9348. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  9349. }
  9350. }
  9351. }
  9352. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  9353. this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
  9354. return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
  9355. }
  9356. checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
  9357. if (this.match(types.arrow)) {
  9358. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  9359. } else if (childExpression.type === "SequenceExpression") {
  9360. this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
  9361. }
  9362. }
  9363. parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
  9364. const bodyNode = this.startNodeAt(startPos, startLoc);
  9365. const isSimpleReference = this.isSimpleReference(childExpression);
  9366. if (isSimpleReference) {
  9367. bodyNode.callee = childExpression;
  9368. } else {
  9369. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  9370. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  9371. }
  9372. bodyNode.expression = childExpression;
  9373. }
  9374. return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
  9375. }
  9376. isSimpleReference(expression) {
  9377. switch (expression.type) {
  9378. case "MemberExpression":
  9379. return !expression.computed && this.isSimpleReference(expression.object);
  9380. case "Identifier":
  9381. return true;
  9382. default:
  9383. return false;
  9384. }
  9385. }
  9386. withTopicPermittingContext(callback) {
  9387. const outerContextTopicState = this.state.topicContext;
  9388. this.state.topicContext = {
  9389. maxNumOfResolvableTopics: 1,
  9390. maxTopicIndex: null
  9391. };
  9392. try {
  9393. return callback();
  9394. } finally {
  9395. this.state.topicContext = outerContextTopicState;
  9396. }
  9397. }
  9398. withTopicForbiddingContext(callback) {
  9399. const outerContextTopicState = this.state.topicContext;
  9400. this.state.topicContext = {
  9401. maxNumOfResolvableTopics: 0,
  9402. maxTopicIndex: null
  9403. };
  9404. try {
  9405. return callback();
  9406. } finally {
  9407. this.state.topicContext = outerContextTopicState;
  9408. }
  9409. }
  9410. withSoloAwaitPermittingContext(callback) {
  9411. const outerContextSoloAwaitState = this.state.soloAwait;
  9412. this.state.soloAwait = true;
  9413. try {
  9414. return callback();
  9415. } finally {
  9416. this.state.soloAwait = outerContextSoloAwaitState;
  9417. }
  9418. }
  9419. allowInAnd(callback) {
  9420. const flags = this.prodParam.currentFlags();
  9421. const prodParamToSet = PARAM_IN & ~flags;
  9422. if (prodParamToSet) {
  9423. this.prodParam.enter(flags | PARAM_IN);
  9424. try {
  9425. return callback();
  9426. } finally {
  9427. this.prodParam.exit();
  9428. }
  9429. }
  9430. return callback();
  9431. }
  9432. disallowInAnd(callback) {
  9433. const flags = this.prodParam.currentFlags();
  9434. const prodParamToClear = PARAM_IN & flags;
  9435. if (prodParamToClear) {
  9436. this.prodParam.enter(flags & ~PARAM_IN);
  9437. try {
  9438. return callback();
  9439. } finally {
  9440. this.prodParam.exit();
  9441. }
  9442. }
  9443. return callback();
  9444. }
  9445. registerTopicReference() {
  9446. this.state.topicContext.maxTopicIndex = 0;
  9447. }
  9448. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  9449. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  9450. }
  9451. topicReferenceWasUsedInCurrentTopicContext() {
  9452. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  9453. }
  9454. parseFSharpPipelineBody(prec) {
  9455. const startPos = this.state.start;
  9456. const startLoc = this.state.startLoc;
  9457. this.state.potentialArrowAt = this.state.start;
  9458. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9459. this.state.inFSharpPipelineDirectBody = true;
  9460. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
  9461. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9462. return ret;
  9463. }
  9464. }
  9465. const loopLabel = {
  9466. kind: "loop"
  9467. },
  9468. switchLabel = {
  9469. kind: "switch"
  9470. };
  9471. const FUNC_NO_FLAGS = 0b000,
  9472. FUNC_STATEMENT = 0b001,
  9473. FUNC_HANGING_STATEMENT = 0b010,
  9474. FUNC_NULLABLE_ID = 0b100;
  9475. const loneSurrogate = /[\uD800-\uDFFF]/u;
  9476. class StatementParser extends ExpressionParser {
  9477. parseTopLevel(file, program) {
  9478. program.sourceType = this.options.sourceType;
  9479. program.interpreter = this.parseInterpreterDirective();
  9480. this.parseBlockBody(program, true, true, types.eof);
  9481. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9482. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  9483. const [name] = _Array$from[_i];
  9484. const pos = this.scope.undefinedExports.get(name);
  9485. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  9486. }
  9487. }
  9488. file.program = this.finishNode(program, "Program");
  9489. file.comments = this.state.comments;
  9490. if (this.options.tokens) file.tokens = this.tokens;
  9491. return this.finishNode(file, "File");
  9492. }
  9493. stmtToDirective(stmt) {
  9494. const expr = stmt.expression;
  9495. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9496. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9497. const raw = this.input.slice(expr.start, expr.end);
  9498. const val = directiveLiteral.value = raw.slice(1, -1);
  9499. this.addExtra(directiveLiteral, "raw", raw);
  9500. this.addExtra(directiveLiteral, "rawValue", val);
  9501. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9502. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9503. }
  9504. parseInterpreterDirective() {
  9505. if (!this.match(types.interpreterDirective)) {
  9506. return null;
  9507. }
  9508. const node = this.startNode();
  9509. node.value = this.state.value;
  9510. this.next();
  9511. return this.finishNode(node, "InterpreterDirective");
  9512. }
  9513. isLet(context) {
  9514. if (!this.isContextual("let")) {
  9515. return false;
  9516. }
  9517. const next = this.nextTokenStart();
  9518. const nextCh = this.input.charCodeAt(next);
  9519. if (nextCh === 91) return true;
  9520. if (context) return false;
  9521. if (nextCh === 123) return true;
  9522. if (isIdentifierStart(nextCh)) {
  9523. let pos = next + 1;
  9524. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9525. ++pos;
  9526. }
  9527. const ident = this.input.slice(next, pos);
  9528. if (!keywordRelationalOperator.test(ident)) return true;
  9529. }
  9530. return false;
  9531. }
  9532. parseStatement(context, topLevel) {
  9533. if (this.match(types.at)) {
  9534. this.parseDecorators(true);
  9535. }
  9536. return this.parseStatementContent(context, topLevel);
  9537. }
  9538. parseStatementContent(context, topLevel) {
  9539. let starttype = this.state.type;
  9540. const node = this.startNode();
  9541. let kind;
  9542. if (this.isLet(context)) {
  9543. starttype = types._var;
  9544. kind = "let";
  9545. }
  9546. switch (starttype) {
  9547. case types._break:
  9548. case types._continue:
  9549. return this.parseBreakContinueStatement(node, starttype.keyword);
  9550. case types._debugger:
  9551. return this.parseDebuggerStatement(node);
  9552. case types._do:
  9553. return this.parseDoStatement(node);
  9554. case types._for:
  9555. return this.parseForStatement(node);
  9556. case types._function:
  9557. if (this.lookaheadCharCode() === 46) break;
  9558. if (context) {
  9559. if (this.state.strict) {
  9560. this.raise(this.state.start, ErrorMessages.StrictFunction);
  9561. } else if (context !== "if" && context !== "label") {
  9562. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  9563. }
  9564. }
  9565. return this.parseFunctionStatement(node, false, !context);
  9566. case types._class:
  9567. if (context) this.unexpected();
  9568. return this.parseClass(node, true);
  9569. case types._if:
  9570. return this.parseIfStatement(node);
  9571. case types._return:
  9572. return this.parseReturnStatement(node);
  9573. case types._switch:
  9574. return this.parseSwitchStatement(node);
  9575. case types._throw:
  9576. return this.parseThrowStatement(node);
  9577. case types._try:
  9578. return this.parseTryStatement(node);
  9579. case types._const:
  9580. case types._var:
  9581. kind = kind || this.state.value;
  9582. if (context && kind !== "var") {
  9583. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  9584. }
  9585. return this.parseVarStatement(node, kind);
  9586. case types._while:
  9587. return this.parseWhileStatement(node);
  9588. case types._with:
  9589. return this.parseWithStatement(node);
  9590. case types.braceL:
  9591. return this.parseBlock();
  9592. case types.semi:
  9593. return this.parseEmptyStatement(node);
  9594. case types._import:
  9595. {
  9596. const nextTokenCharCode = this.lookaheadCharCode();
  9597. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  9598. break;
  9599. }
  9600. }
  9601. case types._export:
  9602. {
  9603. if (!this.options.allowImportExportEverywhere && !topLevel) {
  9604. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  9605. }
  9606. this.next();
  9607. let result;
  9608. if (starttype === types._import) {
  9609. result = this.parseImport(node);
  9610. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  9611. this.sawUnambiguousESM = true;
  9612. }
  9613. } else {
  9614. result = this.parseExport(node);
  9615. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  9616. this.sawUnambiguousESM = true;
  9617. }
  9618. }
  9619. this.assertModuleNodeAllowed(node);
  9620. return result;
  9621. }
  9622. default:
  9623. {
  9624. if (this.isAsyncFunction()) {
  9625. if (context) {
  9626. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  9627. }
  9628. this.next();
  9629. return this.parseFunctionStatement(node, true, !context);
  9630. }
  9631. }
  9632. }
  9633. const maybeName = this.state.value;
  9634. const expr = this.parseExpression();
  9635. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  9636. return this.parseLabeledStatement(node, maybeName, expr, context);
  9637. } else {
  9638. return this.parseExpressionStatement(node, expr);
  9639. }
  9640. }
  9641. assertModuleNodeAllowed(node) {
  9642. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  9643. this.raiseWithData(node.start, {
  9644. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9645. }, ErrorMessages.ImportOutsideModule);
  9646. }
  9647. }
  9648. takeDecorators(node) {
  9649. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9650. if (decorators.length) {
  9651. node.decorators = decorators;
  9652. this.resetStartLocationFromNode(node, decorators[0]);
  9653. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  9654. }
  9655. }
  9656. canHaveLeadingDecorator() {
  9657. return this.match(types._class);
  9658. }
  9659. parseDecorators(allowExport) {
  9660. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9661. while (this.match(types.at)) {
  9662. const decorator = this.parseDecorator();
  9663. currentContextDecorators.push(decorator);
  9664. }
  9665. if (this.match(types._export)) {
  9666. if (!allowExport) {
  9667. this.unexpected();
  9668. }
  9669. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9670. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  9671. }
  9672. } else if (!this.canHaveLeadingDecorator()) {
  9673. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  9674. }
  9675. }
  9676. parseDecorator() {
  9677. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  9678. const node = this.startNode();
  9679. this.next();
  9680. if (this.hasPlugin("decorators")) {
  9681. this.state.decoratorStack.push([]);
  9682. const startPos = this.state.start;
  9683. const startLoc = this.state.startLoc;
  9684. let expr;
  9685. if (this.eat(types.parenL)) {
  9686. expr = this.parseExpression();
  9687. this.expect(types.parenR);
  9688. } else {
  9689. expr = this.parseIdentifier(false);
  9690. while (this.eat(types.dot)) {
  9691. const node = this.startNodeAt(startPos, startLoc);
  9692. node.object = expr;
  9693. node.property = this.parseIdentifier(true);
  9694. node.computed = false;
  9695. expr = this.finishNode(node, "MemberExpression");
  9696. }
  9697. }
  9698. node.expression = this.parseMaybeDecoratorArguments(expr);
  9699. this.state.decoratorStack.pop();
  9700. } else {
  9701. node.expression = this.parseExprSubscripts();
  9702. }
  9703. return this.finishNode(node, "Decorator");
  9704. }
  9705. parseMaybeDecoratorArguments(expr) {
  9706. if (this.eat(types.parenL)) {
  9707. const node = this.startNodeAtNode(expr);
  9708. node.callee = expr;
  9709. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  9710. this.toReferencedList(node.arguments);
  9711. return this.finishNode(node, "CallExpression");
  9712. }
  9713. return expr;
  9714. }
  9715. parseBreakContinueStatement(node, keyword) {
  9716. const isBreak = keyword === "break";
  9717. this.next();
  9718. if (this.isLineTerminator()) {
  9719. node.label = null;
  9720. } else {
  9721. node.label = this.parseIdentifier();
  9722. this.semicolon();
  9723. }
  9724. this.verifyBreakContinue(node, keyword);
  9725. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  9726. }
  9727. verifyBreakContinue(node, keyword) {
  9728. const isBreak = keyword === "break";
  9729. let i;
  9730. for (i = 0; i < this.state.labels.length; ++i) {
  9731. const lab = this.state.labels[i];
  9732. if (node.label == null || lab.name === node.label.name) {
  9733. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  9734. if (node.label && isBreak) break;
  9735. }
  9736. }
  9737. if (i === this.state.labels.length) {
  9738. this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
  9739. }
  9740. }
  9741. parseDebuggerStatement(node) {
  9742. this.next();
  9743. this.semicolon();
  9744. return this.finishNode(node, "DebuggerStatement");
  9745. }
  9746. parseHeaderExpression() {
  9747. this.expect(types.parenL);
  9748. const val = this.parseExpression();
  9749. this.expect(types.parenR);
  9750. return val;
  9751. }
  9752. parseDoStatement(node) {
  9753. this.next();
  9754. this.state.labels.push(loopLabel);
  9755. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  9756. this.state.labels.pop();
  9757. this.expect(types._while);
  9758. node.test = this.parseHeaderExpression();
  9759. this.eat(types.semi);
  9760. return this.finishNode(node, "DoWhileStatement");
  9761. }
  9762. parseForStatement(node) {
  9763. this.next();
  9764. this.state.labels.push(loopLabel);
  9765. let awaitAt = -1;
  9766. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  9767. awaitAt = this.state.lastTokStart;
  9768. }
  9769. this.scope.enter(SCOPE_OTHER);
  9770. this.expect(types.parenL);
  9771. if (this.match(types.semi)) {
  9772. if (awaitAt > -1) {
  9773. this.unexpected(awaitAt);
  9774. }
  9775. return this.parseFor(node, null);
  9776. }
  9777. const isLet = this.isLet();
  9778. if (this.match(types._var) || this.match(types._const) || isLet) {
  9779. const init = this.startNode();
  9780. const kind = isLet ? "let" : this.state.value;
  9781. this.next();
  9782. this.parseVar(init, true, kind);
  9783. this.finishNode(init, "VariableDeclaration");
  9784. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  9785. return this.parseForIn(node, init, awaitAt);
  9786. }
  9787. if (awaitAt > -1) {
  9788. this.unexpected(awaitAt);
  9789. }
  9790. return this.parseFor(node, init);
  9791. }
  9792. const refExpressionErrors = new ExpressionErrors();
  9793. const init = this.parseExpression(true, refExpressionErrors);
  9794. if (this.match(types._in) || this.isContextual("of")) {
  9795. this.toAssignable(init, true);
  9796. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  9797. this.checkLVal(init, description);
  9798. return this.parseForIn(node, init, awaitAt);
  9799. } else {
  9800. this.checkExpressionErrors(refExpressionErrors, true);
  9801. }
  9802. if (awaitAt > -1) {
  9803. this.unexpected(awaitAt);
  9804. }
  9805. return this.parseFor(node, init);
  9806. }
  9807. parseFunctionStatement(node, isAsync, declarationPosition) {
  9808. this.next();
  9809. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  9810. }
  9811. parseIfStatement(node) {
  9812. this.next();
  9813. node.test = this.parseHeaderExpression();
  9814. node.consequent = this.parseStatement("if");
  9815. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  9816. return this.finishNode(node, "IfStatement");
  9817. }
  9818. parseReturnStatement(node) {
  9819. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  9820. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  9821. }
  9822. this.next();
  9823. if (this.isLineTerminator()) {
  9824. node.argument = null;
  9825. } else {
  9826. node.argument = this.parseExpression();
  9827. this.semicolon();
  9828. }
  9829. return this.finishNode(node, "ReturnStatement");
  9830. }
  9831. parseSwitchStatement(node) {
  9832. this.next();
  9833. node.discriminant = this.parseHeaderExpression();
  9834. const cases = node.cases = [];
  9835. this.expect(types.braceL);
  9836. this.state.labels.push(switchLabel);
  9837. this.scope.enter(SCOPE_OTHER);
  9838. let cur;
  9839. for (let sawDefault; !this.match(types.braceR);) {
  9840. if (this.match(types._case) || this.match(types._default)) {
  9841. const isCase = this.match(types._case);
  9842. if (cur) this.finishNode(cur, "SwitchCase");
  9843. cases.push(cur = this.startNode());
  9844. cur.consequent = [];
  9845. this.next();
  9846. if (isCase) {
  9847. cur.test = this.parseExpression();
  9848. } else {
  9849. if (sawDefault) {
  9850. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  9851. }
  9852. sawDefault = true;
  9853. cur.test = null;
  9854. }
  9855. this.expect(types.colon);
  9856. } else {
  9857. if (cur) {
  9858. cur.consequent.push(this.parseStatement(null));
  9859. } else {
  9860. this.unexpected();
  9861. }
  9862. }
  9863. }
  9864. this.scope.exit();
  9865. if (cur) this.finishNode(cur, "SwitchCase");
  9866. this.next();
  9867. this.state.labels.pop();
  9868. return this.finishNode(node, "SwitchStatement");
  9869. }
  9870. parseThrowStatement(node) {
  9871. this.next();
  9872. if (this.hasPrecedingLineBreak()) {
  9873. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  9874. }
  9875. node.argument = this.parseExpression();
  9876. this.semicolon();
  9877. return this.finishNode(node, "ThrowStatement");
  9878. }
  9879. parseCatchClauseParam() {
  9880. const param = this.parseBindingAtom();
  9881. const simple = param.type === "Identifier";
  9882. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9883. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  9884. return param;
  9885. }
  9886. parseTryStatement(node) {
  9887. this.next();
  9888. node.block = this.parseBlock();
  9889. node.handler = null;
  9890. if (this.match(types._catch)) {
  9891. const clause = this.startNode();
  9892. this.next();
  9893. if (this.match(types.parenL)) {
  9894. this.expect(types.parenL);
  9895. clause.param = this.parseCatchClauseParam();
  9896. this.expect(types.parenR);
  9897. } else {
  9898. clause.param = null;
  9899. this.scope.enter(SCOPE_OTHER);
  9900. }
  9901. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9902. this.scope.exit();
  9903. node.handler = this.finishNode(clause, "CatchClause");
  9904. }
  9905. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9906. if (!node.handler && !node.finalizer) {
  9907. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  9908. }
  9909. return this.finishNode(node, "TryStatement");
  9910. }
  9911. parseVarStatement(node, kind) {
  9912. this.next();
  9913. this.parseVar(node, false, kind);
  9914. this.semicolon();
  9915. return this.finishNode(node, "VariableDeclaration");
  9916. }
  9917. parseWhileStatement(node) {
  9918. this.next();
  9919. node.test = this.parseHeaderExpression();
  9920. this.state.labels.push(loopLabel);
  9921. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9922. this.state.labels.pop();
  9923. return this.finishNode(node, "WhileStatement");
  9924. }
  9925. parseWithStatement(node) {
  9926. if (this.state.strict) {
  9927. this.raise(this.state.start, ErrorMessages.StrictWith);
  9928. }
  9929. this.next();
  9930. node.object = this.parseHeaderExpression();
  9931. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9932. return this.finishNode(node, "WithStatement");
  9933. }
  9934. parseEmptyStatement(node) {
  9935. this.next();
  9936. return this.finishNode(node, "EmptyStatement");
  9937. }
  9938. parseLabeledStatement(node, maybeName, expr, context) {
  9939. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9940. const label = _this$state$labels[_i2];
  9941. if (label.name === maybeName) {
  9942. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  9943. }
  9944. }
  9945. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9946. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9947. const label = this.state.labels[i];
  9948. if (label.statementStart === node.start) {
  9949. label.statementStart = this.state.start;
  9950. label.kind = kind;
  9951. } else {
  9952. break;
  9953. }
  9954. }
  9955. this.state.labels.push({
  9956. name: maybeName,
  9957. kind: kind,
  9958. statementStart: this.state.start
  9959. });
  9960. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9961. this.state.labels.pop();
  9962. node.label = expr;
  9963. return this.finishNode(node, "LabeledStatement");
  9964. }
  9965. parseExpressionStatement(node, expr) {
  9966. node.expression = expr;
  9967. this.semicolon();
  9968. return this.finishNode(node, "ExpressionStatement");
  9969. }
  9970. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  9971. const node = this.startNode();
  9972. if (allowDirectives) {
  9973. this.state.strictErrors.clear();
  9974. }
  9975. this.expect(types.braceL);
  9976. if (createNewLexicalScope) {
  9977. this.scope.enter(SCOPE_OTHER);
  9978. }
  9979. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  9980. if (createNewLexicalScope) {
  9981. this.scope.exit();
  9982. }
  9983. return this.finishNode(node, "BlockStatement");
  9984. }
  9985. isValidDirective(stmt) {
  9986. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9987. }
  9988. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  9989. const body = node.body = [];
  9990. const directives = node.directives = [];
  9991. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  9992. }
  9993. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  9994. const oldStrict = this.state.strict;
  9995. let hasStrictModeDirective = false;
  9996. let parsedNonDirective = false;
  9997. while (!this.match(end)) {
  9998. const stmt = this.parseStatement(null, topLevel);
  9999. if (directives && !parsedNonDirective) {
  10000. if (this.isValidDirective(stmt)) {
  10001. const directive = this.stmtToDirective(stmt);
  10002. directives.push(directive);
  10003. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  10004. hasStrictModeDirective = true;
  10005. this.setStrict(true);
  10006. }
  10007. continue;
  10008. }
  10009. parsedNonDirective = true;
  10010. this.state.strictErrors.clear();
  10011. }
  10012. body.push(stmt);
  10013. }
  10014. if (afterBlockParse) {
  10015. afterBlockParse.call(this, hasStrictModeDirective);
  10016. }
  10017. if (!oldStrict) {
  10018. this.setStrict(false);
  10019. }
  10020. this.next();
  10021. }
  10022. parseFor(node, init) {
  10023. node.init = init;
  10024. this.expect(types.semi);
  10025. node.test = this.match(types.semi) ? null : this.parseExpression();
  10026. this.expect(types.semi);
  10027. node.update = this.match(types.parenR) ? null : this.parseExpression();
  10028. this.expect(types.parenR);
  10029. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10030. this.scope.exit();
  10031. this.state.labels.pop();
  10032. return this.finishNode(node, "ForStatement");
  10033. }
  10034. parseForIn(node, init, awaitAt) {
  10035. const isForIn = this.match(types._in);
  10036. this.next();
  10037. if (isForIn) {
  10038. if (awaitAt > -1) this.unexpected(awaitAt);
  10039. } else {
  10040. node.await = awaitAt > -1;
  10041. }
  10042. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  10043. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  10044. } else if (init.type === "AssignmentPattern") {
  10045. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  10046. }
  10047. node.left = init;
  10048. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  10049. this.expect(types.parenR);
  10050. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10051. this.scope.exit();
  10052. this.state.labels.pop();
  10053. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  10054. }
  10055. parseVar(node, isFor, kind) {
  10056. const declarations = node.declarations = [];
  10057. const isTypescript = this.hasPlugin("typescript");
  10058. node.kind = kind;
  10059. for (;;) {
  10060. const decl = this.startNode();
  10061. this.parseVarId(decl, kind);
  10062. if (this.eat(types.eq)) {
  10063. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  10064. } else {
  10065. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  10066. if (!isTypescript) {
  10067. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  10068. }
  10069. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  10070. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  10071. }
  10072. decl.init = null;
  10073. }
  10074. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  10075. if (!this.eat(types.comma)) break;
  10076. }
  10077. return node;
  10078. }
  10079. parseVarId(decl, kind) {
  10080. decl.id = this.parseBindingAtom();
  10081. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  10082. }
  10083. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  10084. const isStatement = statement & FUNC_STATEMENT;
  10085. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  10086. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  10087. this.initFunction(node, isAsync);
  10088. if (this.match(types.star) && isHangingStatement) {
  10089. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  10090. }
  10091. node.generator = this.eat(types.star);
  10092. if (isStatement) {
  10093. node.id = this.parseFunctionId(requireId);
  10094. }
  10095. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10096. this.state.maybeInArrowParameters = false;
  10097. this.scope.enter(SCOPE_FUNCTION);
  10098. this.prodParam.enter(functionFlags(isAsync, node.generator));
  10099. if (!isStatement) {
  10100. node.id = this.parseFunctionId();
  10101. }
  10102. this.parseFunctionParams(node, false);
  10103. this.withTopicForbiddingContext(() => {
  10104. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  10105. });
  10106. this.prodParam.exit();
  10107. this.scope.exit();
  10108. if (isStatement && !isHangingStatement) {
  10109. this.registerFunctionStatementId(node);
  10110. }
  10111. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10112. return node;
  10113. }
  10114. parseFunctionId(requireId) {
  10115. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  10116. }
  10117. parseFunctionParams(node, allowModifiers) {
  10118. this.expect(types.parenL);
  10119. this.expressionScope.enter(newParameterDeclarationScope());
  10120. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  10121. this.expressionScope.exit();
  10122. }
  10123. registerFunctionStatementId(node) {
  10124. if (!node.id) return;
  10125. 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);
  10126. }
  10127. parseClass(node, isStatement, optionalId) {
  10128. this.next();
  10129. this.takeDecorators(node);
  10130. const oldStrict = this.state.strict;
  10131. this.state.strict = true;
  10132. this.parseClassId(node, isStatement, optionalId);
  10133. this.parseClassSuper(node);
  10134. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  10135. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  10136. }
  10137. isClassProperty() {
  10138. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  10139. }
  10140. isClassMethod() {
  10141. return this.match(types.parenL);
  10142. }
  10143. isNonstaticConstructor(method) {
  10144. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  10145. }
  10146. parseClassBody(constructorAllowsSuper, oldStrict) {
  10147. this.classScope.enter();
  10148. const state = {
  10149. constructorAllowsSuper,
  10150. hadConstructor: false,
  10151. hadStaticBlock: false
  10152. };
  10153. let decorators = [];
  10154. const classBody = this.startNode();
  10155. classBody.body = [];
  10156. this.expect(types.braceL);
  10157. this.withTopicForbiddingContext(() => {
  10158. while (!this.match(types.braceR)) {
  10159. if (this.eat(types.semi)) {
  10160. if (decorators.length > 0) {
  10161. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  10162. }
  10163. continue;
  10164. }
  10165. if (this.match(types.at)) {
  10166. decorators.push(this.parseDecorator());
  10167. continue;
  10168. }
  10169. const member = this.startNode();
  10170. if (decorators.length) {
  10171. member.decorators = decorators;
  10172. this.resetStartLocationFromNode(member, decorators[0]);
  10173. decorators = [];
  10174. }
  10175. this.parseClassMember(classBody, member, state);
  10176. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  10177. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  10178. }
  10179. }
  10180. });
  10181. this.state.strict = oldStrict;
  10182. this.next();
  10183. if (decorators.length) {
  10184. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  10185. }
  10186. this.classScope.exit();
  10187. return this.finishNode(classBody, "ClassBody");
  10188. }
  10189. parseClassMemberFromModifier(classBody, member) {
  10190. const key = this.parseIdentifier(true);
  10191. if (this.isClassMethod()) {
  10192. const method = member;
  10193. method.kind = "method";
  10194. method.computed = false;
  10195. method.key = key;
  10196. method.static = false;
  10197. this.pushClassMethod(classBody, method, false, false, false, false);
  10198. return true;
  10199. } else if (this.isClassProperty()) {
  10200. const prop = member;
  10201. prop.computed = false;
  10202. prop.key = key;
  10203. prop.static = false;
  10204. classBody.body.push(this.parseClassProperty(prop));
  10205. return true;
  10206. }
  10207. return false;
  10208. }
  10209. parseClassMember(classBody, member, state) {
  10210. const isStatic = this.isContextual("static");
  10211. if (isStatic) {
  10212. if (this.parseClassMemberFromModifier(classBody, member)) {
  10213. return;
  10214. }
  10215. if (this.eat(types.braceL)) {
  10216. this.parseClassStaticBlock(classBody, member, state);
  10217. return;
  10218. }
  10219. }
  10220. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  10221. }
  10222. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  10223. const publicMethod = member;
  10224. const privateMethod = member;
  10225. const publicProp = member;
  10226. const privateProp = member;
  10227. const method = publicMethod;
  10228. const publicMember = publicMethod;
  10229. member.static = isStatic;
  10230. if (this.eat(types.star)) {
  10231. method.kind = "method";
  10232. this.parseClassElementName(method);
  10233. if (this.isPrivateName(method.key)) {
  10234. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  10235. return;
  10236. }
  10237. if (this.isNonstaticConstructor(publicMethod)) {
  10238. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  10239. }
  10240. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  10241. return;
  10242. }
  10243. const containsEsc = this.state.containsEsc;
  10244. const key = this.parseClassElementName(member);
  10245. const isPrivate = this.isPrivateName(key);
  10246. const isSimple = key.type === "Identifier";
  10247. const maybeQuestionTokenStart = this.state.start;
  10248. this.parsePostMemberNameModifiers(publicMember);
  10249. if (this.isClassMethod()) {
  10250. method.kind = "method";
  10251. if (isPrivate) {
  10252. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10253. return;
  10254. }
  10255. const isConstructor = this.isNonstaticConstructor(publicMethod);
  10256. let allowsDirectSuper = false;
  10257. if (isConstructor) {
  10258. publicMethod.kind = "constructor";
  10259. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  10260. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  10261. }
  10262. state.hadConstructor = true;
  10263. allowsDirectSuper = state.constructorAllowsSuper;
  10264. }
  10265. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  10266. } else if (this.isClassProperty()) {
  10267. if (isPrivate) {
  10268. this.pushClassPrivateProperty(classBody, privateProp);
  10269. } else {
  10270. this.pushClassProperty(classBody, publicProp);
  10271. }
  10272. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  10273. const isGenerator = this.eat(types.star);
  10274. if (publicMember.optional) {
  10275. this.unexpected(maybeQuestionTokenStart);
  10276. }
  10277. method.kind = "method";
  10278. this.parseClassElementName(method);
  10279. this.parsePostMemberNameModifiers(publicMember);
  10280. if (this.isPrivateName(method.key)) {
  10281. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  10282. } else {
  10283. if (this.isNonstaticConstructor(publicMethod)) {
  10284. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  10285. }
  10286. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  10287. }
  10288. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  10289. method.kind = key.name;
  10290. this.parseClassElementName(publicMethod);
  10291. if (this.isPrivateName(method.key)) {
  10292. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10293. } else {
  10294. if (this.isNonstaticConstructor(publicMethod)) {
  10295. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  10296. }
  10297. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  10298. }
  10299. this.checkGetterSetterParams(publicMethod);
  10300. } else if (this.isLineTerminator()) {
  10301. if (isPrivate) {
  10302. this.pushClassPrivateProperty(classBody, privateProp);
  10303. } else {
  10304. this.pushClassProperty(classBody, publicProp);
  10305. }
  10306. } else {
  10307. this.unexpected();
  10308. }
  10309. }
  10310. parseClassElementName(member) {
  10311. const key = this.parsePropertyName(member, true);
  10312. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  10313. this.raise(key.start, ErrorMessages.StaticPrototype);
  10314. }
  10315. if (this.isPrivateName(key) && this.getPrivateNameSV(key) === "constructor") {
  10316. this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
  10317. }
  10318. return key;
  10319. }
  10320. parseClassStaticBlock(classBody, member, state) {
  10321. var _member$decorators;
  10322. this.expectPlugin("classStaticBlock", member.start);
  10323. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10324. this.expressionScope.enter(newExpressionScope());
  10325. const oldLabels = this.state.labels;
  10326. this.state.labels = [];
  10327. this.prodParam.enter(PARAM);
  10328. const body = member.body = [];
  10329. this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
  10330. this.prodParam.exit();
  10331. this.expressionScope.exit();
  10332. this.scope.exit();
  10333. this.state.labels = oldLabels;
  10334. classBody.body.push(this.finishNode(member, "StaticBlock"));
  10335. if (state.hadStaticBlock) {
  10336. this.raise(member.start, ErrorMessages.DuplicateStaticBlock);
  10337. }
  10338. if ((_member$decorators = member.decorators) == null ? void 0 : _member$decorators.length) {
  10339. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  10340. }
  10341. state.hadStaticBlock = true;
  10342. }
  10343. pushClassProperty(classBody, prop) {
  10344. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  10345. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  10346. }
  10347. classBody.body.push(this.parseClassProperty(prop));
  10348. }
  10349. pushClassPrivateProperty(classBody, prop) {
  10350. this.expectPlugin("classPrivateProperties", prop.key.start);
  10351. const node = this.parseClassPrivateProperty(prop);
  10352. classBody.body.push(node);
  10353. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start);
  10354. }
  10355. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  10356. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  10357. }
  10358. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  10359. this.expectPlugin("classPrivateMethods", method.key.start);
  10360. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  10361. classBody.body.push(node);
  10362. 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;
  10363. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start);
  10364. }
  10365. parsePostMemberNameModifiers(methodOrProp) {}
  10366. parseClassPrivateProperty(node) {
  10367. this.parseInitializer(node);
  10368. this.semicolon();
  10369. return this.finishNode(node, "ClassPrivateProperty");
  10370. }
  10371. parseClassProperty(node) {
  10372. if (!node.typeAnnotation || this.match(types.eq)) {
  10373. this.expectPlugin("classProperties");
  10374. }
  10375. this.parseInitializer(node);
  10376. this.semicolon();
  10377. return this.finishNode(node, "ClassProperty");
  10378. }
  10379. parseInitializer(node) {
  10380. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10381. this.expressionScope.enter(newExpressionScope());
  10382. this.prodParam.enter(PARAM);
  10383. node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
  10384. this.expressionScope.exit();
  10385. this.prodParam.exit();
  10386. this.scope.exit();
  10387. }
  10388. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  10389. if (this.match(types.name)) {
  10390. node.id = this.parseIdentifier();
  10391. if (isStatement) {
  10392. this.checkLVal(node.id, "class name", bindingType);
  10393. }
  10394. } else {
  10395. if (optionalId || !isStatement) {
  10396. node.id = null;
  10397. } else {
  10398. this.unexpected(null, ErrorMessages.MissingClassName);
  10399. }
  10400. }
  10401. }
  10402. parseClassSuper(node) {
  10403. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  10404. }
  10405. parseExport(node) {
  10406. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  10407. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  10408. const hasStar = parseAfterDefault && this.eatExportStar(node);
  10409. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  10410. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  10411. const isFromRequired = hasDefault || hasStar;
  10412. if (hasStar && !hasNamespace) {
  10413. if (hasDefault) this.unexpected();
  10414. this.parseExportFrom(node, true);
  10415. return this.finishNode(node, "ExportAllDeclaration");
  10416. }
  10417. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  10418. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  10419. throw this.unexpected(null, types.braceL);
  10420. }
  10421. let hasDeclaration;
  10422. if (isFromRequired || hasSpecifiers) {
  10423. hasDeclaration = false;
  10424. this.parseExportFrom(node, isFromRequired);
  10425. } else {
  10426. hasDeclaration = this.maybeParseExportDeclaration(node);
  10427. }
  10428. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  10429. this.checkExport(node, true, false, !!node.source);
  10430. return this.finishNode(node, "ExportNamedDeclaration");
  10431. }
  10432. if (this.eat(types._default)) {
  10433. node.declaration = this.parseExportDefaultExpression();
  10434. this.checkExport(node, true, true);
  10435. return this.finishNode(node, "ExportDefaultDeclaration");
  10436. }
  10437. throw this.unexpected(null, types.braceL);
  10438. }
  10439. eatExportStar(node) {
  10440. return this.eat(types.star);
  10441. }
  10442. maybeParseExportDefaultSpecifier(node) {
  10443. if (this.isExportDefaultSpecifier()) {
  10444. this.expectPlugin("exportDefaultFrom");
  10445. const specifier = this.startNode();
  10446. specifier.exported = this.parseIdentifier(true);
  10447. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10448. return true;
  10449. }
  10450. return false;
  10451. }
  10452. maybeParseExportNamespaceSpecifier(node) {
  10453. if (this.isContextual("as")) {
  10454. if (!node.specifiers) node.specifiers = [];
  10455. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  10456. this.next();
  10457. specifier.exported = this.parseModuleExportName();
  10458. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  10459. return true;
  10460. }
  10461. return false;
  10462. }
  10463. maybeParseExportNamedSpecifiers(node) {
  10464. if (this.match(types.braceL)) {
  10465. if (!node.specifiers) node.specifiers = [];
  10466. node.specifiers.push(...this.parseExportSpecifiers());
  10467. node.source = null;
  10468. node.declaration = null;
  10469. return true;
  10470. }
  10471. return false;
  10472. }
  10473. maybeParseExportDeclaration(node) {
  10474. if (this.shouldParseExportDeclaration()) {
  10475. node.specifiers = [];
  10476. node.source = null;
  10477. node.declaration = this.parseExportDeclaration(node);
  10478. return true;
  10479. }
  10480. return false;
  10481. }
  10482. isAsyncFunction() {
  10483. if (!this.isContextual("async")) return false;
  10484. const next = this.nextTokenStart();
  10485. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10486. }
  10487. parseExportDefaultExpression() {
  10488. const expr = this.startNode();
  10489. const isAsync = this.isAsyncFunction();
  10490. if (this.match(types._function) || isAsync) {
  10491. this.next();
  10492. if (isAsync) {
  10493. this.next();
  10494. }
  10495. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10496. } else if (this.match(types._class)) {
  10497. return this.parseClass(expr, true, true);
  10498. } else if (this.match(types.at)) {
  10499. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10500. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10501. }
  10502. this.parseDecorators(false);
  10503. return this.parseClass(expr, true, true);
  10504. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10505. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  10506. } else {
  10507. const res = this.parseMaybeAssignAllowIn();
  10508. this.semicolon();
  10509. return res;
  10510. }
  10511. }
  10512. parseExportDeclaration(node) {
  10513. return this.parseStatement(null);
  10514. }
  10515. isExportDefaultSpecifier() {
  10516. if (this.match(types.name)) {
  10517. const value = this.state.value;
  10518. if (value === "async" && !this.state.containsEsc || value === "let") {
  10519. return false;
  10520. }
  10521. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  10522. const l = this.lookahead();
  10523. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  10524. this.expectOnePlugin(["flow", "typescript"]);
  10525. return false;
  10526. }
  10527. }
  10528. } else if (!this.match(types._default)) {
  10529. return false;
  10530. }
  10531. const next = this.nextTokenStart();
  10532. const hasFrom = this.isUnparsedContextual(next, "from");
  10533. if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
  10534. return true;
  10535. }
  10536. if (this.match(types._default) && hasFrom) {
  10537. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  10538. return nextAfterFrom === 34 || nextAfterFrom === 39;
  10539. }
  10540. return false;
  10541. }
  10542. parseExportFrom(node, expect) {
  10543. if (this.eatContextual("from")) {
  10544. node.source = this.parseImportSource();
  10545. this.checkExport(node);
  10546. const assertions = this.maybeParseImportAssertions();
  10547. if (assertions) {
  10548. node.assertions = assertions;
  10549. }
  10550. } else {
  10551. if (expect) {
  10552. this.unexpected();
  10553. } else {
  10554. node.source = null;
  10555. }
  10556. }
  10557. this.semicolon();
  10558. }
  10559. shouldParseExportDeclaration() {
  10560. if (this.match(types.at)) {
  10561. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  10562. if (this.hasPlugin("decorators")) {
  10563. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10564. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10565. } else {
  10566. return true;
  10567. }
  10568. }
  10569. }
  10570. 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();
  10571. }
  10572. checkExport(node, checkNames, isDefault, isFrom) {
  10573. if (checkNames) {
  10574. if (isDefault) {
  10575. this.checkDuplicateExports(node, "default");
  10576. if (this.hasPlugin("exportDefaultFrom")) {
  10577. var _declaration$extra;
  10578. const declaration = node.declaration;
  10579. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) == null ? void 0 : _declaration$extra.parenthesized)) {
  10580. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  10581. }
  10582. }
  10583. } else if (node.specifiers && node.specifiers.length) {
  10584. for (let _i3 = 0, _node$specifiers = node.specifiers; _i3 < _node$specifiers.length; _i3++) {
  10585. const specifier = _node$specifiers[_i3];
  10586. const {
  10587. exported
  10588. } = specifier;
  10589. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  10590. this.checkDuplicateExports(specifier, exportedName);
  10591. if (!isFrom && specifier.local) {
  10592. const {
  10593. local
  10594. } = specifier;
  10595. if (local.type === "StringLiteral") {
  10596. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName);
  10597. } else {
  10598. this.checkReservedWord(local.name, local.start, true, false);
  10599. this.scope.checkLocalExport(local);
  10600. }
  10601. }
  10602. }
  10603. } else if (node.declaration) {
  10604. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  10605. const id = node.declaration.id;
  10606. if (!id) throw new Error("Assertion failure");
  10607. this.checkDuplicateExports(node, id.name);
  10608. } else if (node.declaration.type === "VariableDeclaration") {
  10609. for (let _i4 = 0, _node$declaration$dec = node.declaration.declarations; _i4 < _node$declaration$dec.length; _i4++) {
  10610. const declaration = _node$declaration$dec[_i4];
  10611. this.checkDeclaration(declaration.id);
  10612. }
  10613. }
  10614. }
  10615. }
  10616. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10617. if (currentContextDecorators.length) {
  10618. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  10619. }
  10620. }
  10621. checkDeclaration(node) {
  10622. if (node.type === "Identifier") {
  10623. this.checkDuplicateExports(node, node.name);
  10624. } else if (node.type === "ObjectPattern") {
  10625. for (let _i5 = 0, _node$properties = node.properties; _i5 < _node$properties.length; _i5++) {
  10626. const prop = _node$properties[_i5];
  10627. this.checkDeclaration(prop);
  10628. }
  10629. } else if (node.type === "ArrayPattern") {
  10630. for (let _i6 = 0, _node$elements = node.elements; _i6 < _node$elements.length; _i6++) {
  10631. const elem = _node$elements[_i6];
  10632. if (elem) {
  10633. this.checkDeclaration(elem);
  10634. }
  10635. }
  10636. } else if (node.type === "ObjectProperty") {
  10637. this.checkDeclaration(node.value);
  10638. } else if (node.type === "RestElement") {
  10639. this.checkDeclaration(node.argument);
  10640. } else if (node.type === "AssignmentPattern") {
  10641. this.checkDeclaration(node.left);
  10642. }
  10643. }
  10644. checkDuplicateExports(node, name) {
  10645. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  10646. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  10647. }
  10648. this.state.exportedIdentifiers.push(name);
  10649. }
  10650. parseExportSpecifiers() {
  10651. const nodes = [];
  10652. let first = true;
  10653. this.expect(types.braceL);
  10654. while (!this.eat(types.braceR)) {
  10655. if (first) {
  10656. first = false;
  10657. } else {
  10658. this.expect(types.comma);
  10659. if (this.eat(types.braceR)) break;
  10660. }
  10661. const node = this.startNode();
  10662. node.local = this.parseModuleExportName();
  10663. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
  10664. nodes.push(this.finishNode(node, "ExportSpecifier"));
  10665. }
  10666. return nodes;
  10667. }
  10668. parseModuleExportName() {
  10669. if (this.match(types.string)) {
  10670. this.expectPlugin("moduleStringNames");
  10671. const result = this.parseLiteral(this.state.value, "StringLiteral");
  10672. const surrogate = result.value.match(loneSurrogate);
  10673. if (surrogate) {
  10674. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  10675. }
  10676. return result;
  10677. }
  10678. return this.parseIdentifier(true);
  10679. }
  10680. parseImport(node) {
  10681. node.specifiers = [];
  10682. if (!this.match(types.string)) {
  10683. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  10684. const parseNext = !hasDefault || this.eat(types.comma);
  10685. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  10686. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  10687. this.expectContextual("from");
  10688. }
  10689. node.source = this.parseImportSource();
  10690. const assertions = this.maybeParseImportAssertions();
  10691. if (assertions) {
  10692. node.assertions = assertions;
  10693. } else {
  10694. const attributes = this.maybeParseModuleAttributes();
  10695. if (attributes) {
  10696. node.attributes = attributes;
  10697. }
  10698. }
  10699. this.semicolon();
  10700. return this.finishNode(node, "ImportDeclaration");
  10701. }
  10702. parseImportSource() {
  10703. if (!this.match(types.string)) this.unexpected();
  10704. return this.parseExprAtom();
  10705. }
  10706. shouldParseDefaultImport(node) {
  10707. return this.match(types.name);
  10708. }
  10709. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  10710. specifier.local = this.parseIdentifier();
  10711. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  10712. node.specifiers.push(this.finishNode(specifier, type));
  10713. }
  10714. parseAssertEntries() {
  10715. const attrs = [];
  10716. const attrNames = new Set();
  10717. do {
  10718. if (this.match(types.braceR)) {
  10719. break;
  10720. }
  10721. const node = this.startNode();
  10722. const keyName = this.state.value;
  10723. if (this.match(types.string)) {
  10724. node.key = this.parseLiteral(keyName, "StringLiteral");
  10725. } else {
  10726. node.key = this.parseIdentifier(true);
  10727. }
  10728. this.expect(types.colon);
  10729. if (keyName !== "type") {
  10730. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName);
  10731. }
  10732. if (attrNames.has(keyName)) {
  10733. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  10734. }
  10735. attrNames.add(keyName);
  10736. if (!this.match(types.string)) {
  10737. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  10738. }
  10739. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  10740. this.finishNode(node, "ImportAttribute");
  10741. attrs.push(node);
  10742. } while (this.eat(types.comma));
  10743. return attrs;
  10744. }
  10745. maybeParseModuleAttributes() {
  10746. if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
  10747. this.expectPlugin("moduleAttributes");
  10748. this.next();
  10749. } else {
  10750. if (this.hasPlugin("moduleAttributes")) return [];
  10751. return null;
  10752. }
  10753. const attrs = [];
  10754. const attributes = new Set();
  10755. do {
  10756. const node = this.startNode();
  10757. node.key = this.parseIdentifier(true);
  10758. if (node.key.name !== "type") {
  10759. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  10760. }
  10761. if (attributes.has(node.key.name)) {
  10762. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  10763. }
  10764. attributes.add(node.key.name);
  10765. this.expect(types.colon);
  10766. if (!this.match(types.string)) {
  10767. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  10768. }
  10769. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  10770. this.finishNode(node, "ImportAttribute");
  10771. attrs.push(node);
  10772. } while (this.eat(types.comma));
  10773. return attrs;
  10774. }
  10775. maybeParseImportAssertions() {
  10776. if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) {
  10777. this.expectPlugin("importAssertions");
  10778. this.next();
  10779. } else {
  10780. if (this.hasPlugin("importAssertions")) return [];
  10781. return null;
  10782. }
  10783. this.eat(types.braceL);
  10784. const attrs = this.parseAssertEntries();
  10785. this.eat(types.braceR);
  10786. return attrs;
  10787. }
  10788. maybeParseDefaultImportSpecifier(node) {
  10789. if (this.shouldParseDefaultImport(node)) {
  10790. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  10791. return true;
  10792. }
  10793. return false;
  10794. }
  10795. maybeParseStarImportSpecifier(node) {
  10796. if (this.match(types.star)) {
  10797. const specifier = this.startNode();
  10798. this.next();
  10799. this.expectContextual("as");
  10800. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  10801. return true;
  10802. }
  10803. return false;
  10804. }
  10805. parseNamedImportSpecifiers(node) {
  10806. let first = true;
  10807. this.expect(types.braceL);
  10808. while (!this.eat(types.braceR)) {
  10809. if (first) {
  10810. first = false;
  10811. } else {
  10812. if (this.eat(types.colon)) {
  10813. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  10814. }
  10815. this.expect(types.comma);
  10816. if (this.eat(types.braceR)) break;
  10817. }
  10818. this.parseImportSpecifier(node);
  10819. }
  10820. }
  10821. parseImportSpecifier(node) {
  10822. const specifier = this.startNode();
  10823. specifier.imported = this.parseModuleExportName();
  10824. if (this.eatContextual("as")) {
  10825. specifier.local = this.parseIdentifier();
  10826. } else {
  10827. const {
  10828. imported
  10829. } = specifier;
  10830. if (imported.type === "StringLiteral") {
  10831. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  10832. }
  10833. this.checkReservedWord(imported.name, specifier.start, true, true);
  10834. specifier.local = imported.__clone();
  10835. }
  10836. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  10837. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  10838. }
  10839. }
  10840. class ClassScope {
  10841. constructor() {
  10842. this.privateNames = new Set();
  10843. this.loneAccessors = new Map();
  10844. this.undefinedPrivateNames = new Map();
  10845. }
  10846. }
  10847. class ClassScopeHandler {
  10848. constructor(raise) {
  10849. this.stack = [];
  10850. this.undefinedPrivateNames = new Map();
  10851. this.raise = raise;
  10852. }
  10853. current() {
  10854. return this.stack[this.stack.length - 1];
  10855. }
  10856. enter() {
  10857. this.stack.push(new ClassScope());
  10858. }
  10859. exit() {
  10860. const oldClassScope = this.stack.pop();
  10861. const current = this.current();
  10862. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  10863. const [name, pos] = _Array$from[_i];
  10864. if (current) {
  10865. if (!current.undefinedPrivateNames.has(name)) {
  10866. current.undefinedPrivateNames.set(name, pos);
  10867. }
  10868. } else {
  10869. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  10870. }
  10871. }
  10872. }
  10873. declarePrivateName(name, elementType, pos) {
  10874. const classScope = this.current();
  10875. let redefined = classScope.privateNames.has(name);
  10876. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  10877. const accessor = redefined && classScope.loneAccessors.get(name);
  10878. if (accessor) {
  10879. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  10880. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  10881. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  10882. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  10883. redefined = oldKind === newKind || oldStatic !== newStatic;
  10884. if (!redefined) classScope.loneAccessors.delete(name);
  10885. } else if (!redefined) {
  10886. classScope.loneAccessors.set(name, elementType);
  10887. }
  10888. }
  10889. if (redefined) {
  10890. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  10891. }
  10892. classScope.privateNames.add(name);
  10893. classScope.undefinedPrivateNames.delete(name);
  10894. }
  10895. usePrivateName(name, pos) {
  10896. let classScope;
  10897. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  10898. classScope = _this$stack[_i2];
  10899. if (classScope.privateNames.has(name)) return;
  10900. }
  10901. if (classScope) {
  10902. classScope.undefinedPrivateNames.set(name, pos);
  10903. } else {
  10904. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  10905. }
  10906. }
  10907. }
  10908. class Parser extends StatementParser {
  10909. constructor(options, input) {
  10910. options = getOptions(options);
  10911. super(options, input);
  10912. const ScopeHandler = this.getScopeHandler();
  10913. this.options = options;
  10914. this.inModule = this.options.sourceType === "module";
  10915. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  10916. this.prodParam = new ProductionParameterHandler();
  10917. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  10918. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  10919. this.plugins = pluginsMap(this.options.plugins);
  10920. this.filename = options.sourceFilename;
  10921. }
  10922. getScopeHandler() {
  10923. return ScopeHandler;
  10924. }
  10925. parse() {
  10926. let paramFlags = PARAM;
  10927. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  10928. paramFlags |= PARAM_AWAIT;
  10929. }
  10930. this.scope.enter(SCOPE_PROGRAM);
  10931. this.prodParam.enter(paramFlags);
  10932. const file = this.startNode();
  10933. const program = this.startNode();
  10934. this.nextToken();
  10935. file.errors = null;
  10936. this.parseTopLevel(file, program);
  10937. file.errors = this.state.errors;
  10938. return file;
  10939. }
  10940. }
  10941. function pluginsMap(plugins) {
  10942. const pluginMap = new Map();
  10943. for (let _i = 0; _i < plugins.length; _i++) {
  10944. const plugin = plugins[_i];
  10945. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  10946. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  10947. }
  10948. return pluginMap;
  10949. }
  10950. function parse(input, options) {
  10951. var _options;
  10952. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  10953. options = Object.assign({}, options);
  10954. try {
  10955. options.sourceType = "module";
  10956. const parser = getParser(options, input);
  10957. const ast = parser.parse();
  10958. if (parser.sawUnambiguousESM) {
  10959. return ast;
  10960. }
  10961. if (parser.ambiguousScriptDifferentAst) {
  10962. try {
  10963. options.sourceType = "script";
  10964. return getParser(options, input).parse();
  10965. } catch (_unused) {}
  10966. } else {
  10967. ast.program.sourceType = "script";
  10968. }
  10969. return ast;
  10970. } catch (moduleError) {
  10971. try {
  10972. options.sourceType = "script";
  10973. return getParser(options, input).parse();
  10974. } catch (_unused2) {}
  10975. throw moduleError;
  10976. }
  10977. } else {
  10978. return getParser(options, input).parse();
  10979. }
  10980. }
  10981. function parseExpression(input, options) {
  10982. const parser = getParser(options, input);
  10983. if (parser.options.strictMode) {
  10984. parser.state.strict = true;
  10985. }
  10986. return parser.getExpression();
  10987. }
  10988. function getParser(options, input) {
  10989. let cls = Parser;
  10990. if (options == null ? void 0 : options.plugins) {
  10991. validatePlugins(options.plugins);
  10992. cls = getParserClass(options.plugins);
  10993. }
  10994. return new cls(options, input);
  10995. }
  10996. const parserClassCache = {};
  10997. function getParserClass(pluginsFromOptions) {
  10998. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  10999. const key = pluginList.join("/");
  11000. let cls = parserClassCache[key];
  11001. if (!cls) {
  11002. cls = Parser;
  11003. for (let _i = 0; _i < pluginList.length; _i++) {
  11004. const plugin = pluginList[_i];
  11005. cls = mixinPlugins[plugin](cls);
  11006. }
  11007. parserClassCache[key] = cls;
  11008. }
  11009. return cls;
  11010. }
  11011. exports.parse = parse;
  11012. exports.parseExpression = parseExpression;
  11013. exports.tokTypes = types;
  11014. //# sourceMappingURL=index.js.map