index.js 402 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429
  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 SCOPE_OTHER = 0b00000000,
  285. SCOPE_PROGRAM = 0b00000001,
  286. SCOPE_FUNCTION = 0b00000010,
  287. SCOPE_ARROW = 0b00000100,
  288. SCOPE_SIMPLE_CATCH = 0b00001000,
  289. SCOPE_SUPER = 0b00010000,
  290. SCOPE_DIRECT_SUPER = 0b00100000,
  291. SCOPE_CLASS = 0b01000000,
  292. SCOPE_TS_MODULE = 0b10000000,
  293. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  294. const BIND_KIND_VALUE = 0b00000000001,
  295. BIND_KIND_TYPE = 0b00000000010,
  296. BIND_SCOPE_VAR = 0b00000000100,
  297. BIND_SCOPE_LEXICAL = 0b00000001000,
  298. BIND_SCOPE_FUNCTION = 0b00000010000,
  299. BIND_FLAGS_NONE = 0b00001000000,
  300. BIND_FLAGS_CLASS = 0b00010000000,
  301. BIND_FLAGS_TS_ENUM = 0b00100000000,
  302. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  303. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  304. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  305. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  306. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  307. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  308. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  309. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  310. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  311. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  312. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  313. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  314. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  315. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  316. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  317. CLASS_ELEMENT_KIND_GETTER = 0b010,
  318. CLASS_ELEMENT_KIND_SETTER = 0b001,
  319. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  320. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  321. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  322. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  323. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  324. CLASS_ELEMENT_OTHER = 0;
  325. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  326. const lineBreakG = new RegExp(lineBreak.source, "g");
  327. function isNewLine(code) {
  328. switch (code) {
  329. case 10:
  330. case 13:
  331. case 8232:
  332. case 8233:
  333. return true;
  334. default:
  335. return false;
  336. }
  337. }
  338. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  339. function isWhitespace(code) {
  340. switch (code) {
  341. case 0x0009:
  342. case 0x000b:
  343. case 0x000c:
  344. case 32:
  345. case 160:
  346. case 5760:
  347. case 0x2000:
  348. case 0x2001:
  349. case 0x2002:
  350. case 0x2003:
  351. case 0x2004:
  352. case 0x2005:
  353. case 0x2006:
  354. case 0x2007:
  355. case 0x2008:
  356. case 0x2009:
  357. case 0x200a:
  358. case 0x202f:
  359. case 0x205f:
  360. case 0x3000:
  361. case 0xfeff:
  362. return true;
  363. default:
  364. return false;
  365. }
  366. }
  367. class Position {
  368. constructor(line, col) {
  369. this.line = void 0;
  370. this.column = void 0;
  371. this.line = line;
  372. this.column = col;
  373. }
  374. }
  375. class SourceLocation {
  376. constructor(start, end) {
  377. this.start = void 0;
  378. this.end = void 0;
  379. this.filename = void 0;
  380. this.identifierName = void 0;
  381. this.start = start;
  382. this.end = end;
  383. }
  384. }
  385. function getLineInfo(input, offset) {
  386. let line = 1;
  387. let lineStart = 0;
  388. let match;
  389. lineBreakG.lastIndex = 0;
  390. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  391. line++;
  392. lineStart = lineBreakG.lastIndex;
  393. }
  394. return new Position(line, offset - lineStart);
  395. }
  396. class BaseParser {
  397. constructor() {
  398. this.options = void 0;
  399. this.inModule = void 0;
  400. this.scope = void 0;
  401. this.classScope = void 0;
  402. this.prodParam = void 0;
  403. this.plugins = void 0;
  404. this.filename = void 0;
  405. this.sawUnambiguousESM = false;
  406. this.ambiguousScriptDifferentAst = false;
  407. this.state = void 0;
  408. this.input = void 0;
  409. this.length = void 0;
  410. }
  411. hasPlugin(name) {
  412. return this.plugins.has(name);
  413. }
  414. getPluginOption(plugin, name) {
  415. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  416. }
  417. }
  418. function last(stack) {
  419. return stack[stack.length - 1];
  420. }
  421. class CommentsParser extends BaseParser {
  422. addComment(comment) {
  423. if (this.filename) comment.loc.filename = this.filename;
  424. this.state.trailingComments.push(comment);
  425. this.state.leadingComments.push(comment);
  426. }
  427. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  428. if (this.state.leadingComments.length === 0) {
  429. return;
  430. }
  431. let lastElement = null;
  432. let i = elements.length;
  433. while (lastElement === null && i > 0) {
  434. lastElement = elements[--i];
  435. }
  436. if (lastElement === null) {
  437. return;
  438. }
  439. for (let j = 0; j < this.state.leadingComments.length; j++) {
  440. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  441. this.state.leadingComments.splice(j, 1);
  442. j--;
  443. }
  444. }
  445. const newTrailingComments = [];
  446. for (let i = 0; i < this.state.leadingComments.length; i++) {
  447. const leadingComment = this.state.leadingComments[i];
  448. if (leadingComment.end < node.end) {
  449. newTrailingComments.push(leadingComment);
  450. if (!takeAllComments) {
  451. this.state.leadingComments.splice(i, 1);
  452. i--;
  453. }
  454. } else {
  455. if (node.trailingComments === undefined) {
  456. node.trailingComments = [];
  457. }
  458. node.trailingComments.push(leadingComment);
  459. }
  460. }
  461. if (takeAllComments) this.state.leadingComments = [];
  462. if (newTrailingComments.length > 0) {
  463. lastElement.trailingComments = newTrailingComments;
  464. } else if (lastElement.trailingComments !== undefined) {
  465. lastElement.trailingComments = [];
  466. }
  467. }
  468. processComment(node) {
  469. if (node.type === "Program" && node.body.length > 0) return;
  470. const stack = this.state.commentStack;
  471. let firstChild, lastChild, trailingComments, i, j;
  472. if (this.state.trailingComments.length > 0) {
  473. if (this.state.trailingComments[0].start >= node.end) {
  474. trailingComments = this.state.trailingComments;
  475. this.state.trailingComments = [];
  476. } else {
  477. this.state.trailingComments.length = 0;
  478. }
  479. } else if (stack.length > 0) {
  480. const lastInStack = last(stack);
  481. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  482. trailingComments = lastInStack.trailingComments;
  483. delete lastInStack.trailingComments;
  484. }
  485. }
  486. if (stack.length > 0 && last(stack).start >= node.start) {
  487. firstChild = stack.pop();
  488. }
  489. while (stack.length > 0 && last(stack).start >= node.start) {
  490. lastChild = stack.pop();
  491. }
  492. if (!lastChild && firstChild) lastChild = firstChild;
  493. if (firstChild) {
  494. switch (node.type) {
  495. case "ObjectExpression":
  496. this.adjustCommentsAfterTrailingComma(node, node.properties);
  497. break;
  498. case "ObjectPattern":
  499. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  500. break;
  501. case "CallExpression":
  502. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  503. break;
  504. case "ArrayExpression":
  505. this.adjustCommentsAfterTrailingComma(node, node.elements);
  506. break;
  507. case "ArrayPattern":
  508. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  509. break;
  510. }
  511. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  512. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  513. }
  514. if (lastChild) {
  515. if (lastChild.leadingComments) {
  516. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  517. node.leadingComments = lastChild.leadingComments;
  518. delete lastChild.leadingComments;
  519. } else {
  520. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  521. if (lastChild.leadingComments[i].end <= node.start) {
  522. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  523. break;
  524. }
  525. }
  526. }
  527. }
  528. } else if (this.state.leadingComments.length > 0) {
  529. if (last(this.state.leadingComments).end <= node.start) {
  530. if (this.state.commentPreviousNode) {
  531. for (j = 0; j < this.state.leadingComments.length; j++) {
  532. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  533. this.state.leadingComments.splice(j, 1);
  534. j--;
  535. }
  536. }
  537. }
  538. if (this.state.leadingComments.length > 0) {
  539. node.leadingComments = this.state.leadingComments;
  540. this.state.leadingComments = [];
  541. }
  542. } else {
  543. for (i = 0; i < this.state.leadingComments.length; i++) {
  544. if (this.state.leadingComments[i].end > node.start) {
  545. break;
  546. }
  547. }
  548. const leadingComments = this.state.leadingComments.slice(0, i);
  549. if (leadingComments.length) {
  550. node.leadingComments = leadingComments;
  551. }
  552. trailingComments = this.state.leadingComments.slice(i);
  553. if (trailingComments.length === 0) {
  554. trailingComments = null;
  555. }
  556. }
  557. }
  558. this.state.commentPreviousNode = node;
  559. if (trailingComments) {
  560. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  561. node.innerComments = trailingComments;
  562. } else {
  563. const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end);
  564. if (firstTrailingCommentIndex > 0) {
  565. node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex);
  566. node.trailingComments = trailingComments.slice(firstTrailingCommentIndex);
  567. } else {
  568. node.trailingComments = trailingComments;
  569. }
  570. }
  571. }
  572. stack.push(node);
  573. }
  574. }
  575. const ErrorMessages = Object.freeze({
  576. AccessorIsGenerator: "A %0ter cannot be a generator",
  577. ArgumentsInClass: "'arguments' is only allowed in functions and class methods",
  578. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  579. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  580. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  581. AwaitNotInAsyncFunction: "Can not use keyword 'await' outside an async function",
  582. BadGetterArity: "getter must not have any formal parameters",
  583. BadSetterArity: "setter must have exactly one formal parameter",
  584. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  585. ConstructorClassField: "Classes may not have a field named 'constructor'",
  586. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  587. ConstructorIsAccessor: "Class constructor may not be an accessor",
  588. ConstructorIsAsync: "Constructor can't be an async function",
  589. ConstructorIsGenerator: "Constructor can't be a generator",
  590. DeclarationMissingInitializer: "%0 require an initialization value",
  591. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  592. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  593. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  594. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  595. DecoratorStaticBlock: "Decorators can't be used with a static block",
  596. DeletePrivateField: "Deleting a private field is not allowed",
  597. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  598. DuplicateConstructor: "Duplicate constructor in the same class",
  599. DuplicateDefaultExport: "Only one default export allowed per module.",
  600. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  601. DuplicateProto: "Redefinition of __proto__ property",
  602. DuplicateRegExpFlags: "Duplicate regular expression flag",
  603. DuplicateStaticBlock: "Duplicate static block in the same class",
  604. ElementAfterRest: "Rest element must be last element",
  605. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  606. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { %0 as '%1' } from 'some-module'`?",
  607. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'",
  608. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  609. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  610. IllegalBreakContinue: "Unsyntactic %0",
  611. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  612. IllegalReturn: "'return' outside of function",
  613. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  614. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  615. ImportCallArity: "import() requires exactly %0",
  616. ImportCallNotNewExpression: "Cannot use new with import(...)",
  617. ImportCallSpreadArgument: "... is not allowed in import()",
  618. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  619. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  620. InvalidBigIntLiteral: "Invalid BigIntLiteral",
  621. InvalidCodePoint: "Code point out of bounds",
  622. InvalidDecimal: "Invalid decimal",
  623. InvalidDigit: "Expected number in radix %0",
  624. InvalidEscapeSequence: "Bad character escape sequence",
  625. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  626. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  627. InvalidIdentifier: "Invalid identifier %0",
  628. InvalidLhs: "Invalid left-hand side in %0",
  629. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  630. InvalidNumber: "Invalid number",
  631. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'",
  632. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  633. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  634. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  635. InvalidPropertyBindingPattern: "Binding member expression",
  636. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions",
  637. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  638. LabelRedeclaration: "Label '%0' is already declared",
  639. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  640. LineTerminatorBeforeArrow: "No line break is allowed before '=>'",
  641. MalformedRegExpFlags: "Invalid regular expression flag",
  642. MissingClassName: "A class name is required",
  643. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  644. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  645. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  646. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
  647. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
  648. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
  649. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
  650. ModuleExportUndefined: "Export '%0' is not defined",
  651. MultipleDefaultsInSwitch: "Multiple default clauses",
  652. NewlineAfterThrow: "Illegal newline after throw",
  653. NoCatchOrFinally: "Missing catch or finally clause",
  654. NumberIdentifier: "Identifier directly after number",
  655. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  656. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  657. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  658. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  659. ParamDupe: "Argument name clash",
  660. PatternHasAccessor: "Object pattern can't contain getter or setter",
  661. PatternHasMethod: "Object pattern can't contain methods",
  662. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  663. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  664. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  665. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  666. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  667. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  668. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
  669. PrivateNameRedeclaration: "Duplicate private name #%0",
  670. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  671. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  672. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  673. RecordNoProto: "'__proto__' is not allowed in Record expressions",
  674. RestTrailingComma: "Unexpected trailing comma after rest element",
  675. 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",
  676. StaticPrototype: "Classes may not have static property named prototype",
  677. StrictDelete: "Deleting local variable in strict mode",
  678. StrictEvalArguments: "Assigning to '%0' in strict mode",
  679. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  680. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  681. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
  682. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  683. StrictWith: "'with' in strict mode",
  684. 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?",
  685. SuperPrivateField: "Private fields can't be accessed on super",
  686. TrailingDecorator: "Decorators must be attached to a class element",
  687. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  688. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  689. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  690. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  691. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  692. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  693. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  694. UnexpectedKeyword: "Unexpected keyword '%0'",
  695. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  696. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  697. UnexpectedNewTarget: "new.target can only be used in functions",
  698. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  699. 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).",
  700. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  701. UnexpectedSuper: "super is only allowed in object methods and classes",
  702. UnexpectedToken: "Unexpected token '%0'",
  703. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  704. UnsupportedBind: "Binding should be performed on object property.",
  705. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  706. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  707. UnsupportedImport: "import can only be used in import() or import.meta",
  708. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  709. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  710. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  711. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  712. UnterminatedComment: "Unterminated comment",
  713. UnterminatedRegExp: "Unterminated regular expression",
  714. UnterminatedString: "Unterminated string constant",
  715. UnterminatedTemplate: "Unterminated template",
  716. VarRedeclaration: "Identifier '%0' has already been declared",
  717. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  718. YieldInParameter: "yield is not allowed in generator parameters",
  719. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  720. });
  721. class ParserError extends CommentsParser {
  722. getLocationForPosition(pos) {
  723. let loc;
  724. 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);
  725. return loc;
  726. }
  727. raise(pos, errorTemplate, ...params) {
  728. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  729. }
  730. raiseWithData(pos, data, errorTemplate, ...params) {
  731. const loc = this.getLocationForPosition(pos);
  732. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  733. return this._raise(Object.assign({
  734. loc,
  735. pos
  736. }, data), message);
  737. }
  738. _raise(errorContext, message) {
  739. const err = new SyntaxError(message);
  740. Object.assign(err, errorContext);
  741. if (this.options.errorRecovery) {
  742. if (!this.isLookahead) this.state.errors.push(err);
  743. return err;
  744. } else {
  745. throw err;
  746. }
  747. }
  748. }
  749. function isSimpleProperty(node) {
  750. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  751. }
  752. var estree = (superClass => class extends superClass {
  753. estreeParseRegExpLiteral({
  754. pattern,
  755. flags
  756. }) {
  757. let regex = null;
  758. try {
  759. regex = new RegExp(pattern, flags);
  760. } catch (e) {}
  761. const node = this.estreeParseLiteral(regex);
  762. node.regex = {
  763. pattern,
  764. flags
  765. };
  766. return node;
  767. }
  768. estreeParseBigIntLiteral(value) {
  769. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  770. const node = this.estreeParseLiteral(bigInt);
  771. node.bigint = String(node.value || value);
  772. return node;
  773. }
  774. estreeParseDecimalLiteral(value) {
  775. const decimal = null;
  776. const node = this.estreeParseLiteral(decimal);
  777. node.decimal = String(node.value || value);
  778. return node;
  779. }
  780. estreeParseLiteral(value) {
  781. return this.parseLiteral(value, "Literal");
  782. }
  783. directiveToStmt(directive) {
  784. const directiveLiteral = directive.value;
  785. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  786. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  787. expression.value = directiveLiteral.value;
  788. expression.raw = directiveLiteral.extra.raw;
  789. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  790. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  791. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  792. }
  793. initFunction(node, isAsync) {
  794. super.initFunction(node, isAsync);
  795. node.expression = false;
  796. }
  797. checkDeclaration(node) {
  798. if (isSimpleProperty(node)) {
  799. this.checkDeclaration(node.value);
  800. } else {
  801. super.checkDeclaration(node);
  802. }
  803. }
  804. getObjectOrClassMethodParams(method) {
  805. return method.value.params;
  806. }
  807. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding) {
  808. switch (expr.type) {
  809. case "ObjectPattern":
  810. expr.properties.forEach(prop => {
  811. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  812. });
  813. break;
  814. default:
  815. super.checkLVal(expr, bindingType, checkClashes, contextDescription, disallowLetBinding);
  816. }
  817. }
  818. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  819. if (prop.method) {
  820. return;
  821. }
  822. super.checkProto(prop, isRecord, protoRef, refExpressionErrors);
  823. }
  824. isValidDirective(stmt) {
  825. var _stmt$expression$extr;
  826. 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);
  827. }
  828. stmtToDirective(stmt) {
  829. const directive = super.stmtToDirective(stmt);
  830. const value = stmt.expression.value;
  831. directive.value.value = value;
  832. return directive;
  833. }
  834. parseBlockBody(node, allowDirectives, topLevel, end) {
  835. super.parseBlockBody(node, allowDirectives, topLevel, end);
  836. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  837. node.body = directiveStatements.concat(node.body);
  838. delete node.directives;
  839. }
  840. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  841. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  842. if (method.typeParameters) {
  843. method.value.typeParameters = method.typeParameters;
  844. delete method.typeParameters;
  845. }
  846. classBody.body.push(method);
  847. }
  848. parseExprAtom(refExpressionErrors) {
  849. switch (this.state.type) {
  850. case types.num:
  851. case types.string:
  852. return this.estreeParseLiteral(this.state.value);
  853. case types.regexp:
  854. return this.estreeParseRegExpLiteral(this.state.value);
  855. case types.bigint:
  856. return this.estreeParseBigIntLiteral(this.state.value);
  857. case types.decimal:
  858. return this.estreeParseDecimalLiteral(this.state.value);
  859. case types._null:
  860. return this.estreeParseLiteral(null);
  861. case types._true:
  862. return this.estreeParseLiteral(true);
  863. case types._false:
  864. return this.estreeParseLiteral(false);
  865. default:
  866. return super.parseExprAtom(refExpressionErrors);
  867. }
  868. }
  869. parseLiteral(value, type, startPos, startLoc) {
  870. const node = super.parseLiteral(value, type, startPos, startLoc);
  871. node.raw = node.extra.raw;
  872. delete node.extra;
  873. return node;
  874. }
  875. parseFunctionBody(node, allowExpression, isMethod = false) {
  876. super.parseFunctionBody(node, allowExpression, isMethod);
  877. node.expression = node.body.type !== "BlockStatement";
  878. }
  879. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  880. let funcNode = this.startNode();
  881. funcNode.kind = node.kind;
  882. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  883. funcNode.type = "FunctionExpression";
  884. delete funcNode.kind;
  885. node.value = funcNode;
  886. type = type === "ClassMethod" ? "MethodDefinition" : type;
  887. return this.finishNode(node, type);
  888. }
  889. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  890. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  891. if (node) {
  892. node.type = "Property";
  893. if (node.kind === "method") node.kind = "init";
  894. node.shorthand = false;
  895. }
  896. return node;
  897. }
  898. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  899. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  900. if (node) {
  901. node.kind = "init";
  902. node.type = "Property";
  903. }
  904. return node;
  905. }
  906. toAssignable(node) {
  907. if (isSimpleProperty(node)) {
  908. this.toAssignable(node.value);
  909. return node;
  910. }
  911. return super.toAssignable(node);
  912. }
  913. toAssignableObjectExpressionProp(prop, isLast) {
  914. if (prop.kind === "get" || prop.kind === "set") {
  915. throw this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  916. } else if (prop.method) {
  917. throw this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  918. } else {
  919. super.toAssignableObjectExpressionProp(prop, isLast);
  920. }
  921. }
  922. finishCallExpression(node, optional) {
  923. super.finishCallExpression(node, optional);
  924. if (node.callee.type === "Import") {
  925. node.type = "ImportExpression";
  926. node.source = node.arguments[0];
  927. delete node.arguments;
  928. delete node.callee;
  929. }
  930. return node;
  931. }
  932. toReferencedListDeep(exprList, isParenthesizedExpr) {
  933. if (!exprList) {
  934. return;
  935. }
  936. super.toReferencedListDeep(exprList, isParenthesizedExpr);
  937. }
  938. parseExport(node) {
  939. super.parseExport(node);
  940. switch (node.type) {
  941. case "ExportAllDeclaration":
  942. node.exported = null;
  943. break;
  944. case "ExportNamedDeclaration":
  945. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  946. node.type = "ExportAllDeclaration";
  947. node.exported = node.specifiers[0].exported;
  948. delete node.specifiers;
  949. }
  950. break;
  951. }
  952. return node;
  953. }
  954. parseSubscript(base, startPos, startLoc, noCalls, state) {
  955. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  956. if (state.optionalChainMember) {
  957. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  958. node.type = node.type.substring(8);
  959. }
  960. if (state.stop) {
  961. const chain = this.startNodeAtNode(node);
  962. chain.expression = node;
  963. return this.finishNode(chain, "ChainExpression");
  964. }
  965. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  966. node.optional = false;
  967. }
  968. return node;
  969. }
  970. });
  971. class TokContext {
  972. constructor(token, isExpr, preserveSpace, override) {
  973. this.token = void 0;
  974. this.isExpr = void 0;
  975. this.preserveSpace = void 0;
  976. this.override = void 0;
  977. this.token = token;
  978. this.isExpr = !!isExpr;
  979. this.preserveSpace = !!preserveSpace;
  980. this.override = override;
  981. }
  982. }
  983. const types$1 = {
  984. braceStatement: new TokContext("{", false),
  985. braceExpression: new TokContext("{", true),
  986. recordExpression: new TokContext("#{", true),
  987. templateQuasi: new TokContext("${", false),
  988. parenStatement: new TokContext("(", false),
  989. parenExpression: new TokContext("(", true),
  990. template: new TokContext("`", true, true, p => p.readTmplToken()),
  991. functionExpression: new TokContext("function", true),
  992. functionStatement: new TokContext("function", false)
  993. };
  994. types.parenR.updateContext = types.braceR.updateContext = function () {
  995. if (this.state.context.length === 1) {
  996. this.state.exprAllowed = true;
  997. return;
  998. }
  999. let out = this.state.context.pop();
  1000. if (out === types$1.braceStatement && this.curContext().token === "function") {
  1001. out = this.state.context.pop();
  1002. }
  1003. this.state.exprAllowed = !out.isExpr;
  1004. };
  1005. types.name.updateContext = function (prevType) {
  1006. let allowed = false;
  1007. if (prevType !== types.dot) {
  1008. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class || this.state.value === "yield" && this.prodParam.hasYield) {
  1009. allowed = true;
  1010. }
  1011. }
  1012. this.state.exprAllowed = allowed;
  1013. if (this.state.isIterator) {
  1014. this.state.isIterator = false;
  1015. }
  1016. };
  1017. types.braceL.updateContext = function (prevType) {
  1018. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  1019. this.state.exprAllowed = true;
  1020. };
  1021. types.dollarBraceL.updateContext = function () {
  1022. this.state.context.push(types$1.templateQuasi);
  1023. this.state.exprAllowed = true;
  1024. };
  1025. types.parenL.updateContext = function (prevType) {
  1026. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  1027. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  1028. this.state.exprAllowed = true;
  1029. };
  1030. types.incDec.updateContext = function () {};
  1031. types._function.updateContext = types._class.updateContext = function (prevType) {
  1032. 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)) {
  1033. this.state.context.push(types$1.functionExpression);
  1034. } else {
  1035. this.state.context.push(types$1.functionStatement);
  1036. }
  1037. this.state.exprAllowed = false;
  1038. };
  1039. types.backQuote.updateContext = function () {
  1040. if (this.curContext() === types$1.template) {
  1041. this.state.context.pop();
  1042. } else {
  1043. this.state.context.push(types$1.template);
  1044. }
  1045. this.state.exprAllowed = false;
  1046. };
  1047. types.braceHashL.updateContext = function () {
  1048. this.state.context.push(types$1.recordExpression);
  1049. this.state.exprAllowed = true;
  1050. };
  1051. 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";
  1052. 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";
  1053. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1054. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1055. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1056. 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];
  1057. 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];
  1058. function isInAstralSet(code, set) {
  1059. let pos = 0x10000;
  1060. for (let i = 0, length = set.length; i < length; i += 2) {
  1061. pos += set[i];
  1062. if (pos > code) return false;
  1063. pos += set[i + 1];
  1064. if (pos >= code) return true;
  1065. }
  1066. return false;
  1067. }
  1068. function isIdentifierStart(code) {
  1069. if (code < 65) return code === 36;
  1070. if (code <= 90) return true;
  1071. if (code < 97) return code === 95;
  1072. if (code <= 122) return true;
  1073. if (code <= 0xffff) {
  1074. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1075. }
  1076. return isInAstralSet(code, astralIdentifierStartCodes);
  1077. }
  1078. function isIdentifierChar(code) {
  1079. if (code < 48) return code === 36;
  1080. if (code < 58) return true;
  1081. if (code < 65) return false;
  1082. if (code <= 90) return true;
  1083. if (code < 97) return code === 95;
  1084. if (code <= 122) return true;
  1085. if (code <= 0xffff) {
  1086. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1087. }
  1088. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1089. }
  1090. const reservedWords = {
  1091. 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"],
  1092. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1093. strictBind: ["eval", "arguments"]
  1094. };
  1095. const keywords$1 = new Set(reservedWords.keyword);
  1096. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1097. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1098. function isReservedWord(word, inModule) {
  1099. return inModule && word === "await" || word === "enum";
  1100. }
  1101. function isStrictReservedWord(word, inModule) {
  1102. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1103. }
  1104. function isStrictBindOnlyReservedWord(word) {
  1105. return reservedWordsStrictBindSet.has(word);
  1106. }
  1107. function isStrictBindReservedWord(word, inModule) {
  1108. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1109. }
  1110. function isKeyword(word) {
  1111. return keywords$1.has(word);
  1112. }
  1113. const keywordRelationalOperator = /^in(stanceof)?$/;
  1114. function isIteratorStart(current, next) {
  1115. return current === 64 && next === 64;
  1116. }
  1117. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1118. const FlowErrors = Object.freeze({
  1119. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1120. 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",
  1121. AssignReservedType: "Cannot overwrite reserved type %0",
  1122. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1123. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1124. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1125. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1126. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1127. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1128. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1129. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1130. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1131. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1132. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1133. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1134. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1135. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1136. 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",
  1137. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1138. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1139. InexactVariance: "Explicit inexact syntax cannot have variance",
  1140. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1141. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1142. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1143. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1144. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1145. SpreadVariance: "Spread properties cannot have variance",
  1146. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1147. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1148. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1149. UnexpectedReservedType: "Unexpected reserved type %0",
  1150. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1151. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1152. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1153. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1154. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1155. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  1156. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1157. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1158. UnterminatedFlowComment: "Unterminated flow-comment"
  1159. });
  1160. function isEsModuleType(bodyElement) {
  1161. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1162. }
  1163. function hasTypeImportKind(node) {
  1164. return node.importKind === "type" || node.importKind === "typeof";
  1165. }
  1166. function isMaybeDefaultImport(state) {
  1167. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1168. }
  1169. const exportSuggestions = {
  1170. const: "declare export var",
  1171. let: "declare export var",
  1172. type: "export type",
  1173. interface: "export interface"
  1174. };
  1175. function partition(list, test) {
  1176. const list1 = [];
  1177. const list2 = [];
  1178. for (let i = 0; i < list.length; i++) {
  1179. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1180. }
  1181. return [list1, list2];
  1182. }
  1183. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1184. var flow = (superClass => {
  1185. var _temp;
  1186. return _temp = class extends superClass {
  1187. constructor(options, input) {
  1188. super(options, input);
  1189. this.flowPragma = void 0;
  1190. this.flowPragma = undefined;
  1191. }
  1192. shouldParseTypes() {
  1193. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1194. }
  1195. shouldParseEnums() {
  1196. return !!this.getPluginOption("flow", "enums");
  1197. }
  1198. finishToken(type, val) {
  1199. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1200. if (this.flowPragma === undefined) {
  1201. this.flowPragma = null;
  1202. }
  1203. }
  1204. return super.finishToken(type, val);
  1205. }
  1206. addComment(comment) {
  1207. if (this.flowPragma === undefined) {
  1208. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1209. if (!matches) ; else if (matches[1] === "flow") {
  1210. this.flowPragma = "flow";
  1211. } else if (matches[1] === "noflow") {
  1212. this.flowPragma = "noflow";
  1213. } else {
  1214. throw new Error("Unexpected flow pragma");
  1215. }
  1216. }
  1217. return super.addComment(comment);
  1218. }
  1219. flowParseTypeInitialiser(tok) {
  1220. const oldInType = this.state.inType;
  1221. this.state.inType = true;
  1222. this.expect(tok || types.colon);
  1223. const type = this.flowParseType();
  1224. this.state.inType = oldInType;
  1225. return type;
  1226. }
  1227. flowParsePredicate() {
  1228. const node = this.startNode();
  1229. const moduloLoc = this.state.startLoc;
  1230. const moduloPos = this.state.start;
  1231. this.expect(types.modulo);
  1232. const checksLoc = this.state.startLoc;
  1233. this.expectContextual("checks");
  1234. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1235. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1236. }
  1237. if (this.eat(types.parenL)) {
  1238. node.value = this.parseExpression();
  1239. this.expect(types.parenR);
  1240. return this.finishNode(node, "DeclaredPredicate");
  1241. } else {
  1242. return this.finishNode(node, "InferredPredicate");
  1243. }
  1244. }
  1245. flowParseTypeAndPredicateInitialiser() {
  1246. const oldInType = this.state.inType;
  1247. this.state.inType = true;
  1248. this.expect(types.colon);
  1249. let type = null;
  1250. let predicate = null;
  1251. if (this.match(types.modulo)) {
  1252. this.state.inType = oldInType;
  1253. predicate = this.flowParsePredicate();
  1254. } else {
  1255. type = this.flowParseType();
  1256. this.state.inType = oldInType;
  1257. if (this.match(types.modulo)) {
  1258. predicate = this.flowParsePredicate();
  1259. }
  1260. }
  1261. return [type, predicate];
  1262. }
  1263. flowParseDeclareClass(node) {
  1264. this.next();
  1265. this.flowParseInterfaceish(node, true);
  1266. return this.finishNode(node, "DeclareClass");
  1267. }
  1268. flowParseDeclareFunction(node) {
  1269. this.next();
  1270. const id = node.id = this.parseIdentifier();
  1271. const typeNode = this.startNode();
  1272. const typeContainer = this.startNode();
  1273. if (this.isRelational("<")) {
  1274. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1275. } else {
  1276. typeNode.typeParameters = null;
  1277. }
  1278. this.expect(types.parenL);
  1279. const tmp = this.flowParseFunctionTypeParams();
  1280. typeNode.params = tmp.params;
  1281. typeNode.rest = tmp.rest;
  1282. this.expect(types.parenR);
  1283. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1284. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1285. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1286. this.resetEndLocation(id);
  1287. this.semicolon();
  1288. return this.finishNode(node, "DeclareFunction");
  1289. }
  1290. flowParseDeclare(node, insideModule) {
  1291. if (this.match(types._class)) {
  1292. return this.flowParseDeclareClass(node);
  1293. } else if (this.match(types._function)) {
  1294. return this.flowParseDeclareFunction(node);
  1295. } else if (this.match(types._var)) {
  1296. return this.flowParseDeclareVariable(node);
  1297. } else if (this.eatContextual("module")) {
  1298. if (this.match(types.dot)) {
  1299. return this.flowParseDeclareModuleExports(node);
  1300. } else {
  1301. if (insideModule) {
  1302. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1303. }
  1304. return this.flowParseDeclareModule(node);
  1305. }
  1306. } else if (this.isContextual("type")) {
  1307. return this.flowParseDeclareTypeAlias(node);
  1308. } else if (this.isContextual("opaque")) {
  1309. return this.flowParseDeclareOpaqueType(node);
  1310. } else if (this.isContextual("interface")) {
  1311. return this.flowParseDeclareInterface(node);
  1312. } else if (this.match(types._export)) {
  1313. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1314. } else {
  1315. throw this.unexpected();
  1316. }
  1317. }
  1318. flowParseDeclareVariable(node) {
  1319. this.next();
  1320. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1321. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1322. this.semicolon();
  1323. return this.finishNode(node, "DeclareVariable");
  1324. }
  1325. flowParseDeclareModule(node) {
  1326. this.scope.enter(SCOPE_OTHER);
  1327. if (this.match(types.string)) {
  1328. node.id = this.parseExprAtom();
  1329. } else {
  1330. node.id = this.parseIdentifier();
  1331. }
  1332. const bodyNode = node.body = this.startNode();
  1333. const body = bodyNode.body = [];
  1334. this.expect(types.braceL);
  1335. while (!this.match(types.braceR)) {
  1336. let bodyNode = this.startNode();
  1337. if (this.match(types._import)) {
  1338. this.next();
  1339. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1340. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1341. }
  1342. this.parseImport(bodyNode);
  1343. } else {
  1344. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1345. bodyNode = this.flowParseDeclare(bodyNode, true);
  1346. }
  1347. body.push(bodyNode);
  1348. }
  1349. this.scope.exit();
  1350. this.expect(types.braceR);
  1351. this.finishNode(bodyNode, "BlockStatement");
  1352. let kind = null;
  1353. let hasModuleExport = false;
  1354. body.forEach(bodyElement => {
  1355. if (isEsModuleType(bodyElement)) {
  1356. if (kind === "CommonJS") {
  1357. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1358. }
  1359. kind = "ES";
  1360. } else if (bodyElement.type === "DeclareModuleExports") {
  1361. if (hasModuleExport) {
  1362. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1363. }
  1364. if (kind === "ES") {
  1365. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1366. }
  1367. kind = "CommonJS";
  1368. hasModuleExport = true;
  1369. }
  1370. });
  1371. node.kind = kind || "CommonJS";
  1372. return this.finishNode(node, "DeclareModule");
  1373. }
  1374. flowParseDeclareExportDeclaration(node, insideModule) {
  1375. this.expect(types._export);
  1376. if (this.eat(types._default)) {
  1377. if (this.match(types._function) || this.match(types._class)) {
  1378. node.declaration = this.flowParseDeclare(this.startNode());
  1379. } else {
  1380. node.declaration = this.flowParseType();
  1381. this.semicolon();
  1382. }
  1383. node.default = true;
  1384. return this.finishNode(node, "DeclareExportDeclaration");
  1385. } else {
  1386. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1387. const label = this.state.value;
  1388. const suggestion = exportSuggestions[label];
  1389. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1390. }
  1391. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1392. node.declaration = this.flowParseDeclare(this.startNode());
  1393. node.default = false;
  1394. return this.finishNode(node, "DeclareExportDeclaration");
  1395. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1396. node = this.parseExport(node);
  1397. if (node.type === "ExportNamedDeclaration") {
  1398. node.type = "ExportDeclaration";
  1399. node.default = false;
  1400. delete node.exportKind;
  1401. }
  1402. node.type = "Declare" + node.type;
  1403. return node;
  1404. }
  1405. }
  1406. throw this.unexpected();
  1407. }
  1408. flowParseDeclareModuleExports(node) {
  1409. this.next();
  1410. this.expectContextual("exports");
  1411. node.typeAnnotation = this.flowParseTypeAnnotation();
  1412. this.semicolon();
  1413. return this.finishNode(node, "DeclareModuleExports");
  1414. }
  1415. flowParseDeclareTypeAlias(node) {
  1416. this.next();
  1417. this.flowParseTypeAlias(node);
  1418. node.type = "DeclareTypeAlias";
  1419. return node;
  1420. }
  1421. flowParseDeclareOpaqueType(node) {
  1422. this.next();
  1423. this.flowParseOpaqueType(node, true);
  1424. node.type = "DeclareOpaqueType";
  1425. return node;
  1426. }
  1427. flowParseDeclareInterface(node) {
  1428. this.next();
  1429. this.flowParseInterfaceish(node);
  1430. return this.finishNode(node, "DeclareInterface");
  1431. }
  1432. flowParseInterfaceish(node, isClass = false) {
  1433. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1434. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1435. if (this.isRelational("<")) {
  1436. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1437. } else {
  1438. node.typeParameters = null;
  1439. }
  1440. node.extends = [];
  1441. node.implements = [];
  1442. node.mixins = [];
  1443. if (this.eat(types._extends)) {
  1444. do {
  1445. node.extends.push(this.flowParseInterfaceExtends());
  1446. } while (!isClass && this.eat(types.comma));
  1447. }
  1448. if (this.isContextual("mixins")) {
  1449. this.next();
  1450. do {
  1451. node.mixins.push(this.flowParseInterfaceExtends());
  1452. } while (this.eat(types.comma));
  1453. }
  1454. if (this.isContextual("implements")) {
  1455. this.next();
  1456. do {
  1457. node.implements.push(this.flowParseInterfaceExtends());
  1458. } while (this.eat(types.comma));
  1459. }
  1460. node.body = this.flowParseObjectType({
  1461. allowStatic: isClass,
  1462. allowExact: false,
  1463. allowSpread: false,
  1464. allowProto: isClass,
  1465. allowInexact: false
  1466. });
  1467. }
  1468. flowParseInterfaceExtends() {
  1469. const node = this.startNode();
  1470. node.id = this.flowParseQualifiedTypeIdentifier();
  1471. if (this.isRelational("<")) {
  1472. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1473. } else {
  1474. node.typeParameters = null;
  1475. }
  1476. return this.finishNode(node, "InterfaceExtends");
  1477. }
  1478. flowParseInterface(node) {
  1479. this.flowParseInterfaceish(node);
  1480. return this.finishNode(node, "InterfaceDeclaration");
  1481. }
  1482. checkNotUnderscore(word) {
  1483. if (word === "_") {
  1484. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1485. }
  1486. }
  1487. checkReservedType(word, startLoc, declaration) {
  1488. if (!reservedTypes.has(word)) return;
  1489. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1490. }
  1491. flowParseRestrictedIdentifier(liberal, declaration) {
  1492. this.checkReservedType(this.state.value, this.state.start, declaration);
  1493. return this.parseIdentifier(liberal);
  1494. }
  1495. flowParseTypeAlias(node) {
  1496. node.id = this.flowParseRestrictedIdentifier(false, true);
  1497. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1498. if (this.isRelational("<")) {
  1499. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1500. } else {
  1501. node.typeParameters = null;
  1502. }
  1503. node.right = this.flowParseTypeInitialiser(types.eq);
  1504. this.semicolon();
  1505. return this.finishNode(node, "TypeAlias");
  1506. }
  1507. flowParseOpaqueType(node, declare) {
  1508. this.expectContextual("type");
  1509. node.id = this.flowParseRestrictedIdentifier(true, true);
  1510. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1511. if (this.isRelational("<")) {
  1512. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1513. } else {
  1514. node.typeParameters = null;
  1515. }
  1516. node.supertype = null;
  1517. if (this.match(types.colon)) {
  1518. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1519. }
  1520. node.impltype = null;
  1521. if (!declare) {
  1522. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1523. }
  1524. this.semicolon();
  1525. return this.finishNode(node, "OpaqueType");
  1526. }
  1527. flowParseTypeParameter(requireDefault = false) {
  1528. const nodeStart = this.state.start;
  1529. const node = this.startNode();
  1530. const variance = this.flowParseVariance();
  1531. const ident = this.flowParseTypeAnnotatableIdentifier();
  1532. node.name = ident.name;
  1533. node.variance = variance;
  1534. node.bound = ident.typeAnnotation;
  1535. if (this.match(types.eq)) {
  1536. this.eat(types.eq);
  1537. node.default = this.flowParseType();
  1538. } else {
  1539. if (requireDefault) {
  1540. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1541. }
  1542. }
  1543. return this.finishNode(node, "TypeParameter");
  1544. }
  1545. flowParseTypeParameterDeclaration() {
  1546. const oldInType = this.state.inType;
  1547. const node = this.startNode();
  1548. node.params = [];
  1549. this.state.inType = true;
  1550. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1551. this.next();
  1552. } else {
  1553. this.unexpected();
  1554. }
  1555. let defaultRequired = false;
  1556. do {
  1557. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1558. node.params.push(typeParameter);
  1559. if (typeParameter.default) {
  1560. defaultRequired = true;
  1561. }
  1562. if (!this.isRelational(">")) {
  1563. this.expect(types.comma);
  1564. }
  1565. } while (!this.isRelational(">"));
  1566. this.expectRelational(">");
  1567. this.state.inType = oldInType;
  1568. return this.finishNode(node, "TypeParameterDeclaration");
  1569. }
  1570. flowParseTypeParameterInstantiation() {
  1571. const node = this.startNode();
  1572. const oldInType = this.state.inType;
  1573. node.params = [];
  1574. this.state.inType = true;
  1575. this.expectRelational("<");
  1576. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1577. this.state.noAnonFunctionType = false;
  1578. while (!this.isRelational(">")) {
  1579. node.params.push(this.flowParseType());
  1580. if (!this.isRelational(">")) {
  1581. this.expect(types.comma);
  1582. }
  1583. }
  1584. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1585. this.expectRelational(">");
  1586. this.state.inType = oldInType;
  1587. return this.finishNode(node, "TypeParameterInstantiation");
  1588. }
  1589. flowParseTypeParameterInstantiationCallOrNew() {
  1590. const node = this.startNode();
  1591. const oldInType = this.state.inType;
  1592. node.params = [];
  1593. this.state.inType = true;
  1594. this.expectRelational("<");
  1595. while (!this.isRelational(">")) {
  1596. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1597. if (!this.isRelational(">")) {
  1598. this.expect(types.comma);
  1599. }
  1600. }
  1601. this.expectRelational(">");
  1602. this.state.inType = oldInType;
  1603. return this.finishNode(node, "TypeParameterInstantiation");
  1604. }
  1605. flowParseInterfaceType() {
  1606. const node = this.startNode();
  1607. this.expectContextual("interface");
  1608. node.extends = [];
  1609. if (this.eat(types._extends)) {
  1610. do {
  1611. node.extends.push(this.flowParseInterfaceExtends());
  1612. } while (this.eat(types.comma));
  1613. }
  1614. node.body = this.flowParseObjectType({
  1615. allowStatic: false,
  1616. allowExact: false,
  1617. allowSpread: false,
  1618. allowProto: false,
  1619. allowInexact: false
  1620. });
  1621. return this.finishNode(node, "InterfaceTypeAnnotation");
  1622. }
  1623. flowParseObjectPropertyKey() {
  1624. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1625. }
  1626. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1627. node.static = isStatic;
  1628. if (this.lookahead().type === types.colon) {
  1629. node.id = this.flowParseObjectPropertyKey();
  1630. node.key = this.flowParseTypeInitialiser();
  1631. } else {
  1632. node.id = null;
  1633. node.key = this.flowParseType();
  1634. }
  1635. this.expect(types.bracketR);
  1636. node.value = this.flowParseTypeInitialiser();
  1637. node.variance = variance;
  1638. return this.finishNode(node, "ObjectTypeIndexer");
  1639. }
  1640. flowParseObjectTypeInternalSlot(node, isStatic) {
  1641. node.static = isStatic;
  1642. node.id = this.flowParseObjectPropertyKey();
  1643. this.expect(types.bracketR);
  1644. this.expect(types.bracketR);
  1645. if (this.isRelational("<") || this.match(types.parenL)) {
  1646. node.method = true;
  1647. node.optional = false;
  1648. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1649. } else {
  1650. node.method = false;
  1651. if (this.eat(types.question)) {
  1652. node.optional = true;
  1653. }
  1654. node.value = this.flowParseTypeInitialiser();
  1655. }
  1656. return this.finishNode(node, "ObjectTypeInternalSlot");
  1657. }
  1658. flowParseObjectTypeMethodish(node) {
  1659. node.params = [];
  1660. node.rest = null;
  1661. node.typeParameters = null;
  1662. if (this.isRelational("<")) {
  1663. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1664. }
  1665. this.expect(types.parenL);
  1666. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1667. node.params.push(this.flowParseFunctionTypeParam());
  1668. if (!this.match(types.parenR)) {
  1669. this.expect(types.comma);
  1670. }
  1671. }
  1672. if (this.eat(types.ellipsis)) {
  1673. node.rest = this.flowParseFunctionTypeParam();
  1674. }
  1675. this.expect(types.parenR);
  1676. node.returnType = this.flowParseTypeInitialiser();
  1677. return this.finishNode(node, "FunctionTypeAnnotation");
  1678. }
  1679. flowParseObjectTypeCallProperty(node, isStatic) {
  1680. const valueNode = this.startNode();
  1681. node.static = isStatic;
  1682. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1683. return this.finishNode(node, "ObjectTypeCallProperty");
  1684. }
  1685. flowParseObjectType({
  1686. allowStatic,
  1687. allowExact,
  1688. allowSpread,
  1689. allowProto,
  1690. allowInexact
  1691. }) {
  1692. const oldInType = this.state.inType;
  1693. this.state.inType = true;
  1694. const nodeStart = this.startNode();
  1695. nodeStart.callProperties = [];
  1696. nodeStart.properties = [];
  1697. nodeStart.indexers = [];
  1698. nodeStart.internalSlots = [];
  1699. let endDelim;
  1700. let exact;
  1701. let inexact = false;
  1702. if (allowExact && this.match(types.braceBarL)) {
  1703. this.expect(types.braceBarL);
  1704. endDelim = types.braceBarR;
  1705. exact = true;
  1706. } else {
  1707. this.expect(types.braceL);
  1708. endDelim = types.braceR;
  1709. exact = false;
  1710. }
  1711. nodeStart.exact = exact;
  1712. while (!this.match(endDelim)) {
  1713. let isStatic = false;
  1714. let protoStart = null;
  1715. let inexactStart = null;
  1716. const node = this.startNode();
  1717. if (allowProto && this.isContextual("proto")) {
  1718. const lookahead = this.lookahead();
  1719. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1720. this.next();
  1721. protoStart = this.state.start;
  1722. allowStatic = false;
  1723. }
  1724. }
  1725. if (allowStatic && this.isContextual("static")) {
  1726. const lookahead = this.lookahead();
  1727. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1728. this.next();
  1729. isStatic = true;
  1730. }
  1731. }
  1732. const variance = this.flowParseVariance();
  1733. if (this.eat(types.bracketL)) {
  1734. if (protoStart != null) {
  1735. this.unexpected(protoStart);
  1736. }
  1737. if (this.eat(types.bracketL)) {
  1738. if (variance) {
  1739. this.unexpected(variance.start);
  1740. }
  1741. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1742. } else {
  1743. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1744. }
  1745. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1746. if (protoStart != null) {
  1747. this.unexpected(protoStart);
  1748. }
  1749. if (variance) {
  1750. this.unexpected(variance.start);
  1751. }
  1752. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1753. } else {
  1754. let kind = "init";
  1755. if (this.isContextual("get") || this.isContextual("set")) {
  1756. const lookahead = this.lookahead();
  1757. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1758. kind = this.state.value;
  1759. this.next();
  1760. }
  1761. }
  1762. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1763. if (propOrInexact === null) {
  1764. inexact = true;
  1765. inexactStart = this.state.lastTokStart;
  1766. } else {
  1767. nodeStart.properties.push(propOrInexact);
  1768. }
  1769. }
  1770. this.flowObjectTypeSemicolon();
  1771. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1772. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  1773. }
  1774. }
  1775. this.expect(endDelim);
  1776. if (allowSpread) {
  1777. nodeStart.inexact = inexact;
  1778. }
  1779. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1780. this.state.inType = oldInType;
  1781. return out;
  1782. }
  1783. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1784. if (this.eat(types.ellipsis)) {
  1785. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1786. if (isInexactToken) {
  1787. if (!allowSpread) {
  1788. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  1789. } else if (!allowInexact) {
  1790. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  1791. }
  1792. if (variance) {
  1793. this.raise(variance.start, FlowErrors.InexactVariance);
  1794. }
  1795. return null;
  1796. }
  1797. if (!allowSpread) {
  1798. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  1799. }
  1800. if (protoStart != null) {
  1801. this.unexpected(protoStart);
  1802. }
  1803. if (variance) {
  1804. this.raise(variance.start, FlowErrors.SpreadVariance);
  1805. }
  1806. node.argument = this.flowParseType();
  1807. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1808. } else {
  1809. node.key = this.flowParseObjectPropertyKey();
  1810. node.static = isStatic;
  1811. node.proto = protoStart != null;
  1812. node.kind = kind;
  1813. let optional = false;
  1814. if (this.isRelational("<") || this.match(types.parenL)) {
  1815. node.method = true;
  1816. if (protoStart != null) {
  1817. this.unexpected(protoStart);
  1818. }
  1819. if (variance) {
  1820. this.unexpected(variance.start);
  1821. }
  1822. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1823. if (kind === "get" || kind === "set") {
  1824. this.flowCheckGetterSetterParams(node);
  1825. }
  1826. } else {
  1827. if (kind !== "init") this.unexpected();
  1828. node.method = false;
  1829. if (this.eat(types.question)) {
  1830. optional = true;
  1831. }
  1832. node.value = this.flowParseTypeInitialiser();
  1833. node.variance = variance;
  1834. }
  1835. node.optional = optional;
  1836. return this.finishNode(node, "ObjectTypeProperty");
  1837. }
  1838. }
  1839. flowCheckGetterSetterParams(property) {
  1840. const paramCount = property.kind === "get" ? 0 : 1;
  1841. const start = property.start;
  1842. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1843. if (length !== paramCount) {
  1844. if (property.kind === "get") {
  1845. this.raise(start, ErrorMessages.BadGetterArity);
  1846. } else {
  1847. this.raise(start, ErrorMessages.BadSetterArity);
  1848. }
  1849. }
  1850. if (property.kind === "set" && property.value.rest) {
  1851. this.raise(start, ErrorMessages.BadSetterRestParameter);
  1852. }
  1853. }
  1854. flowObjectTypeSemicolon() {
  1855. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1856. this.unexpected();
  1857. }
  1858. }
  1859. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1860. startPos = startPos || this.state.start;
  1861. startLoc = startLoc || this.state.startLoc;
  1862. let node = id || this.flowParseRestrictedIdentifier(true);
  1863. while (this.eat(types.dot)) {
  1864. const node2 = this.startNodeAt(startPos, startLoc);
  1865. node2.qualification = node;
  1866. node2.id = this.flowParseRestrictedIdentifier(true);
  1867. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1868. }
  1869. return node;
  1870. }
  1871. flowParseGenericType(startPos, startLoc, id) {
  1872. const node = this.startNodeAt(startPos, startLoc);
  1873. node.typeParameters = null;
  1874. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1875. if (this.isRelational("<")) {
  1876. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1877. }
  1878. return this.finishNode(node, "GenericTypeAnnotation");
  1879. }
  1880. flowParseTypeofType() {
  1881. const node = this.startNode();
  1882. this.expect(types._typeof);
  1883. node.argument = this.flowParsePrimaryType();
  1884. return this.finishNode(node, "TypeofTypeAnnotation");
  1885. }
  1886. flowParseTupleType() {
  1887. const node = this.startNode();
  1888. node.types = [];
  1889. this.expect(types.bracketL);
  1890. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1891. node.types.push(this.flowParseType());
  1892. if (this.match(types.bracketR)) break;
  1893. this.expect(types.comma);
  1894. }
  1895. this.expect(types.bracketR);
  1896. return this.finishNode(node, "TupleTypeAnnotation");
  1897. }
  1898. flowParseFunctionTypeParam() {
  1899. let name = null;
  1900. let optional = false;
  1901. let typeAnnotation = null;
  1902. const node = this.startNode();
  1903. const lh = this.lookahead();
  1904. if (lh.type === types.colon || lh.type === types.question) {
  1905. name = this.parseIdentifier();
  1906. if (this.eat(types.question)) {
  1907. optional = true;
  1908. }
  1909. typeAnnotation = this.flowParseTypeInitialiser();
  1910. } else {
  1911. typeAnnotation = this.flowParseType();
  1912. }
  1913. node.name = name;
  1914. node.optional = optional;
  1915. node.typeAnnotation = typeAnnotation;
  1916. return this.finishNode(node, "FunctionTypeParam");
  1917. }
  1918. reinterpretTypeAsFunctionTypeParam(type) {
  1919. const node = this.startNodeAt(type.start, type.loc.start);
  1920. node.name = null;
  1921. node.optional = false;
  1922. node.typeAnnotation = type;
  1923. return this.finishNode(node, "FunctionTypeParam");
  1924. }
  1925. flowParseFunctionTypeParams(params = []) {
  1926. let rest = null;
  1927. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1928. params.push(this.flowParseFunctionTypeParam());
  1929. if (!this.match(types.parenR)) {
  1930. this.expect(types.comma);
  1931. }
  1932. }
  1933. if (this.eat(types.ellipsis)) {
  1934. rest = this.flowParseFunctionTypeParam();
  1935. }
  1936. return {
  1937. params,
  1938. rest
  1939. };
  1940. }
  1941. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1942. switch (id.name) {
  1943. case "any":
  1944. return this.finishNode(node, "AnyTypeAnnotation");
  1945. case "bool":
  1946. case "boolean":
  1947. return this.finishNode(node, "BooleanTypeAnnotation");
  1948. case "mixed":
  1949. return this.finishNode(node, "MixedTypeAnnotation");
  1950. case "empty":
  1951. return this.finishNode(node, "EmptyTypeAnnotation");
  1952. case "number":
  1953. return this.finishNode(node, "NumberTypeAnnotation");
  1954. case "string":
  1955. return this.finishNode(node, "StringTypeAnnotation");
  1956. case "symbol":
  1957. return this.finishNode(node, "SymbolTypeAnnotation");
  1958. default:
  1959. this.checkNotUnderscore(id.name);
  1960. return this.flowParseGenericType(startPos, startLoc, id);
  1961. }
  1962. }
  1963. flowParsePrimaryType() {
  1964. const startPos = this.state.start;
  1965. const startLoc = this.state.startLoc;
  1966. const node = this.startNode();
  1967. let tmp;
  1968. let type;
  1969. let isGroupedType = false;
  1970. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1971. switch (this.state.type) {
  1972. case types.name:
  1973. if (this.isContextual("interface")) {
  1974. return this.flowParseInterfaceType();
  1975. }
  1976. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1977. case types.braceL:
  1978. return this.flowParseObjectType({
  1979. allowStatic: false,
  1980. allowExact: false,
  1981. allowSpread: true,
  1982. allowProto: false,
  1983. allowInexact: true
  1984. });
  1985. case types.braceBarL:
  1986. return this.flowParseObjectType({
  1987. allowStatic: false,
  1988. allowExact: true,
  1989. allowSpread: true,
  1990. allowProto: false,
  1991. allowInexact: false
  1992. });
  1993. case types.bracketL:
  1994. this.state.noAnonFunctionType = false;
  1995. type = this.flowParseTupleType();
  1996. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1997. return type;
  1998. case types.relational:
  1999. if (this.state.value === "<") {
  2000. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2001. this.expect(types.parenL);
  2002. tmp = this.flowParseFunctionTypeParams();
  2003. node.params = tmp.params;
  2004. node.rest = tmp.rest;
  2005. this.expect(types.parenR);
  2006. this.expect(types.arrow);
  2007. node.returnType = this.flowParseType();
  2008. return this.finishNode(node, "FunctionTypeAnnotation");
  2009. }
  2010. break;
  2011. case types.parenL:
  2012. this.next();
  2013. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  2014. if (this.match(types.name)) {
  2015. const token = this.lookahead().type;
  2016. isGroupedType = token !== types.question && token !== types.colon;
  2017. } else {
  2018. isGroupedType = true;
  2019. }
  2020. }
  2021. if (isGroupedType) {
  2022. this.state.noAnonFunctionType = false;
  2023. type = this.flowParseType();
  2024. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2025. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  2026. this.expect(types.parenR);
  2027. return type;
  2028. } else {
  2029. this.eat(types.comma);
  2030. }
  2031. }
  2032. if (type) {
  2033. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  2034. } else {
  2035. tmp = this.flowParseFunctionTypeParams();
  2036. }
  2037. node.params = tmp.params;
  2038. node.rest = tmp.rest;
  2039. this.expect(types.parenR);
  2040. this.expect(types.arrow);
  2041. node.returnType = this.flowParseType();
  2042. node.typeParameters = null;
  2043. return this.finishNode(node, "FunctionTypeAnnotation");
  2044. case types.string:
  2045. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  2046. case types._true:
  2047. case types._false:
  2048. node.value = this.match(types._true);
  2049. this.next();
  2050. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  2051. case types.plusMin:
  2052. if (this.state.value === "-") {
  2053. this.next();
  2054. if (this.match(types.num)) {
  2055. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  2056. }
  2057. if (this.match(types.bigint)) {
  2058. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  2059. }
  2060. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  2061. }
  2062. throw this.unexpected();
  2063. case types.num:
  2064. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  2065. case types.bigint:
  2066. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  2067. case types._void:
  2068. this.next();
  2069. return this.finishNode(node, "VoidTypeAnnotation");
  2070. case types._null:
  2071. this.next();
  2072. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2073. case types._this:
  2074. this.next();
  2075. return this.finishNode(node, "ThisTypeAnnotation");
  2076. case types.star:
  2077. this.next();
  2078. return this.finishNode(node, "ExistsTypeAnnotation");
  2079. default:
  2080. if (this.state.type.keyword === "typeof") {
  2081. return this.flowParseTypeofType();
  2082. } else if (this.state.type.keyword) {
  2083. const label = this.state.type.label;
  2084. this.next();
  2085. return super.createIdentifier(node, label);
  2086. }
  2087. }
  2088. throw this.unexpected();
  2089. }
  2090. flowParsePostfixType() {
  2091. const startPos = this.state.start,
  2092. startLoc = this.state.startLoc;
  2093. let type = this.flowParsePrimaryType();
  2094. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2095. const node = this.startNodeAt(startPos, startLoc);
  2096. node.elementType = type;
  2097. this.expect(types.bracketL);
  2098. this.expect(types.bracketR);
  2099. type = this.finishNode(node, "ArrayTypeAnnotation");
  2100. }
  2101. return type;
  2102. }
  2103. flowParsePrefixType() {
  2104. const node = this.startNode();
  2105. if (this.eat(types.question)) {
  2106. node.typeAnnotation = this.flowParsePrefixType();
  2107. return this.finishNode(node, "NullableTypeAnnotation");
  2108. } else {
  2109. return this.flowParsePostfixType();
  2110. }
  2111. }
  2112. flowParseAnonFunctionWithoutParens() {
  2113. const param = this.flowParsePrefixType();
  2114. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2115. const node = this.startNodeAt(param.start, param.loc.start);
  2116. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2117. node.rest = null;
  2118. node.returnType = this.flowParseType();
  2119. node.typeParameters = null;
  2120. return this.finishNode(node, "FunctionTypeAnnotation");
  2121. }
  2122. return param;
  2123. }
  2124. flowParseIntersectionType() {
  2125. const node = this.startNode();
  2126. this.eat(types.bitwiseAND);
  2127. const type = this.flowParseAnonFunctionWithoutParens();
  2128. node.types = [type];
  2129. while (this.eat(types.bitwiseAND)) {
  2130. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2131. }
  2132. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2133. }
  2134. flowParseUnionType() {
  2135. const node = this.startNode();
  2136. this.eat(types.bitwiseOR);
  2137. const type = this.flowParseIntersectionType();
  2138. node.types = [type];
  2139. while (this.eat(types.bitwiseOR)) {
  2140. node.types.push(this.flowParseIntersectionType());
  2141. }
  2142. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2143. }
  2144. flowParseType() {
  2145. const oldInType = this.state.inType;
  2146. this.state.inType = true;
  2147. const type = this.flowParseUnionType();
  2148. this.state.inType = oldInType;
  2149. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2150. return type;
  2151. }
  2152. flowParseTypeOrImplicitInstantiation() {
  2153. if (this.state.type === types.name && this.state.value === "_") {
  2154. const startPos = this.state.start;
  2155. const startLoc = this.state.startLoc;
  2156. const node = this.parseIdentifier();
  2157. return this.flowParseGenericType(startPos, startLoc, node);
  2158. } else {
  2159. return this.flowParseType();
  2160. }
  2161. }
  2162. flowParseTypeAnnotation() {
  2163. const node = this.startNode();
  2164. node.typeAnnotation = this.flowParseTypeInitialiser();
  2165. return this.finishNode(node, "TypeAnnotation");
  2166. }
  2167. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2168. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2169. if (this.match(types.colon)) {
  2170. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2171. this.resetEndLocation(ident);
  2172. }
  2173. return ident;
  2174. }
  2175. typeCastToParameter(node) {
  2176. node.expression.typeAnnotation = node.typeAnnotation;
  2177. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2178. return node.expression;
  2179. }
  2180. flowParseVariance() {
  2181. let variance = null;
  2182. if (this.match(types.plusMin)) {
  2183. variance = this.startNode();
  2184. if (this.state.value === "+") {
  2185. variance.kind = "plus";
  2186. } else {
  2187. variance.kind = "minus";
  2188. }
  2189. this.next();
  2190. this.finishNode(variance, "Variance");
  2191. }
  2192. return variance;
  2193. }
  2194. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2195. if (allowExpressionBody) {
  2196. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2197. }
  2198. return super.parseFunctionBody(node, false, isMethod);
  2199. }
  2200. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2201. if (this.match(types.colon)) {
  2202. const typeNode = this.startNode();
  2203. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2204. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2205. }
  2206. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2207. }
  2208. parseStatement(context, topLevel) {
  2209. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2210. const node = this.startNode();
  2211. this.next();
  2212. return this.flowParseInterface(node);
  2213. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2214. const node = this.startNode();
  2215. this.next();
  2216. return this.flowParseEnumDeclaration(node);
  2217. } else {
  2218. const stmt = super.parseStatement(context, topLevel);
  2219. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2220. this.flowPragma = null;
  2221. }
  2222. return stmt;
  2223. }
  2224. }
  2225. parseExpressionStatement(node, expr) {
  2226. if (expr.type === "Identifier") {
  2227. if (expr.name === "declare") {
  2228. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2229. return this.flowParseDeclare(node);
  2230. }
  2231. } else if (this.match(types.name)) {
  2232. if (expr.name === "interface") {
  2233. return this.flowParseInterface(node);
  2234. } else if (expr.name === "type") {
  2235. return this.flowParseTypeAlias(node);
  2236. } else if (expr.name === "opaque") {
  2237. return this.flowParseOpaqueType(node, false);
  2238. }
  2239. }
  2240. }
  2241. return super.parseExpressionStatement(node, expr);
  2242. }
  2243. shouldParseExportDeclaration() {
  2244. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2245. }
  2246. isExportDefaultSpecifier() {
  2247. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2248. return false;
  2249. }
  2250. return super.isExportDefaultSpecifier();
  2251. }
  2252. parseExportDefaultExpression() {
  2253. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2254. const node = this.startNode();
  2255. this.next();
  2256. return this.flowParseEnumDeclaration(node);
  2257. }
  2258. return super.parseExportDefaultExpression();
  2259. }
  2260. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  2261. if (!this.match(types.question)) return expr;
  2262. if (refNeedsArrowPos) {
  2263. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  2264. if (!result.node) {
  2265. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2266. return expr;
  2267. }
  2268. if (result.error) this.state = result.failState;
  2269. return result.node;
  2270. }
  2271. this.expect(types.question);
  2272. const state = this.state.clone();
  2273. const originalNoArrowAt = this.state.noArrowAt;
  2274. const node = this.startNodeAt(startPos, startLoc);
  2275. let {
  2276. consequent,
  2277. failed
  2278. } = this.tryParseConditionalConsequent();
  2279. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2280. if (failed || invalid.length > 0) {
  2281. const noArrowAt = [...originalNoArrowAt];
  2282. if (invalid.length > 0) {
  2283. this.state = state;
  2284. this.state.noArrowAt = noArrowAt;
  2285. for (let i = 0; i < invalid.length; i++) {
  2286. noArrowAt.push(invalid[i].start);
  2287. }
  2288. ({
  2289. consequent,
  2290. failed
  2291. } = this.tryParseConditionalConsequent());
  2292. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2293. }
  2294. if (failed && valid.length > 1) {
  2295. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2296. }
  2297. if (failed && valid.length === 1) {
  2298. this.state = state;
  2299. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2300. ({
  2301. consequent,
  2302. failed
  2303. } = this.tryParseConditionalConsequent());
  2304. }
  2305. }
  2306. this.getArrowLikeExpressions(consequent, true);
  2307. this.state.noArrowAt = originalNoArrowAt;
  2308. this.expect(types.colon);
  2309. node.test = expr;
  2310. node.consequent = consequent;
  2311. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  2312. return this.finishNode(node, "ConditionalExpression");
  2313. }
  2314. tryParseConditionalConsequent() {
  2315. this.state.noArrowParamsConversionAt.push(this.state.start);
  2316. const consequent = this.parseMaybeAssignAllowIn();
  2317. const failed = !this.match(types.colon);
  2318. this.state.noArrowParamsConversionAt.pop();
  2319. return {
  2320. consequent,
  2321. failed
  2322. };
  2323. }
  2324. getArrowLikeExpressions(node, disallowInvalid) {
  2325. const stack = [node];
  2326. const arrows = [];
  2327. while (stack.length !== 0) {
  2328. const node = stack.pop();
  2329. if (node.type === "ArrowFunctionExpression") {
  2330. if (node.typeParameters || !node.returnType) {
  2331. this.finishArrowValidation(node);
  2332. } else {
  2333. arrows.push(node);
  2334. }
  2335. stack.push(node.body);
  2336. } else if (node.type === "ConditionalExpression") {
  2337. stack.push(node.consequent);
  2338. stack.push(node.alternate);
  2339. }
  2340. }
  2341. if (disallowInvalid) {
  2342. arrows.forEach(node => this.finishArrowValidation(node));
  2343. return [arrows, []];
  2344. }
  2345. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2346. }
  2347. finishArrowValidation(node) {
  2348. var _node$extra;
  2349. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma);
  2350. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2351. super.checkParams(node, false, true);
  2352. this.scope.exit();
  2353. }
  2354. forwardNoArrowParamsConversionAt(node, parse) {
  2355. let result;
  2356. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2357. this.state.noArrowParamsConversionAt.push(this.state.start);
  2358. result = parse();
  2359. this.state.noArrowParamsConversionAt.pop();
  2360. } else {
  2361. result = parse();
  2362. }
  2363. return result;
  2364. }
  2365. parseParenItem(node, startPos, startLoc) {
  2366. node = super.parseParenItem(node, startPos, startLoc);
  2367. if (this.eat(types.question)) {
  2368. node.optional = true;
  2369. this.resetEndLocation(node);
  2370. }
  2371. if (this.match(types.colon)) {
  2372. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2373. typeCastNode.expression = node;
  2374. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2375. return this.finishNode(typeCastNode, "TypeCastExpression");
  2376. }
  2377. return node;
  2378. }
  2379. assertModuleNodeAllowed(node) {
  2380. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2381. return;
  2382. }
  2383. super.assertModuleNodeAllowed(node);
  2384. }
  2385. parseExport(node) {
  2386. const decl = super.parseExport(node);
  2387. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2388. decl.exportKind = decl.exportKind || "value";
  2389. }
  2390. return decl;
  2391. }
  2392. parseExportDeclaration(node) {
  2393. if (this.isContextual("type")) {
  2394. node.exportKind = "type";
  2395. const declarationNode = this.startNode();
  2396. this.next();
  2397. if (this.match(types.braceL)) {
  2398. node.specifiers = this.parseExportSpecifiers();
  2399. this.parseExportFrom(node);
  2400. return null;
  2401. } else {
  2402. return this.flowParseTypeAlias(declarationNode);
  2403. }
  2404. } else if (this.isContextual("opaque")) {
  2405. node.exportKind = "type";
  2406. const declarationNode = this.startNode();
  2407. this.next();
  2408. return this.flowParseOpaqueType(declarationNode, false);
  2409. } else if (this.isContextual("interface")) {
  2410. node.exportKind = "type";
  2411. const declarationNode = this.startNode();
  2412. this.next();
  2413. return this.flowParseInterface(declarationNode);
  2414. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2415. node.exportKind = "value";
  2416. const declarationNode = this.startNode();
  2417. this.next();
  2418. return this.flowParseEnumDeclaration(declarationNode);
  2419. } else {
  2420. return super.parseExportDeclaration(node);
  2421. }
  2422. }
  2423. eatExportStar(node) {
  2424. if (super.eatExportStar(...arguments)) return true;
  2425. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2426. node.exportKind = "type";
  2427. this.next();
  2428. this.next();
  2429. return true;
  2430. }
  2431. return false;
  2432. }
  2433. maybeParseExportNamespaceSpecifier(node) {
  2434. const pos = this.state.start;
  2435. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2436. if (hasNamespace && node.exportKind === "type") {
  2437. this.unexpected(pos);
  2438. }
  2439. return hasNamespace;
  2440. }
  2441. parseClassId(node, isStatement, optionalId) {
  2442. super.parseClassId(node, isStatement, optionalId);
  2443. if (this.isRelational("<")) {
  2444. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2445. }
  2446. }
  2447. parseClassMember(classBody, member, state) {
  2448. const pos = this.state.start;
  2449. if (this.isContextual("declare")) {
  2450. if (this.parseClassMemberFromModifier(classBody, member)) {
  2451. return;
  2452. }
  2453. member.declare = true;
  2454. }
  2455. super.parseClassMember(classBody, member, state);
  2456. if (member.declare) {
  2457. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  2458. this.raise(pos, FlowErrors.DeclareClassElement);
  2459. } else if (member.value) {
  2460. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2461. }
  2462. }
  2463. }
  2464. getTokenFromCode(code) {
  2465. const next = this.input.charCodeAt(this.state.pos + 1);
  2466. if (code === 123 && next === 124) {
  2467. return this.finishOp(types.braceBarL, 2);
  2468. } else if (this.state.inType && (code === 62 || code === 60)) {
  2469. return this.finishOp(types.relational, 1);
  2470. } else if (this.state.inType && code === 63) {
  2471. return this.finishOp(types.question, 1);
  2472. } else if (isIteratorStart(code, next)) {
  2473. this.state.isIterator = true;
  2474. return super.readWord();
  2475. } else {
  2476. return super.getTokenFromCode(code);
  2477. }
  2478. }
  2479. isAssignable(node, isBinding) {
  2480. switch (node.type) {
  2481. case "Identifier":
  2482. case "ObjectPattern":
  2483. case "ArrayPattern":
  2484. case "AssignmentPattern":
  2485. return true;
  2486. case "ObjectExpression":
  2487. {
  2488. const last = node.properties.length - 1;
  2489. return node.properties.every((prop, i) => {
  2490. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2491. });
  2492. }
  2493. case "ObjectProperty":
  2494. return this.isAssignable(node.value);
  2495. case "SpreadElement":
  2496. return this.isAssignable(node.argument);
  2497. case "ArrayExpression":
  2498. return node.elements.every(element => this.isAssignable(element));
  2499. case "AssignmentExpression":
  2500. return node.operator === "=";
  2501. case "ParenthesizedExpression":
  2502. case "TypeCastExpression":
  2503. return this.isAssignable(node.expression);
  2504. case "MemberExpression":
  2505. case "OptionalMemberExpression":
  2506. return !isBinding;
  2507. default:
  2508. return false;
  2509. }
  2510. }
  2511. toAssignable(node) {
  2512. if (node.type === "TypeCastExpression") {
  2513. return super.toAssignable(this.typeCastToParameter(node));
  2514. } else {
  2515. return super.toAssignable(node);
  2516. }
  2517. }
  2518. toAssignableList(exprList, trailingCommaPos) {
  2519. for (let i = 0; i < exprList.length; i++) {
  2520. const expr = exprList[i];
  2521. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  2522. exprList[i] = this.typeCastToParameter(expr);
  2523. }
  2524. }
  2525. return super.toAssignableList(exprList, trailingCommaPos);
  2526. }
  2527. toReferencedList(exprList, isParenthesizedExpr) {
  2528. for (let i = 0; i < exprList.length; i++) {
  2529. var _expr$extra;
  2530. const expr = exprList[i];
  2531. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) == null ? void 0 : _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2532. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2533. }
  2534. }
  2535. return exprList;
  2536. }
  2537. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  2538. if (expr.type !== "TypeCastExpression") {
  2539. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  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, BIND_LEXICAL, undefined, contextDescription);
  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.parseIdentifier(true);
  2679. let specifierTypeKind = null;
  2680. if (firstIdent.name === "type") {
  2681. specifierTypeKind = "type";
  2682. } else if (firstIdent.name === "typeof") {
  2683. specifierTypeKind = "typeof";
  2684. }
  2685. let isBinding = false;
  2686. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2687. const as_ident = this.parseIdentifier(true);
  2688. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2689. specifier.imported = as_ident;
  2690. specifier.importKind = specifierTypeKind;
  2691. specifier.local = as_ident.__clone();
  2692. } else {
  2693. specifier.imported = firstIdent;
  2694. specifier.importKind = null;
  2695. specifier.local = this.parseIdentifier();
  2696. }
  2697. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2698. specifier.imported = this.parseIdentifier(true);
  2699. specifier.importKind = specifierTypeKind;
  2700. if (this.eatContextual("as")) {
  2701. specifier.local = this.parseIdentifier();
  2702. } else {
  2703. isBinding = true;
  2704. specifier.local = specifier.imported.__clone();
  2705. }
  2706. } else {
  2707. isBinding = true;
  2708. specifier.imported = firstIdent;
  2709. specifier.importKind = null;
  2710. specifier.local = specifier.imported.__clone();
  2711. }
  2712. const nodeIsTypeImport = hasTypeImportKind(node);
  2713. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2714. if (nodeIsTypeImport && specifierIsTypeImport) {
  2715. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  2716. }
  2717. if (nodeIsTypeImport || specifierIsTypeImport) {
  2718. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2719. }
  2720. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2721. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2722. }
  2723. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2724. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2725. }
  2726. parseFunctionParams(node, allowModifiers) {
  2727. const kind = node.kind;
  2728. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2729. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2730. }
  2731. super.parseFunctionParams(node, allowModifiers);
  2732. }
  2733. parseVarId(decl, kind) {
  2734. super.parseVarId(decl, kind);
  2735. if (this.match(types.colon)) {
  2736. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2737. this.resetEndLocation(decl.id);
  2738. }
  2739. }
  2740. parseAsyncArrowFromCallExpression(node, call) {
  2741. if (this.match(types.colon)) {
  2742. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2743. this.state.noAnonFunctionType = true;
  2744. node.returnType = this.flowParseTypeAnnotation();
  2745. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2746. }
  2747. return super.parseAsyncArrowFromCallExpression(node, call);
  2748. }
  2749. shouldParseAsyncArrow() {
  2750. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2751. }
  2752. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  2753. var _jsx;
  2754. let state = null;
  2755. let jsx;
  2756. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2757. state = this.state.clone();
  2758. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  2759. if (!jsx.error) return jsx.node;
  2760. const {
  2761. context
  2762. } = this.state;
  2763. if (context[context.length - 1] === types$1.j_oTag) {
  2764. context.length -= 2;
  2765. } else if (context[context.length - 1] === types$1.j_expr) {
  2766. context.length -= 1;
  2767. }
  2768. }
  2769. if (((_jsx = jsx) == null ? void 0 : _jsx.error) || this.isRelational("<")) {
  2770. var _jsx2, _jsx3;
  2771. state = state || this.state.clone();
  2772. let typeParameters;
  2773. const arrow = this.tryParse(abort => {
  2774. var _arrowExpression$extr;
  2775. typeParameters = this.flowParseTypeParameterDeclaration();
  2776. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  2777. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2778. this.resetStartLocationFromNode(result, typeParameters);
  2779. return result;
  2780. });
  2781. if (arrowExpression.type !== "ArrowFunctionExpression" && ((_arrowExpression$extr = arrowExpression.extra) == null ? void 0 : _arrowExpression$extr.parenthesized)) {
  2782. abort();
  2783. }
  2784. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  2785. expr.typeParameters = typeParameters;
  2786. this.resetStartLocationFromNode(expr, typeParameters);
  2787. return arrowExpression;
  2788. }, state);
  2789. let arrowExpression = null;
  2790. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  2791. if (!arrow.error && !arrow.aborted) {
  2792. if (arrow.node.async) {
  2793. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  2794. }
  2795. return arrow.node;
  2796. }
  2797. arrowExpression = arrow.node;
  2798. }
  2799. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  2800. this.state = jsx.failState;
  2801. return jsx.node;
  2802. }
  2803. if (arrowExpression) {
  2804. this.state = arrow.failState;
  2805. return arrowExpression;
  2806. }
  2807. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  2808. if (arrow.thrown) throw arrow.error;
  2809. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  2810. }
  2811. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2812. }
  2813. parseArrow(node) {
  2814. if (this.match(types.colon)) {
  2815. const result = this.tryParse(() => {
  2816. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2817. this.state.noAnonFunctionType = true;
  2818. const typeNode = this.startNode();
  2819. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2820. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2821. if (this.canInsertSemicolon()) this.unexpected();
  2822. if (!this.match(types.arrow)) this.unexpected();
  2823. return typeNode;
  2824. });
  2825. if (result.thrown) return null;
  2826. if (result.error) this.state = result.failState;
  2827. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2828. }
  2829. return super.parseArrow(node);
  2830. }
  2831. shouldParseArrow() {
  2832. return this.match(types.colon) || super.shouldParseArrow();
  2833. }
  2834. setArrowFunctionParameters(node, params) {
  2835. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2836. node.params = params;
  2837. } else {
  2838. super.setArrowFunctionParameters(node, params);
  2839. }
  2840. }
  2841. checkParams(node, allowDuplicates, isArrowFunction) {
  2842. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2843. return;
  2844. }
  2845. return super.checkParams(...arguments);
  2846. }
  2847. parseParenAndDistinguishExpression(canBeArrow) {
  2848. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2849. }
  2850. parseSubscripts(base, startPos, startLoc, noCalls) {
  2851. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2852. this.next();
  2853. const node = this.startNodeAt(startPos, startLoc);
  2854. node.callee = base;
  2855. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2856. base = this.finishNode(node, "CallExpression");
  2857. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2858. const state = this.state.clone();
  2859. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2860. if (!arrow.error && !arrow.aborted) return arrow.node;
  2861. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2862. if (result.node && !result.error) return result.node;
  2863. if (arrow.node) {
  2864. this.state = arrow.failState;
  2865. return arrow.node;
  2866. }
  2867. if (result.node) {
  2868. this.state = result.failState;
  2869. return result.node;
  2870. }
  2871. throw arrow.error || result.error;
  2872. }
  2873. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2874. }
  2875. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2876. if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
  2877. subscriptState.optionalChainMember = true;
  2878. if (noCalls) {
  2879. subscriptState.stop = true;
  2880. return base;
  2881. }
  2882. this.next();
  2883. const node = this.startNodeAt(startPos, startLoc);
  2884. node.callee = base;
  2885. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2886. this.expect(types.parenL);
  2887. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2888. node.optional = true;
  2889. return this.finishCallExpression(node, true);
  2890. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2891. const node = this.startNodeAt(startPos, startLoc);
  2892. node.callee = base;
  2893. const result = this.tryParse(() => {
  2894. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2895. this.expect(types.parenL);
  2896. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2897. if (subscriptState.optionalChainMember) node.optional = false;
  2898. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2899. });
  2900. if (result.node) {
  2901. if (result.error) this.state = result.failState;
  2902. return result.node;
  2903. }
  2904. }
  2905. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2906. }
  2907. parseNewArguments(node) {
  2908. let targs = null;
  2909. if (this.shouldParseTypes() && this.isRelational("<")) {
  2910. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2911. }
  2912. node.typeArguments = targs;
  2913. super.parseNewArguments(node);
  2914. }
  2915. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2916. const node = this.startNodeAt(startPos, startLoc);
  2917. this.parseFunctionParams(node);
  2918. if (!this.parseArrow(node)) return;
  2919. return this.parseArrowExpression(node, undefined, true);
  2920. }
  2921. readToken_mult_modulo(code) {
  2922. const next = this.input.charCodeAt(this.state.pos + 1);
  2923. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2924. this.state.hasFlowComment = false;
  2925. this.state.pos += 2;
  2926. this.nextToken();
  2927. return;
  2928. }
  2929. super.readToken_mult_modulo(code);
  2930. }
  2931. readToken_pipe_amp(code) {
  2932. const next = this.input.charCodeAt(this.state.pos + 1);
  2933. if (code === 124 && next === 125) {
  2934. this.finishOp(types.braceBarR, 2);
  2935. return;
  2936. }
  2937. super.readToken_pipe_amp(code);
  2938. }
  2939. parseTopLevel(file, program) {
  2940. const fileNode = super.parseTopLevel(file, program);
  2941. if (this.state.hasFlowComment) {
  2942. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  2943. }
  2944. return fileNode;
  2945. }
  2946. skipBlockComment() {
  2947. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2948. if (this.state.hasFlowComment) {
  2949. this.unexpected(null, FlowErrors.NestedFlowComment);
  2950. }
  2951. this.hasFlowCommentCompletion();
  2952. this.state.pos += this.skipFlowComment();
  2953. this.state.hasFlowComment = true;
  2954. return;
  2955. }
  2956. if (this.state.hasFlowComment) {
  2957. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2958. if (end === -1) {
  2959. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  2960. }
  2961. this.state.pos = end + 3;
  2962. return;
  2963. }
  2964. super.skipBlockComment();
  2965. }
  2966. skipFlowComment() {
  2967. const {
  2968. pos
  2969. } = this.state;
  2970. let shiftToFirstNonWhiteSpace = 2;
  2971. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2972. shiftToFirstNonWhiteSpace++;
  2973. }
  2974. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2975. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2976. if (ch2 === 58 && ch3 === 58) {
  2977. return shiftToFirstNonWhiteSpace + 2;
  2978. }
  2979. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2980. return shiftToFirstNonWhiteSpace + 12;
  2981. }
  2982. if (ch2 === 58 && ch3 !== 58) {
  2983. return shiftToFirstNonWhiteSpace;
  2984. }
  2985. return false;
  2986. }
  2987. hasFlowCommentCompletion() {
  2988. const end = this.input.indexOf("*/", this.state.pos);
  2989. if (end === -1) {
  2990. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  2991. }
  2992. }
  2993. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2994. enumName,
  2995. memberName
  2996. }) {
  2997. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  2998. }
  2999. flowEnumErrorInvalidMemberName(pos, {
  3000. enumName,
  3001. memberName
  3002. }) {
  3003. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  3004. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  3005. }
  3006. flowEnumErrorDuplicateMemberName(pos, {
  3007. enumName,
  3008. memberName
  3009. }) {
  3010. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  3011. }
  3012. flowEnumErrorInconsistentMemberValues(pos, {
  3013. enumName
  3014. }) {
  3015. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  3016. }
  3017. flowEnumErrorInvalidExplicitType(pos, {
  3018. enumName,
  3019. suppliedType
  3020. }) {
  3021. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  3022. }
  3023. flowEnumErrorInvalidMemberInitializer(pos, {
  3024. enumName,
  3025. explicitType,
  3026. memberName
  3027. }) {
  3028. let message = null;
  3029. switch (explicitType) {
  3030. case "boolean":
  3031. case "number":
  3032. case "string":
  3033. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  3034. break;
  3035. case "symbol":
  3036. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  3037. break;
  3038. default:
  3039. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  3040. }
  3041. return this.raise(pos, message, enumName, memberName, explicitType);
  3042. }
  3043. flowEnumErrorNumberMemberNotInitialized(pos, {
  3044. enumName,
  3045. memberName
  3046. }) {
  3047. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  3048. }
  3049. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  3050. enumName
  3051. }) {
  3052. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  3053. }
  3054. flowEnumMemberInit() {
  3055. const startPos = this.state.start;
  3056. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  3057. switch (this.state.type) {
  3058. case types.num:
  3059. {
  3060. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  3061. if (endOfInit()) {
  3062. return {
  3063. type: "number",
  3064. pos: literal.start,
  3065. value: literal
  3066. };
  3067. }
  3068. return {
  3069. type: "invalid",
  3070. pos: startPos
  3071. };
  3072. }
  3073. case types.string:
  3074. {
  3075. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  3076. if (endOfInit()) {
  3077. return {
  3078. type: "string",
  3079. pos: literal.start,
  3080. value: literal
  3081. };
  3082. }
  3083. return {
  3084. type: "invalid",
  3085. pos: startPos
  3086. };
  3087. }
  3088. case types._true:
  3089. case types._false:
  3090. {
  3091. const literal = this.parseBooleanLiteral();
  3092. if (endOfInit()) {
  3093. return {
  3094. type: "boolean",
  3095. pos: literal.start,
  3096. value: literal
  3097. };
  3098. }
  3099. return {
  3100. type: "invalid",
  3101. pos: startPos
  3102. };
  3103. }
  3104. default:
  3105. return {
  3106. type: "invalid",
  3107. pos: startPos
  3108. };
  3109. }
  3110. }
  3111. flowEnumMemberRaw() {
  3112. const pos = this.state.start;
  3113. const id = this.parseIdentifier(true);
  3114. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3115. type: "none",
  3116. pos
  3117. };
  3118. return {
  3119. id,
  3120. init
  3121. };
  3122. }
  3123. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3124. const {
  3125. explicitType
  3126. } = context;
  3127. if (explicitType === null) {
  3128. return;
  3129. }
  3130. if (explicitType !== expectedType) {
  3131. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3132. }
  3133. }
  3134. flowEnumMembers({
  3135. enumName,
  3136. explicitType
  3137. }) {
  3138. const seenNames = new Set();
  3139. const members = {
  3140. booleanMembers: [],
  3141. numberMembers: [],
  3142. stringMembers: [],
  3143. defaultedMembers: []
  3144. };
  3145. while (!this.match(types.braceR)) {
  3146. const memberNode = this.startNode();
  3147. const {
  3148. id,
  3149. init
  3150. } = this.flowEnumMemberRaw();
  3151. const memberName = id.name;
  3152. if (memberName === "") {
  3153. continue;
  3154. }
  3155. if (/^[a-z]/.test(memberName)) {
  3156. this.flowEnumErrorInvalidMemberName(id.start, {
  3157. enumName,
  3158. memberName
  3159. });
  3160. }
  3161. if (seenNames.has(memberName)) {
  3162. this.flowEnumErrorDuplicateMemberName(id.start, {
  3163. enumName,
  3164. memberName
  3165. });
  3166. }
  3167. seenNames.add(memberName);
  3168. const context = {
  3169. enumName,
  3170. explicitType,
  3171. memberName
  3172. };
  3173. memberNode.id = id;
  3174. switch (init.type) {
  3175. case "boolean":
  3176. {
  3177. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3178. memberNode.init = init.value;
  3179. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3180. break;
  3181. }
  3182. case "number":
  3183. {
  3184. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3185. memberNode.init = init.value;
  3186. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3187. break;
  3188. }
  3189. case "string":
  3190. {
  3191. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3192. memberNode.init = init.value;
  3193. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3194. break;
  3195. }
  3196. case "invalid":
  3197. {
  3198. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3199. }
  3200. case "none":
  3201. {
  3202. switch (explicitType) {
  3203. case "boolean":
  3204. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3205. break;
  3206. case "number":
  3207. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3208. break;
  3209. default:
  3210. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3211. }
  3212. }
  3213. }
  3214. if (!this.match(types.braceR)) {
  3215. this.expect(types.comma);
  3216. }
  3217. }
  3218. return members;
  3219. }
  3220. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3221. enumName
  3222. }) {
  3223. if (initializedMembers.length === 0) {
  3224. return defaultedMembers;
  3225. } else if (defaultedMembers.length === 0) {
  3226. return initializedMembers;
  3227. } else if (defaultedMembers.length > initializedMembers.length) {
  3228. for (let _i = 0; _i < initializedMembers.length; _i++) {
  3229. const member = initializedMembers[_i];
  3230. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3231. enumName
  3232. });
  3233. }
  3234. return defaultedMembers;
  3235. } else {
  3236. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  3237. const member = defaultedMembers[_i2];
  3238. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3239. enumName
  3240. });
  3241. }
  3242. return initializedMembers;
  3243. }
  3244. }
  3245. flowEnumParseExplicitType({
  3246. enumName
  3247. }) {
  3248. if (this.eatContextual("of")) {
  3249. if (!this.match(types.name)) {
  3250. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3251. enumName,
  3252. suppliedType: null
  3253. });
  3254. }
  3255. const {
  3256. value
  3257. } = this.state;
  3258. this.next();
  3259. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3260. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3261. enumName,
  3262. suppliedType: value
  3263. });
  3264. }
  3265. return value;
  3266. }
  3267. return null;
  3268. }
  3269. flowEnumBody(node, {
  3270. enumName,
  3271. nameLoc
  3272. }) {
  3273. const explicitType = this.flowEnumParseExplicitType({
  3274. enumName
  3275. });
  3276. this.expect(types.braceL);
  3277. const members = this.flowEnumMembers({
  3278. enumName,
  3279. explicitType
  3280. });
  3281. switch (explicitType) {
  3282. case "boolean":
  3283. node.explicitType = true;
  3284. node.members = members.booleanMembers;
  3285. this.expect(types.braceR);
  3286. return this.finishNode(node, "EnumBooleanBody");
  3287. case "number":
  3288. node.explicitType = true;
  3289. node.members = members.numberMembers;
  3290. this.expect(types.braceR);
  3291. return this.finishNode(node, "EnumNumberBody");
  3292. case "string":
  3293. node.explicitType = true;
  3294. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3295. enumName
  3296. });
  3297. this.expect(types.braceR);
  3298. return this.finishNode(node, "EnumStringBody");
  3299. case "symbol":
  3300. node.members = members.defaultedMembers;
  3301. this.expect(types.braceR);
  3302. return this.finishNode(node, "EnumSymbolBody");
  3303. default:
  3304. {
  3305. const empty = () => {
  3306. node.members = [];
  3307. this.expect(types.braceR);
  3308. return this.finishNode(node, "EnumStringBody");
  3309. };
  3310. node.explicitType = false;
  3311. const boolsLen = members.booleanMembers.length;
  3312. const numsLen = members.numberMembers.length;
  3313. const strsLen = members.stringMembers.length;
  3314. const defaultedLen = members.defaultedMembers.length;
  3315. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3316. return empty();
  3317. } else if (!boolsLen && !numsLen) {
  3318. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3319. enumName
  3320. });
  3321. this.expect(types.braceR);
  3322. return this.finishNode(node, "EnumStringBody");
  3323. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3324. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  3325. const member = _members$defaultedMem[_i3];
  3326. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3327. enumName,
  3328. memberName: member.id.name
  3329. });
  3330. }
  3331. node.members = members.booleanMembers;
  3332. this.expect(types.braceR);
  3333. return this.finishNode(node, "EnumBooleanBody");
  3334. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3335. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  3336. const member = _members$defaultedMem2[_i4];
  3337. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3338. enumName,
  3339. memberName: member.id.name
  3340. });
  3341. }
  3342. node.members = members.numberMembers;
  3343. this.expect(types.braceR);
  3344. return this.finishNode(node, "EnumNumberBody");
  3345. } else {
  3346. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3347. enumName
  3348. });
  3349. return empty();
  3350. }
  3351. }
  3352. }
  3353. }
  3354. flowParseEnumDeclaration(node) {
  3355. const id = this.parseIdentifier();
  3356. node.id = id;
  3357. node.body = this.flowEnumBody(this.startNode(), {
  3358. enumName: id.name,
  3359. nameLoc: id.start
  3360. });
  3361. return this.finishNode(node, "EnumDeclaration");
  3362. }
  3363. updateContext(prevType) {
  3364. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  3365. this.state.exprAllowed = false;
  3366. } else {
  3367. super.updateContext(prevType);
  3368. }
  3369. }
  3370. isLookaheadToken_lt() {
  3371. const next = this.nextTokenStart();
  3372. if (this.input.charCodeAt(next) === 60) {
  3373. const afterNext = this.input.charCodeAt(next + 1);
  3374. return afterNext !== 60 && afterNext !== 61;
  3375. }
  3376. return false;
  3377. }
  3378. maybeUnwrapTypeCastExpression(node) {
  3379. return node.type === "TypeCastExpression" ? node.expression : node;
  3380. }
  3381. }, _temp;
  3382. });
  3383. const entities = {
  3384. quot: "\u0022",
  3385. amp: "&",
  3386. apos: "\u0027",
  3387. lt: "<",
  3388. gt: ">",
  3389. nbsp: "\u00A0",
  3390. iexcl: "\u00A1",
  3391. cent: "\u00A2",
  3392. pound: "\u00A3",
  3393. curren: "\u00A4",
  3394. yen: "\u00A5",
  3395. brvbar: "\u00A6",
  3396. sect: "\u00A7",
  3397. uml: "\u00A8",
  3398. copy: "\u00A9",
  3399. ordf: "\u00AA",
  3400. laquo: "\u00AB",
  3401. not: "\u00AC",
  3402. shy: "\u00AD",
  3403. reg: "\u00AE",
  3404. macr: "\u00AF",
  3405. deg: "\u00B0",
  3406. plusmn: "\u00B1",
  3407. sup2: "\u00B2",
  3408. sup3: "\u00B3",
  3409. acute: "\u00B4",
  3410. micro: "\u00B5",
  3411. para: "\u00B6",
  3412. middot: "\u00B7",
  3413. cedil: "\u00B8",
  3414. sup1: "\u00B9",
  3415. ordm: "\u00BA",
  3416. raquo: "\u00BB",
  3417. frac14: "\u00BC",
  3418. frac12: "\u00BD",
  3419. frac34: "\u00BE",
  3420. iquest: "\u00BF",
  3421. Agrave: "\u00C0",
  3422. Aacute: "\u00C1",
  3423. Acirc: "\u00C2",
  3424. Atilde: "\u00C3",
  3425. Auml: "\u00C4",
  3426. Aring: "\u00C5",
  3427. AElig: "\u00C6",
  3428. Ccedil: "\u00C7",
  3429. Egrave: "\u00C8",
  3430. Eacute: "\u00C9",
  3431. Ecirc: "\u00CA",
  3432. Euml: "\u00CB",
  3433. Igrave: "\u00CC",
  3434. Iacute: "\u00CD",
  3435. Icirc: "\u00CE",
  3436. Iuml: "\u00CF",
  3437. ETH: "\u00D0",
  3438. Ntilde: "\u00D1",
  3439. Ograve: "\u00D2",
  3440. Oacute: "\u00D3",
  3441. Ocirc: "\u00D4",
  3442. Otilde: "\u00D5",
  3443. Ouml: "\u00D6",
  3444. times: "\u00D7",
  3445. Oslash: "\u00D8",
  3446. Ugrave: "\u00D9",
  3447. Uacute: "\u00DA",
  3448. Ucirc: "\u00DB",
  3449. Uuml: "\u00DC",
  3450. Yacute: "\u00DD",
  3451. THORN: "\u00DE",
  3452. szlig: "\u00DF",
  3453. agrave: "\u00E0",
  3454. aacute: "\u00E1",
  3455. acirc: "\u00E2",
  3456. atilde: "\u00E3",
  3457. auml: "\u00E4",
  3458. aring: "\u00E5",
  3459. aelig: "\u00E6",
  3460. ccedil: "\u00E7",
  3461. egrave: "\u00E8",
  3462. eacute: "\u00E9",
  3463. ecirc: "\u00EA",
  3464. euml: "\u00EB",
  3465. igrave: "\u00EC",
  3466. iacute: "\u00ED",
  3467. icirc: "\u00EE",
  3468. iuml: "\u00EF",
  3469. eth: "\u00F0",
  3470. ntilde: "\u00F1",
  3471. ograve: "\u00F2",
  3472. oacute: "\u00F3",
  3473. ocirc: "\u00F4",
  3474. otilde: "\u00F5",
  3475. ouml: "\u00F6",
  3476. divide: "\u00F7",
  3477. oslash: "\u00F8",
  3478. ugrave: "\u00F9",
  3479. uacute: "\u00FA",
  3480. ucirc: "\u00FB",
  3481. uuml: "\u00FC",
  3482. yacute: "\u00FD",
  3483. thorn: "\u00FE",
  3484. yuml: "\u00FF",
  3485. OElig: "\u0152",
  3486. oelig: "\u0153",
  3487. Scaron: "\u0160",
  3488. scaron: "\u0161",
  3489. Yuml: "\u0178",
  3490. fnof: "\u0192",
  3491. circ: "\u02C6",
  3492. tilde: "\u02DC",
  3493. Alpha: "\u0391",
  3494. Beta: "\u0392",
  3495. Gamma: "\u0393",
  3496. Delta: "\u0394",
  3497. Epsilon: "\u0395",
  3498. Zeta: "\u0396",
  3499. Eta: "\u0397",
  3500. Theta: "\u0398",
  3501. Iota: "\u0399",
  3502. Kappa: "\u039A",
  3503. Lambda: "\u039B",
  3504. Mu: "\u039C",
  3505. Nu: "\u039D",
  3506. Xi: "\u039E",
  3507. Omicron: "\u039F",
  3508. Pi: "\u03A0",
  3509. Rho: "\u03A1",
  3510. Sigma: "\u03A3",
  3511. Tau: "\u03A4",
  3512. Upsilon: "\u03A5",
  3513. Phi: "\u03A6",
  3514. Chi: "\u03A7",
  3515. Psi: "\u03A8",
  3516. Omega: "\u03A9",
  3517. alpha: "\u03B1",
  3518. beta: "\u03B2",
  3519. gamma: "\u03B3",
  3520. delta: "\u03B4",
  3521. epsilon: "\u03B5",
  3522. zeta: "\u03B6",
  3523. eta: "\u03B7",
  3524. theta: "\u03B8",
  3525. iota: "\u03B9",
  3526. kappa: "\u03BA",
  3527. lambda: "\u03BB",
  3528. mu: "\u03BC",
  3529. nu: "\u03BD",
  3530. xi: "\u03BE",
  3531. omicron: "\u03BF",
  3532. pi: "\u03C0",
  3533. rho: "\u03C1",
  3534. sigmaf: "\u03C2",
  3535. sigma: "\u03C3",
  3536. tau: "\u03C4",
  3537. upsilon: "\u03C5",
  3538. phi: "\u03C6",
  3539. chi: "\u03C7",
  3540. psi: "\u03C8",
  3541. omega: "\u03C9",
  3542. thetasym: "\u03D1",
  3543. upsih: "\u03D2",
  3544. piv: "\u03D6",
  3545. ensp: "\u2002",
  3546. emsp: "\u2003",
  3547. thinsp: "\u2009",
  3548. zwnj: "\u200C",
  3549. zwj: "\u200D",
  3550. lrm: "\u200E",
  3551. rlm: "\u200F",
  3552. ndash: "\u2013",
  3553. mdash: "\u2014",
  3554. lsquo: "\u2018",
  3555. rsquo: "\u2019",
  3556. sbquo: "\u201A",
  3557. ldquo: "\u201C",
  3558. rdquo: "\u201D",
  3559. bdquo: "\u201E",
  3560. dagger: "\u2020",
  3561. Dagger: "\u2021",
  3562. bull: "\u2022",
  3563. hellip: "\u2026",
  3564. permil: "\u2030",
  3565. prime: "\u2032",
  3566. Prime: "\u2033",
  3567. lsaquo: "\u2039",
  3568. rsaquo: "\u203A",
  3569. oline: "\u203E",
  3570. frasl: "\u2044",
  3571. euro: "\u20AC",
  3572. image: "\u2111",
  3573. weierp: "\u2118",
  3574. real: "\u211C",
  3575. trade: "\u2122",
  3576. alefsym: "\u2135",
  3577. larr: "\u2190",
  3578. uarr: "\u2191",
  3579. rarr: "\u2192",
  3580. darr: "\u2193",
  3581. harr: "\u2194",
  3582. crarr: "\u21B5",
  3583. lArr: "\u21D0",
  3584. uArr: "\u21D1",
  3585. rArr: "\u21D2",
  3586. dArr: "\u21D3",
  3587. hArr: "\u21D4",
  3588. forall: "\u2200",
  3589. part: "\u2202",
  3590. exist: "\u2203",
  3591. empty: "\u2205",
  3592. nabla: "\u2207",
  3593. isin: "\u2208",
  3594. notin: "\u2209",
  3595. ni: "\u220B",
  3596. prod: "\u220F",
  3597. sum: "\u2211",
  3598. minus: "\u2212",
  3599. lowast: "\u2217",
  3600. radic: "\u221A",
  3601. prop: "\u221D",
  3602. infin: "\u221E",
  3603. ang: "\u2220",
  3604. and: "\u2227",
  3605. or: "\u2228",
  3606. cap: "\u2229",
  3607. cup: "\u222A",
  3608. int: "\u222B",
  3609. there4: "\u2234",
  3610. sim: "\u223C",
  3611. cong: "\u2245",
  3612. asymp: "\u2248",
  3613. ne: "\u2260",
  3614. equiv: "\u2261",
  3615. le: "\u2264",
  3616. ge: "\u2265",
  3617. sub: "\u2282",
  3618. sup: "\u2283",
  3619. nsub: "\u2284",
  3620. sube: "\u2286",
  3621. supe: "\u2287",
  3622. oplus: "\u2295",
  3623. otimes: "\u2297",
  3624. perp: "\u22A5",
  3625. sdot: "\u22C5",
  3626. lceil: "\u2308",
  3627. rceil: "\u2309",
  3628. lfloor: "\u230A",
  3629. rfloor: "\u230B",
  3630. lang: "\u2329",
  3631. rang: "\u232A",
  3632. loz: "\u25CA",
  3633. spades: "\u2660",
  3634. clubs: "\u2663",
  3635. hearts: "\u2665",
  3636. diams: "\u2666"
  3637. };
  3638. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3639. const DECIMAL_NUMBER = /^\d+$/;
  3640. const JsxErrors = Object.freeze({
  3641. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3642. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3643. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3644. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3645. UnterminatedJsxContent: "Unterminated JSX contents",
  3646. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3647. });
  3648. types$1.j_oTag = new TokContext("<tag", false);
  3649. types$1.j_cTag = new TokContext("</tag", false);
  3650. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3651. types.jsxName = new TokenType("jsxName");
  3652. types.jsxText = new TokenType("jsxText", {
  3653. beforeExpr: true
  3654. });
  3655. types.jsxTagStart = new TokenType("jsxTagStart", {
  3656. startsExpr: true
  3657. });
  3658. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3659. types.jsxTagStart.updateContext = function () {
  3660. this.state.context.push(types$1.j_expr);
  3661. this.state.context.push(types$1.j_oTag);
  3662. this.state.exprAllowed = false;
  3663. };
  3664. types.jsxTagEnd.updateContext = function (prevType) {
  3665. const out = this.state.context.pop();
  3666. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3667. this.state.context.pop();
  3668. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3669. } else {
  3670. this.state.exprAllowed = true;
  3671. }
  3672. };
  3673. function isFragment(object) {
  3674. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3675. }
  3676. function getQualifiedJSXName(object) {
  3677. if (object.type === "JSXIdentifier") {
  3678. return object.name;
  3679. }
  3680. if (object.type === "JSXNamespacedName") {
  3681. return object.namespace.name + ":" + object.name.name;
  3682. }
  3683. if (object.type === "JSXMemberExpression") {
  3684. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3685. }
  3686. throw new Error("Node had unexpected type: " + object.type);
  3687. }
  3688. var jsx = (superClass => class extends superClass {
  3689. jsxReadToken() {
  3690. let out = "";
  3691. let chunkStart = this.state.pos;
  3692. for (;;) {
  3693. if (this.state.pos >= this.length) {
  3694. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  3695. }
  3696. const ch = this.input.charCodeAt(this.state.pos);
  3697. switch (ch) {
  3698. case 60:
  3699. case 123:
  3700. if (this.state.pos === this.state.start) {
  3701. if (ch === 60 && this.state.exprAllowed) {
  3702. ++this.state.pos;
  3703. return this.finishToken(types.jsxTagStart);
  3704. }
  3705. return super.getTokenFromCode(ch);
  3706. }
  3707. out += this.input.slice(chunkStart, this.state.pos);
  3708. return this.finishToken(types.jsxText, out);
  3709. case 38:
  3710. out += this.input.slice(chunkStart, this.state.pos);
  3711. out += this.jsxReadEntity();
  3712. chunkStart = this.state.pos;
  3713. break;
  3714. default:
  3715. if (isNewLine(ch)) {
  3716. out += this.input.slice(chunkStart, this.state.pos);
  3717. out += this.jsxReadNewLine(true);
  3718. chunkStart = this.state.pos;
  3719. } else {
  3720. ++this.state.pos;
  3721. }
  3722. }
  3723. }
  3724. }
  3725. jsxReadNewLine(normalizeCRLF) {
  3726. const ch = this.input.charCodeAt(this.state.pos);
  3727. let out;
  3728. ++this.state.pos;
  3729. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3730. ++this.state.pos;
  3731. out = normalizeCRLF ? "\n" : "\r\n";
  3732. } else {
  3733. out = String.fromCharCode(ch);
  3734. }
  3735. ++this.state.curLine;
  3736. this.state.lineStart = this.state.pos;
  3737. return out;
  3738. }
  3739. jsxReadString(quote) {
  3740. let out = "";
  3741. let chunkStart = ++this.state.pos;
  3742. for (;;) {
  3743. if (this.state.pos >= this.length) {
  3744. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3745. }
  3746. const ch = this.input.charCodeAt(this.state.pos);
  3747. if (ch === quote) break;
  3748. if (ch === 38) {
  3749. out += this.input.slice(chunkStart, this.state.pos);
  3750. out += this.jsxReadEntity();
  3751. chunkStart = this.state.pos;
  3752. } else if (isNewLine(ch)) {
  3753. out += this.input.slice(chunkStart, this.state.pos);
  3754. out += this.jsxReadNewLine(false);
  3755. chunkStart = this.state.pos;
  3756. } else {
  3757. ++this.state.pos;
  3758. }
  3759. }
  3760. out += this.input.slice(chunkStart, this.state.pos++);
  3761. return this.finishToken(types.string, out);
  3762. }
  3763. jsxReadEntity() {
  3764. let str = "";
  3765. let count = 0;
  3766. let entity;
  3767. let ch = this.input[this.state.pos];
  3768. const startPos = ++this.state.pos;
  3769. while (this.state.pos < this.length && count++ < 10) {
  3770. ch = this.input[this.state.pos++];
  3771. if (ch === ";") {
  3772. if (str[0] === "#") {
  3773. if (str[1] === "x") {
  3774. str = str.substr(2);
  3775. if (HEX_NUMBER.test(str)) {
  3776. entity = String.fromCodePoint(parseInt(str, 16));
  3777. }
  3778. } else {
  3779. str = str.substr(1);
  3780. if (DECIMAL_NUMBER.test(str)) {
  3781. entity = String.fromCodePoint(parseInt(str, 10));
  3782. }
  3783. }
  3784. } else {
  3785. entity = entities[str];
  3786. }
  3787. break;
  3788. }
  3789. str += ch;
  3790. }
  3791. if (!entity) {
  3792. this.state.pos = startPos;
  3793. return "&";
  3794. }
  3795. return entity;
  3796. }
  3797. jsxReadWord() {
  3798. let ch;
  3799. const start = this.state.pos;
  3800. do {
  3801. ch = this.input.charCodeAt(++this.state.pos);
  3802. } while (isIdentifierChar(ch) || ch === 45);
  3803. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3804. }
  3805. jsxParseIdentifier() {
  3806. const node = this.startNode();
  3807. if (this.match(types.jsxName)) {
  3808. node.name = this.state.value;
  3809. } else if (this.state.type.keyword) {
  3810. node.name = this.state.type.keyword;
  3811. } else {
  3812. this.unexpected();
  3813. }
  3814. this.next();
  3815. return this.finishNode(node, "JSXIdentifier");
  3816. }
  3817. jsxParseNamespacedName() {
  3818. const startPos = this.state.start;
  3819. const startLoc = this.state.startLoc;
  3820. const name = this.jsxParseIdentifier();
  3821. if (!this.eat(types.colon)) return name;
  3822. const node = this.startNodeAt(startPos, startLoc);
  3823. node.namespace = name;
  3824. node.name = this.jsxParseIdentifier();
  3825. return this.finishNode(node, "JSXNamespacedName");
  3826. }
  3827. jsxParseElementName() {
  3828. const startPos = this.state.start;
  3829. const startLoc = this.state.startLoc;
  3830. let node = this.jsxParseNamespacedName();
  3831. if (node.type === "JSXNamespacedName") {
  3832. return node;
  3833. }
  3834. while (this.eat(types.dot)) {
  3835. const newNode = this.startNodeAt(startPos, startLoc);
  3836. newNode.object = node;
  3837. newNode.property = this.jsxParseIdentifier();
  3838. node = this.finishNode(newNode, "JSXMemberExpression");
  3839. }
  3840. return node;
  3841. }
  3842. jsxParseAttributeValue() {
  3843. let node;
  3844. switch (this.state.type) {
  3845. case types.braceL:
  3846. node = this.startNode();
  3847. this.next();
  3848. node = this.jsxParseExpressionContainer(node);
  3849. if (node.expression.type === "JSXEmptyExpression") {
  3850. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  3851. }
  3852. return node;
  3853. case types.jsxTagStart:
  3854. case types.string:
  3855. return this.parseExprAtom();
  3856. default:
  3857. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  3858. }
  3859. }
  3860. jsxParseEmptyExpression() {
  3861. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3862. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3863. }
  3864. jsxParseSpreadChild(node) {
  3865. this.next();
  3866. node.expression = this.parseExpression();
  3867. this.expect(types.braceR);
  3868. return this.finishNode(node, "JSXSpreadChild");
  3869. }
  3870. jsxParseExpressionContainer(node) {
  3871. if (this.match(types.braceR)) {
  3872. node.expression = this.jsxParseEmptyExpression();
  3873. } else {
  3874. node.expression = this.parseExpression();
  3875. }
  3876. this.expect(types.braceR);
  3877. return this.finishNode(node, "JSXExpressionContainer");
  3878. }
  3879. jsxParseAttribute() {
  3880. const node = this.startNode();
  3881. if (this.eat(types.braceL)) {
  3882. this.expect(types.ellipsis);
  3883. node.argument = this.parseMaybeAssignAllowIn();
  3884. this.expect(types.braceR);
  3885. return this.finishNode(node, "JSXSpreadAttribute");
  3886. }
  3887. node.name = this.jsxParseNamespacedName();
  3888. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3889. return this.finishNode(node, "JSXAttribute");
  3890. }
  3891. jsxParseOpeningElementAt(startPos, startLoc) {
  3892. const node = this.startNodeAt(startPos, startLoc);
  3893. if (this.match(types.jsxTagEnd)) {
  3894. this.expect(types.jsxTagEnd);
  3895. return this.finishNode(node, "JSXOpeningFragment");
  3896. }
  3897. node.name = this.jsxParseElementName();
  3898. return this.jsxParseOpeningElementAfterName(node);
  3899. }
  3900. jsxParseOpeningElementAfterName(node) {
  3901. const attributes = [];
  3902. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3903. attributes.push(this.jsxParseAttribute());
  3904. }
  3905. node.attributes = attributes;
  3906. node.selfClosing = this.eat(types.slash);
  3907. this.expect(types.jsxTagEnd);
  3908. return this.finishNode(node, "JSXOpeningElement");
  3909. }
  3910. jsxParseClosingElementAt(startPos, startLoc) {
  3911. const node = this.startNodeAt(startPos, startLoc);
  3912. if (this.match(types.jsxTagEnd)) {
  3913. this.expect(types.jsxTagEnd);
  3914. return this.finishNode(node, "JSXClosingFragment");
  3915. }
  3916. node.name = this.jsxParseElementName();
  3917. this.expect(types.jsxTagEnd);
  3918. return this.finishNode(node, "JSXClosingElement");
  3919. }
  3920. jsxParseElementAt(startPos, startLoc) {
  3921. const node = this.startNodeAt(startPos, startLoc);
  3922. const children = [];
  3923. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3924. let closingElement = null;
  3925. if (!openingElement.selfClosing) {
  3926. contents: for (;;) {
  3927. switch (this.state.type) {
  3928. case types.jsxTagStart:
  3929. startPos = this.state.start;
  3930. startLoc = this.state.startLoc;
  3931. this.next();
  3932. if (this.eat(types.slash)) {
  3933. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3934. break contents;
  3935. }
  3936. children.push(this.jsxParseElementAt(startPos, startLoc));
  3937. break;
  3938. case types.jsxText:
  3939. children.push(this.parseExprAtom());
  3940. break;
  3941. case types.braceL:
  3942. {
  3943. const node = this.startNode();
  3944. this.next();
  3945. if (this.match(types.ellipsis)) {
  3946. children.push(this.jsxParseSpreadChild(node));
  3947. } else {
  3948. children.push(this.jsxParseExpressionContainer(node));
  3949. }
  3950. break;
  3951. }
  3952. default:
  3953. throw this.unexpected();
  3954. }
  3955. }
  3956. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3957. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  3958. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3959. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3960. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3961. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3962. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3963. }
  3964. }
  3965. }
  3966. if (isFragment(openingElement)) {
  3967. node.openingFragment = openingElement;
  3968. node.closingFragment = closingElement;
  3969. } else {
  3970. node.openingElement = openingElement;
  3971. node.closingElement = closingElement;
  3972. }
  3973. node.children = children;
  3974. if (this.isRelational("<")) {
  3975. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  3976. }
  3977. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3978. }
  3979. jsxParseElement() {
  3980. const startPos = this.state.start;
  3981. const startLoc = this.state.startLoc;
  3982. this.next();
  3983. return this.jsxParseElementAt(startPos, startLoc);
  3984. }
  3985. parseExprAtom(refExpressionErrors) {
  3986. if (this.match(types.jsxText)) {
  3987. return this.parseLiteral(this.state.value, "JSXText");
  3988. } else if (this.match(types.jsxTagStart)) {
  3989. return this.jsxParseElement();
  3990. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3991. this.finishToken(types.jsxTagStart);
  3992. return this.jsxParseElement();
  3993. } else {
  3994. return super.parseExprAtom(refExpressionErrors);
  3995. }
  3996. }
  3997. getTokenFromCode(code) {
  3998. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  3999. const context = this.curContext();
  4000. if (context === types$1.j_expr) {
  4001. return this.jsxReadToken();
  4002. }
  4003. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  4004. if (isIdentifierStart(code)) {
  4005. return this.jsxReadWord();
  4006. }
  4007. if (code === 62) {
  4008. ++this.state.pos;
  4009. return this.finishToken(types.jsxTagEnd);
  4010. }
  4011. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  4012. return this.jsxReadString(code);
  4013. }
  4014. }
  4015. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  4016. ++this.state.pos;
  4017. return this.finishToken(types.jsxTagStart);
  4018. }
  4019. return super.getTokenFromCode(code);
  4020. }
  4021. updateContext(prevType) {
  4022. if (this.match(types.braceL)) {
  4023. const curContext = this.curContext();
  4024. if (curContext === types$1.j_oTag) {
  4025. this.state.context.push(types$1.braceExpression);
  4026. } else if (curContext === types$1.j_expr) {
  4027. this.state.context.push(types$1.templateQuasi);
  4028. } else {
  4029. super.updateContext(prevType);
  4030. }
  4031. this.state.exprAllowed = true;
  4032. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  4033. this.state.context.length -= 2;
  4034. this.state.context.push(types$1.j_cTag);
  4035. this.state.exprAllowed = false;
  4036. } else {
  4037. return super.updateContext(prevType);
  4038. }
  4039. }
  4040. });
  4041. class Scope {
  4042. constructor(flags) {
  4043. this.flags = void 0;
  4044. this.var = [];
  4045. this.lexical = [];
  4046. this.functions = [];
  4047. this.flags = flags;
  4048. }
  4049. }
  4050. class ScopeHandler {
  4051. constructor(raise, inModule) {
  4052. this.scopeStack = [];
  4053. this.raise = void 0;
  4054. this.inModule = void 0;
  4055. this.undefinedExports = new Map();
  4056. this.undefinedPrivateNames = new Map();
  4057. this.raise = raise;
  4058. this.inModule = inModule;
  4059. }
  4060. get inFunction() {
  4061. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  4062. }
  4063. get allowSuper() {
  4064. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  4065. }
  4066. get allowDirectSuper() {
  4067. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  4068. }
  4069. get inClass() {
  4070. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  4071. }
  4072. get inNonArrowFunction() {
  4073. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  4074. }
  4075. get treatFunctionsAsVar() {
  4076. return this.treatFunctionsAsVarInScope(this.currentScope());
  4077. }
  4078. createScope(flags) {
  4079. return new Scope(flags);
  4080. }
  4081. enter(flags) {
  4082. this.scopeStack.push(this.createScope(flags));
  4083. }
  4084. exit() {
  4085. this.scopeStack.pop();
  4086. }
  4087. treatFunctionsAsVarInScope(scope) {
  4088. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  4089. }
  4090. declareName(name, bindingType, pos) {
  4091. let scope = this.currentScope();
  4092. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  4093. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4094. if (bindingType & BIND_SCOPE_FUNCTION) {
  4095. scope.functions.push(name);
  4096. } else {
  4097. scope.lexical.push(name);
  4098. }
  4099. if (bindingType & BIND_SCOPE_LEXICAL) {
  4100. this.maybeExportDefined(scope, name);
  4101. }
  4102. } else if (bindingType & BIND_SCOPE_VAR) {
  4103. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  4104. scope = this.scopeStack[i];
  4105. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4106. scope.var.push(name);
  4107. this.maybeExportDefined(scope, name);
  4108. if (scope.flags & SCOPE_VAR) break;
  4109. }
  4110. }
  4111. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4112. this.undefinedExports.delete(name);
  4113. }
  4114. }
  4115. maybeExportDefined(scope, name) {
  4116. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4117. this.undefinedExports.delete(name);
  4118. }
  4119. }
  4120. checkRedeclarationInScope(scope, name, bindingType, pos) {
  4121. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  4122. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  4123. }
  4124. }
  4125. isRedeclaredInScope(scope, name, bindingType) {
  4126. if (!(bindingType & BIND_KIND_VALUE)) return false;
  4127. if (bindingType & BIND_SCOPE_LEXICAL) {
  4128. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  4129. }
  4130. if (bindingType & BIND_SCOPE_FUNCTION) {
  4131. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  4132. }
  4133. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  4134. }
  4135. checkLocalExport(id) {
  4136. 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) {
  4137. this.undefinedExports.set(id.name, id.start);
  4138. }
  4139. }
  4140. currentScope() {
  4141. return this.scopeStack[this.scopeStack.length - 1];
  4142. }
  4143. currentVarScope() {
  4144. for (let i = this.scopeStack.length - 1;; i--) {
  4145. const scope = this.scopeStack[i];
  4146. if (scope.flags & SCOPE_VAR) {
  4147. return scope;
  4148. }
  4149. }
  4150. }
  4151. currentThisScope() {
  4152. for (let i = this.scopeStack.length - 1;; i--) {
  4153. const scope = this.scopeStack[i];
  4154. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  4155. return scope;
  4156. }
  4157. }
  4158. }
  4159. }
  4160. class TypeScriptScope extends Scope {
  4161. constructor(...args) {
  4162. super(...args);
  4163. this.types = [];
  4164. this.enums = [];
  4165. this.constEnums = [];
  4166. this.classes = [];
  4167. this.exportOnlyBindings = [];
  4168. }
  4169. }
  4170. class TypeScriptScopeHandler extends ScopeHandler {
  4171. createScope(flags) {
  4172. return new TypeScriptScope(flags);
  4173. }
  4174. declareName(name, bindingType, pos) {
  4175. const scope = this.currentScope();
  4176. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4177. this.maybeExportDefined(scope, name);
  4178. scope.exportOnlyBindings.push(name);
  4179. return;
  4180. }
  4181. super.declareName(...arguments);
  4182. if (bindingType & BIND_KIND_TYPE) {
  4183. if (!(bindingType & BIND_KIND_VALUE)) {
  4184. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4185. this.maybeExportDefined(scope, name);
  4186. }
  4187. scope.types.push(name);
  4188. }
  4189. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4190. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4191. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4192. }
  4193. isRedeclaredInScope(scope, name, bindingType) {
  4194. if (scope.enums.indexOf(name) > -1) {
  4195. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4196. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4197. const wasConst = scope.constEnums.indexOf(name) > -1;
  4198. return isConst !== wasConst;
  4199. }
  4200. return true;
  4201. }
  4202. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4203. if (scope.lexical.indexOf(name) > -1) {
  4204. return !!(bindingType & BIND_KIND_VALUE);
  4205. } else {
  4206. return false;
  4207. }
  4208. }
  4209. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4210. return true;
  4211. }
  4212. return super.isRedeclaredInScope(...arguments);
  4213. }
  4214. checkLocalExport(id) {
  4215. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4216. super.checkLocalExport(id);
  4217. }
  4218. }
  4219. }
  4220. const PARAM = 0b0000,
  4221. PARAM_YIELD = 0b0001,
  4222. PARAM_AWAIT = 0b0010,
  4223. PARAM_RETURN = 0b0100,
  4224. PARAM_IN = 0b1000;
  4225. class ProductionParameterHandler {
  4226. constructor() {
  4227. this.stacks = [];
  4228. }
  4229. enter(flags) {
  4230. this.stacks.push(flags);
  4231. }
  4232. exit() {
  4233. this.stacks.pop();
  4234. }
  4235. currentFlags() {
  4236. return this.stacks[this.stacks.length - 1];
  4237. }
  4238. get hasAwait() {
  4239. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4240. }
  4241. get hasYield() {
  4242. return (this.currentFlags() & PARAM_YIELD) > 0;
  4243. }
  4244. get hasReturn() {
  4245. return (this.currentFlags() & PARAM_RETURN) > 0;
  4246. }
  4247. get hasIn() {
  4248. return (this.currentFlags() & PARAM_IN) > 0;
  4249. }
  4250. }
  4251. function functionFlags(isAsync, isGenerator) {
  4252. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4253. }
  4254. function nonNull(x) {
  4255. if (x == null) {
  4256. throw new Error(`Unexpected ${x} value.`);
  4257. }
  4258. return x;
  4259. }
  4260. function assert(x) {
  4261. if (!x) {
  4262. throw new Error("Assert fail");
  4263. }
  4264. }
  4265. const TSErrors = Object.freeze({
  4266. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4267. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4268. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  4269. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  4270. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  4271. DuplicateModifier: "Duplicate modifier: '%0'",
  4272. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4273. EmptyTypeArguments: "Type argument list cannot be empty.",
  4274. EmptyTypeParameters: "Type parameter list cannot be empty.",
  4275. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4276. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4277. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4278. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
  4279. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  4280. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  4281. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4282. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4283. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4284. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4285. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4286. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  4287. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4288. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4289. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4290. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4291. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4292. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4293. });
  4294. function keywordTypeFromName(value) {
  4295. switch (value) {
  4296. case "any":
  4297. return "TSAnyKeyword";
  4298. case "boolean":
  4299. return "TSBooleanKeyword";
  4300. case "bigint":
  4301. return "TSBigIntKeyword";
  4302. case "never":
  4303. return "TSNeverKeyword";
  4304. case "number":
  4305. return "TSNumberKeyword";
  4306. case "object":
  4307. return "TSObjectKeyword";
  4308. case "string":
  4309. return "TSStringKeyword";
  4310. case "symbol":
  4311. return "TSSymbolKeyword";
  4312. case "undefined":
  4313. return "TSUndefinedKeyword";
  4314. case "unknown":
  4315. return "TSUnknownKeyword";
  4316. default:
  4317. return undefined;
  4318. }
  4319. }
  4320. var typescript = (superClass => class extends superClass {
  4321. getScopeHandler() {
  4322. return TypeScriptScopeHandler;
  4323. }
  4324. tsIsIdentifier() {
  4325. return this.match(types.name);
  4326. }
  4327. tsNextTokenCanFollowModifier() {
  4328. this.next();
  4329. return !this.hasPrecedingLineBreak() && !this.match(types.parenL) && !this.match(types.parenR) && !this.match(types.colon) && !this.match(types.eq) && !this.match(types.question) && !this.match(types.bang);
  4330. }
  4331. tsParseModifier(allowedModifiers) {
  4332. if (!this.match(types.name)) {
  4333. return undefined;
  4334. }
  4335. const modifier = this.state.value;
  4336. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4337. return modifier;
  4338. }
  4339. return undefined;
  4340. }
  4341. tsParseModifiers(modified, allowedModifiers) {
  4342. for (;;) {
  4343. const startPos = this.state.start;
  4344. const modifier = this.tsParseModifier(allowedModifiers);
  4345. if (!modifier) break;
  4346. if (Object.hasOwnProperty.call(modified, modifier)) {
  4347. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4348. }
  4349. modified[modifier] = true;
  4350. }
  4351. }
  4352. tsIsListTerminator(kind) {
  4353. switch (kind) {
  4354. case "EnumMembers":
  4355. case "TypeMembers":
  4356. return this.match(types.braceR);
  4357. case "HeritageClauseElement":
  4358. return this.match(types.braceL);
  4359. case "TupleElementTypes":
  4360. return this.match(types.bracketR);
  4361. case "TypeParametersOrArguments":
  4362. return this.isRelational(">");
  4363. }
  4364. throw new Error("Unreachable");
  4365. }
  4366. tsParseList(kind, parseElement) {
  4367. const result = [];
  4368. while (!this.tsIsListTerminator(kind)) {
  4369. result.push(parseElement());
  4370. }
  4371. return result;
  4372. }
  4373. tsParseDelimitedList(kind, parseElement) {
  4374. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4375. }
  4376. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4377. const result = [];
  4378. for (;;) {
  4379. if (this.tsIsListTerminator(kind)) {
  4380. break;
  4381. }
  4382. const element = parseElement();
  4383. if (element == null) {
  4384. return undefined;
  4385. }
  4386. result.push(element);
  4387. if (this.eat(types.comma)) {
  4388. continue;
  4389. }
  4390. if (this.tsIsListTerminator(kind)) {
  4391. break;
  4392. }
  4393. if (expectSuccess) {
  4394. this.expect(types.comma);
  4395. }
  4396. return undefined;
  4397. }
  4398. return result;
  4399. }
  4400. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4401. if (!skipFirstToken) {
  4402. if (bracket) {
  4403. this.expect(types.bracketL);
  4404. } else {
  4405. this.expectRelational("<");
  4406. }
  4407. }
  4408. const result = this.tsParseDelimitedList(kind, parseElement);
  4409. if (bracket) {
  4410. this.expect(types.bracketR);
  4411. } else {
  4412. this.expectRelational(">");
  4413. }
  4414. return result;
  4415. }
  4416. tsParseImportType() {
  4417. const node = this.startNode();
  4418. this.expect(types._import);
  4419. this.expect(types.parenL);
  4420. if (!this.match(types.string)) {
  4421. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4422. }
  4423. node.argument = this.parseExprAtom();
  4424. this.expect(types.parenR);
  4425. if (this.eat(types.dot)) {
  4426. node.qualifier = this.tsParseEntityName(true);
  4427. }
  4428. if (this.isRelational("<")) {
  4429. node.typeParameters = this.tsParseTypeArguments();
  4430. }
  4431. return this.finishNode(node, "TSImportType");
  4432. }
  4433. tsParseEntityName(allowReservedWords) {
  4434. let entity = this.parseIdentifier();
  4435. while (this.eat(types.dot)) {
  4436. const node = this.startNodeAtNode(entity);
  4437. node.left = entity;
  4438. node.right = this.parseIdentifier(allowReservedWords);
  4439. entity = this.finishNode(node, "TSQualifiedName");
  4440. }
  4441. return entity;
  4442. }
  4443. tsParseTypeReference() {
  4444. const node = this.startNode();
  4445. node.typeName = this.tsParseEntityName(false);
  4446. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4447. node.typeParameters = this.tsParseTypeArguments();
  4448. }
  4449. return this.finishNode(node, "TSTypeReference");
  4450. }
  4451. tsParseThisTypePredicate(lhs) {
  4452. this.next();
  4453. const node = this.startNodeAtNode(lhs);
  4454. node.parameterName = lhs;
  4455. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4456. return this.finishNode(node, "TSTypePredicate");
  4457. }
  4458. tsParseThisTypeNode() {
  4459. const node = this.startNode();
  4460. this.next();
  4461. return this.finishNode(node, "TSThisType");
  4462. }
  4463. tsParseTypeQuery() {
  4464. const node = this.startNode();
  4465. this.expect(types._typeof);
  4466. if (this.match(types._import)) {
  4467. node.exprName = this.tsParseImportType();
  4468. } else {
  4469. node.exprName = this.tsParseEntityName(true);
  4470. }
  4471. return this.finishNode(node, "TSTypeQuery");
  4472. }
  4473. tsParseTypeParameter() {
  4474. const node = this.startNode();
  4475. node.name = this.parseIdentifierName(node.start);
  4476. node.constraint = this.tsEatThenParseType(types._extends);
  4477. node.default = this.tsEatThenParseType(types.eq);
  4478. return this.finishNode(node, "TSTypeParameter");
  4479. }
  4480. tsTryParseTypeParameters() {
  4481. if (this.isRelational("<")) {
  4482. return this.tsParseTypeParameters();
  4483. }
  4484. }
  4485. tsParseTypeParameters() {
  4486. const node = this.startNode();
  4487. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4488. this.next();
  4489. } else {
  4490. this.unexpected();
  4491. }
  4492. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4493. if (node.params.length === 0) {
  4494. this.raise(node.start, TSErrors.EmptyTypeParameters);
  4495. }
  4496. return this.finishNode(node, "TSTypeParameterDeclaration");
  4497. }
  4498. tsTryNextParseConstantContext() {
  4499. if (this.lookahead().type === types._const) {
  4500. this.next();
  4501. return this.tsParseTypeReference();
  4502. }
  4503. return null;
  4504. }
  4505. tsFillSignature(returnToken, signature) {
  4506. const returnTokenRequired = returnToken === types.arrow;
  4507. signature.typeParameters = this.tsTryParseTypeParameters();
  4508. this.expect(types.parenL);
  4509. signature.parameters = this.tsParseBindingListForSignature();
  4510. if (returnTokenRequired) {
  4511. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4512. } else if (this.match(returnToken)) {
  4513. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4514. }
  4515. }
  4516. tsParseBindingListForSignature() {
  4517. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4518. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4519. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4520. }
  4521. return pattern;
  4522. });
  4523. }
  4524. tsParseTypeMemberSemicolon() {
  4525. if (!this.eat(types.comma)) {
  4526. this.semicolon();
  4527. }
  4528. }
  4529. tsParseSignatureMember(kind, node) {
  4530. this.tsFillSignature(types.colon, node);
  4531. this.tsParseTypeMemberSemicolon();
  4532. return this.finishNode(node, kind);
  4533. }
  4534. tsIsUnambiguouslyIndexSignature() {
  4535. this.next();
  4536. return this.eat(types.name) && this.match(types.colon);
  4537. }
  4538. tsTryParseIndexSignature(node) {
  4539. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4540. return undefined;
  4541. }
  4542. this.expect(types.bracketL);
  4543. const id = this.parseIdentifier();
  4544. id.typeAnnotation = this.tsParseTypeAnnotation();
  4545. this.resetEndLocation(id);
  4546. this.expect(types.bracketR);
  4547. node.parameters = [id];
  4548. const type = this.tsTryParseTypeAnnotation();
  4549. if (type) node.typeAnnotation = type;
  4550. this.tsParseTypeMemberSemicolon();
  4551. return this.finishNode(node, "TSIndexSignature");
  4552. }
  4553. tsParsePropertyOrMethodSignature(node, readonly) {
  4554. if (this.eat(types.question)) node.optional = true;
  4555. const nodeAny = node;
  4556. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  4557. const method = nodeAny;
  4558. this.tsFillSignature(types.colon, method);
  4559. this.tsParseTypeMemberSemicolon();
  4560. return this.finishNode(method, "TSMethodSignature");
  4561. } else {
  4562. const property = nodeAny;
  4563. if (readonly) property.readonly = true;
  4564. const type = this.tsTryParseTypeAnnotation();
  4565. if (type) property.typeAnnotation = type;
  4566. this.tsParseTypeMemberSemicolon();
  4567. return this.finishNode(property, "TSPropertySignature");
  4568. }
  4569. }
  4570. tsParseTypeMember() {
  4571. const node = this.startNode();
  4572. if (this.match(types.parenL) || this.isRelational("<")) {
  4573. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4574. }
  4575. if (this.match(types._new)) {
  4576. const id = this.startNode();
  4577. this.next();
  4578. if (this.match(types.parenL) || this.isRelational("<")) {
  4579. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4580. } else {
  4581. node.key = this.createIdentifier(id, "new");
  4582. return this.tsParsePropertyOrMethodSignature(node, false);
  4583. }
  4584. }
  4585. const readonly = !!this.tsParseModifier(["readonly"]);
  4586. const idx = this.tsTryParseIndexSignature(node);
  4587. if (idx) {
  4588. if (readonly) node.readonly = true;
  4589. return idx;
  4590. }
  4591. this.parsePropertyName(node, false);
  4592. return this.tsParsePropertyOrMethodSignature(node, readonly);
  4593. }
  4594. tsParseTypeLiteral() {
  4595. const node = this.startNode();
  4596. node.members = this.tsParseObjectTypeMembers();
  4597. return this.finishNode(node, "TSTypeLiteral");
  4598. }
  4599. tsParseObjectTypeMembers() {
  4600. this.expect(types.braceL);
  4601. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4602. this.expect(types.braceR);
  4603. return members;
  4604. }
  4605. tsIsStartOfMappedType() {
  4606. this.next();
  4607. if (this.eat(types.plusMin)) {
  4608. return this.isContextual("readonly");
  4609. }
  4610. if (this.isContextual("readonly")) {
  4611. this.next();
  4612. }
  4613. if (!this.match(types.bracketL)) {
  4614. return false;
  4615. }
  4616. this.next();
  4617. if (!this.tsIsIdentifier()) {
  4618. return false;
  4619. }
  4620. this.next();
  4621. return this.match(types._in);
  4622. }
  4623. tsParseMappedTypeParameter() {
  4624. const node = this.startNode();
  4625. node.name = this.parseIdentifierName(node.start);
  4626. node.constraint = this.tsExpectThenParseType(types._in);
  4627. return this.finishNode(node, "TSTypeParameter");
  4628. }
  4629. tsParseMappedType() {
  4630. const node = this.startNode();
  4631. this.expect(types.braceL);
  4632. if (this.match(types.plusMin)) {
  4633. node.readonly = this.state.value;
  4634. this.next();
  4635. this.expectContextual("readonly");
  4636. } else if (this.eatContextual("readonly")) {
  4637. node.readonly = true;
  4638. }
  4639. this.expect(types.bracketL);
  4640. node.typeParameter = this.tsParseMappedTypeParameter();
  4641. node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
  4642. this.expect(types.bracketR);
  4643. if (this.match(types.plusMin)) {
  4644. node.optional = this.state.value;
  4645. this.next();
  4646. this.expect(types.question);
  4647. } else if (this.eat(types.question)) {
  4648. node.optional = true;
  4649. }
  4650. node.typeAnnotation = this.tsTryParseType();
  4651. this.semicolon();
  4652. this.expect(types.braceR);
  4653. return this.finishNode(node, "TSMappedType");
  4654. }
  4655. tsParseTupleType() {
  4656. const node = this.startNode();
  4657. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4658. let seenOptionalElement = false;
  4659. let labeledElements = null;
  4660. node.elementTypes.forEach(elementNode => {
  4661. var _labeledElements;
  4662. let {
  4663. type
  4664. } = elementNode;
  4665. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  4666. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4667. }
  4668. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  4669. if (type === "TSRestType") {
  4670. elementNode = elementNode.typeAnnotation;
  4671. type = elementNode.type;
  4672. }
  4673. const isLabeled = type === "TSNamedTupleMember";
  4674. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  4675. if (labeledElements !== isLabeled) {
  4676. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  4677. }
  4678. });
  4679. return this.finishNode(node, "TSTupleType");
  4680. }
  4681. tsParseTupleElementType() {
  4682. const {
  4683. start: startPos,
  4684. startLoc
  4685. } = this.state;
  4686. const rest = this.eat(types.ellipsis);
  4687. let type = this.tsParseType();
  4688. const optional = this.eat(types.question);
  4689. const labeled = this.eat(types.colon);
  4690. if (labeled) {
  4691. const labeledNode = this.startNodeAtNode(type);
  4692. labeledNode.optional = optional;
  4693. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  4694. labeledNode.label = type.typeName;
  4695. } else {
  4696. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  4697. labeledNode.label = type;
  4698. }
  4699. labeledNode.elementType = this.tsParseType();
  4700. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  4701. } else if (optional) {
  4702. const optionalTypeNode = this.startNodeAtNode(type);
  4703. optionalTypeNode.typeAnnotation = type;
  4704. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  4705. }
  4706. if (rest) {
  4707. const restNode = this.startNodeAt(startPos, startLoc);
  4708. restNode.typeAnnotation = type;
  4709. type = this.finishNode(restNode, "TSRestType");
  4710. }
  4711. return type;
  4712. }
  4713. tsParseParenthesizedType() {
  4714. const node = this.startNode();
  4715. this.expect(types.parenL);
  4716. node.typeAnnotation = this.tsParseType();
  4717. this.expect(types.parenR);
  4718. return this.finishNode(node, "TSParenthesizedType");
  4719. }
  4720. tsParseFunctionOrConstructorType(type) {
  4721. const node = this.startNode();
  4722. if (type === "TSConstructorType") {
  4723. this.expect(types._new);
  4724. }
  4725. this.tsFillSignature(types.arrow, node);
  4726. return this.finishNode(node, type);
  4727. }
  4728. tsParseLiteralTypeNode() {
  4729. const node = this.startNode();
  4730. node.literal = (() => {
  4731. switch (this.state.type) {
  4732. case types.num:
  4733. case types.bigint:
  4734. case types.string:
  4735. case types._true:
  4736. case types._false:
  4737. return this.parseExprAtom();
  4738. default:
  4739. throw this.unexpected();
  4740. }
  4741. })();
  4742. return this.finishNode(node, "TSLiteralType");
  4743. }
  4744. tsParseTemplateLiteralType() {
  4745. const node = this.startNode();
  4746. node.literal = this.parseTemplate(false);
  4747. return this.finishNode(node, "TSLiteralType");
  4748. }
  4749. parseTemplateSubstitution() {
  4750. if (this.state.inType) return this.tsParseType();
  4751. return super.parseTemplateSubstitution();
  4752. }
  4753. tsParseThisTypeOrThisTypePredicate() {
  4754. const thisKeyword = this.tsParseThisTypeNode();
  4755. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4756. return this.tsParseThisTypePredicate(thisKeyword);
  4757. } else {
  4758. return thisKeyword;
  4759. }
  4760. }
  4761. tsParseNonArrayType() {
  4762. switch (this.state.type) {
  4763. case types.name:
  4764. case types._void:
  4765. case types._null:
  4766. {
  4767. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4768. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4769. const node = this.startNode();
  4770. this.next();
  4771. return this.finishNode(node, type);
  4772. }
  4773. return this.tsParseTypeReference();
  4774. }
  4775. case types.string:
  4776. case types.num:
  4777. case types.bigint:
  4778. case types._true:
  4779. case types._false:
  4780. return this.tsParseLiteralTypeNode();
  4781. case types.plusMin:
  4782. if (this.state.value === "-") {
  4783. const node = this.startNode();
  4784. const nextToken = this.lookahead();
  4785. if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
  4786. throw this.unexpected();
  4787. }
  4788. node.literal = this.parseMaybeUnary();
  4789. return this.finishNode(node, "TSLiteralType");
  4790. }
  4791. break;
  4792. case types._this:
  4793. return this.tsParseThisTypeOrThisTypePredicate();
  4794. case types._typeof:
  4795. return this.tsParseTypeQuery();
  4796. case types._import:
  4797. return this.tsParseImportType();
  4798. case types.braceL:
  4799. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4800. case types.bracketL:
  4801. return this.tsParseTupleType();
  4802. case types.parenL:
  4803. return this.tsParseParenthesizedType();
  4804. case types.backQuote:
  4805. return this.tsParseTemplateLiteralType();
  4806. }
  4807. throw this.unexpected();
  4808. }
  4809. tsParseArrayTypeOrHigher() {
  4810. let type = this.tsParseNonArrayType();
  4811. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4812. if (this.match(types.bracketR)) {
  4813. const node = this.startNodeAtNode(type);
  4814. node.elementType = type;
  4815. this.expect(types.bracketR);
  4816. type = this.finishNode(node, "TSArrayType");
  4817. } else {
  4818. const node = this.startNodeAtNode(type);
  4819. node.objectType = type;
  4820. node.indexType = this.tsParseType();
  4821. this.expect(types.bracketR);
  4822. type = this.finishNode(node, "TSIndexedAccessType");
  4823. }
  4824. }
  4825. return type;
  4826. }
  4827. tsParseTypeOperator(operator) {
  4828. const node = this.startNode();
  4829. this.expectContextual(operator);
  4830. node.operator = operator;
  4831. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4832. if (operator === "readonly") {
  4833. this.tsCheckTypeAnnotationForReadOnly(node);
  4834. }
  4835. return this.finishNode(node, "TSTypeOperator");
  4836. }
  4837. tsCheckTypeAnnotationForReadOnly(node) {
  4838. switch (node.typeAnnotation.type) {
  4839. case "TSTupleType":
  4840. case "TSArrayType":
  4841. return;
  4842. default:
  4843. this.raise(node.start, TSErrors.UnexpectedReadonly);
  4844. }
  4845. }
  4846. tsParseInferType() {
  4847. const node = this.startNode();
  4848. this.expectContextual("infer");
  4849. const typeParameter = this.startNode();
  4850. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4851. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4852. return this.finishNode(node, "TSInferType");
  4853. }
  4854. tsParseTypeOperatorOrHigher() {
  4855. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4856. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4857. }
  4858. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4859. this.eat(operator);
  4860. let type = parseConstituentType();
  4861. if (this.match(operator)) {
  4862. const types = [type];
  4863. while (this.eat(operator)) {
  4864. types.push(parseConstituentType());
  4865. }
  4866. const node = this.startNodeAtNode(type);
  4867. node.types = types;
  4868. type = this.finishNode(node, kind);
  4869. }
  4870. return type;
  4871. }
  4872. tsParseIntersectionTypeOrHigher() {
  4873. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4874. }
  4875. tsParseUnionTypeOrHigher() {
  4876. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4877. }
  4878. tsIsStartOfFunctionType() {
  4879. if (this.isRelational("<")) {
  4880. return true;
  4881. }
  4882. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4883. }
  4884. tsSkipParameterStart() {
  4885. if (this.match(types.name) || this.match(types._this)) {
  4886. this.next();
  4887. return true;
  4888. }
  4889. if (this.match(types.braceL)) {
  4890. let braceStackCounter = 1;
  4891. this.next();
  4892. while (braceStackCounter > 0) {
  4893. if (this.match(types.braceL)) {
  4894. ++braceStackCounter;
  4895. } else if (this.match(types.braceR)) {
  4896. --braceStackCounter;
  4897. }
  4898. this.next();
  4899. }
  4900. return true;
  4901. }
  4902. if (this.match(types.bracketL)) {
  4903. let braceStackCounter = 1;
  4904. this.next();
  4905. while (braceStackCounter > 0) {
  4906. if (this.match(types.bracketL)) {
  4907. ++braceStackCounter;
  4908. } else if (this.match(types.bracketR)) {
  4909. --braceStackCounter;
  4910. }
  4911. this.next();
  4912. }
  4913. return true;
  4914. }
  4915. return false;
  4916. }
  4917. tsIsUnambiguouslyStartOfFunctionType() {
  4918. this.next();
  4919. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4920. return true;
  4921. }
  4922. if (this.tsSkipParameterStart()) {
  4923. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4924. return true;
  4925. }
  4926. if (this.match(types.parenR)) {
  4927. this.next();
  4928. if (this.match(types.arrow)) {
  4929. return true;
  4930. }
  4931. }
  4932. }
  4933. return false;
  4934. }
  4935. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4936. return this.tsInType(() => {
  4937. const t = this.startNode();
  4938. this.expect(returnToken);
  4939. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4940. if (asserts && this.match(types._this)) {
  4941. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4942. if (thisTypePredicate.type === "TSThisType") {
  4943. const node = this.startNodeAtNode(t);
  4944. node.parameterName = thisTypePredicate;
  4945. node.asserts = true;
  4946. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4947. } else {
  4948. thisTypePredicate.asserts = true;
  4949. }
  4950. t.typeAnnotation = thisTypePredicate;
  4951. return this.finishNode(t, "TSTypeAnnotation");
  4952. }
  4953. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4954. if (!typePredicateVariable) {
  4955. if (!asserts) {
  4956. return this.tsParseTypeAnnotation(false, t);
  4957. }
  4958. const node = this.startNodeAtNode(t);
  4959. node.parameterName = this.parseIdentifier();
  4960. node.asserts = asserts;
  4961. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4962. return this.finishNode(t, "TSTypeAnnotation");
  4963. }
  4964. const type = this.tsParseTypeAnnotation(false);
  4965. const node = this.startNodeAtNode(t);
  4966. node.parameterName = typePredicateVariable;
  4967. node.typeAnnotation = type;
  4968. node.asserts = asserts;
  4969. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4970. return this.finishNode(t, "TSTypeAnnotation");
  4971. });
  4972. }
  4973. tsTryParseTypeOrTypePredicateAnnotation() {
  4974. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4975. }
  4976. tsTryParseTypeAnnotation() {
  4977. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4978. }
  4979. tsTryParseType() {
  4980. return this.tsEatThenParseType(types.colon);
  4981. }
  4982. tsParseTypePredicatePrefix() {
  4983. const id = this.parseIdentifier();
  4984. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4985. this.next();
  4986. return id;
  4987. }
  4988. }
  4989. tsParseTypePredicateAsserts() {
  4990. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4991. return false;
  4992. }
  4993. const containsEsc = this.state.containsEsc;
  4994. this.next();
  4995. if (!this.match(types.name) && !this.match(types._this)) {
  4996. return false;
  4997. }
  4998. if (containsEsc) {
  4999. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  5000. }
  5001. return true;
  5002. }
  5003. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  5004. this.tsInType(() => {
  5005. if (eatColon) this.expect(types.colon);
  5006. t.typeAnnotation = this.tsParseType();
  5007. });
  5008. return this.finishNode(t, "TSTypeAnnotation");
  5009. }
  5010. tsParseType() {
  5011. assert(this.state.inType);
  5012. const type = this.tsParseNonConditionalType();
  5013. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  5014. return type;
  5015. }
  5016. const node = this.startNodeAtNode(type);
  5017. node.checkType = type;
  5018. node.extendsType = this.tsParseNonConditionalType();
  5019. this.expect(types.question);
  5020. node.trueType = this.tsParseType();
  5021. this.expect(types.colon);
  5022. node.falseType = this.tsParseType();
  5023. return this.finishNode(node, "TSConditionalType");
  5024. }
  5025. tsParseNonConditionalType() {
  5026. if (this.tsIsStartOfFunctionType()) {
  5027. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  5028. }
  5029. if (this.match(types._new)) {
  5030. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  5031. }
  5032. return this.tsParseUnionTypeOrHigher();
  5033. }
  5034. tsParseTypeAssertion() {
  5035. const node = this.startNode();
  5036. const _const = this.tsTryNextParseConstantContext();
  5037. node.typeAnnotation = _const || this.tsNextThenParseType();
  5038. this.expectRelational(">");
  5039. node.expression = this.parseMaybeUnary();
  5040. return this.finishNode(node, "TSTypeAssertion");
  5041. }
  5042. tsParseHeritageClause(descriptor) {
  5043. const originalStart = this.state.start;
  5044. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  5045. if (!delimitedList.length) {
  5046. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  5047. }
  5048. return delimitedList;
  5049. }
  5050. tsParseExpressionWithTypeArguments() {
  5051. const node = this.startNode();
  5052. node.expression = this.tsParseEntityName(false);
  5053. if (this.isRelational("<")) {
  5054. node.typeParameters = this.tsParseTypeArguments();
  5055. }
  5056. return this.finishNode(node, "TSExpressionWithTypeArguments");
  5057. }
  5058. tsParseInterfaceDeclaration(node) {
  5059. node.id = this.parseIdentifier();
  5060. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  5061. node.typeParameters = this.tsTryParseTypeParameters();
  5062. if (this.eat(types._extends)) {
  5063. node.extends = this.tsParseHeritageClause("extends");
  5064. }
  5065. const body = this.startNode();
  5066. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  5067. node.body = this.finishNode(body, "TSInterfaceBody");
  5068. return this.finishNode(node, "TSInterfaceDeclaration");
  5069. }
  5070. tsParseTypeAliasDeclaration(node) {
  5071. node.id = this.parseIdentifier();
  5072. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  5073. node.typeParameters = this.tsTryParseTypeParameters();
  5074. node.typeAnnotation = this.tsInType(() => {
  5075. this.expect(types.eq);
  5076. if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
  5077. const node = this.startNode();
  5078. this.next();
  5079. return this.finishNode(node, "TSIntrinsicKeyword");
  5080. }
  5081. return this.tsParseType();
  5082. });
  5083. this.semicolon();
  5084. return this.finishNode(node, "TSTypeAliasDeclaration");
  5085. }
  5086. tsInNoContext(cb) {
  5087. const oldContext = this.state.context;
  5088. this.state.context = [oldContext[0]];
  5089. try {
  5090. return cb();
  5091. } finally {
  5092. this.state.context = oldContext;
  5093. }
  5094. }
  5095. tsInType(cb) {
  5096. const oldInType = this.state.inType;
  5097. this.state.inType = true;
  5098. try {
  5099. return cb();
  5100. } finally {
  5101. this.state.inType = oldInType;
  5102. }
  5103. }
  5104. tsEatThenParseType(token) {
  5105. return !this.match(token) ? undefined : this.tsNextThenParseType();
  5106. }
  5107. tsExpectThenParseType(token) {
  5108. return this.tsDoThenParseType(() => this.expect(token));
  5109. }
  5110. tsNextThenParseType() {
  5111. return this.tsDoThenParseType(() => this.next());
  5112. }
  5113. tsDoThenParseType(cb) {
  5114. return this.tsInType(() => {
  5115. cb();
  5116. return this.tsParseType();
  5117. });
  5118. }
  5119. tsParseEnumMember() {
  5120. const node = this.startNode();
  5121. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  5122. if (this.eat(types.eq)) {
  5123. node.initializer = this.parseMaybeAssignAllowIn();
  5124. }
  5125. return this.finishNode(node, "TSEnumMember");
  5126. }
  5127. tsParseEnumDeclaration(node, isConst) {
  5128. if (isConst) node.const = true;
  5129. node.id = this.parseIdentifier();
  5130. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  5131. this.expect(types.braceL);
  5132. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  5133. this.expect(types.braceR);
  5134. return this.finishNode(node, "TSEnumDeclaration");
  5135. }
  5136. tsParseModuleBlock() {
  5137. const node = this.startNode();
  5138. this.scope.enter(SCOPE_OTHER);
  5139. this.expect(types.braceL);
  5140. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  5141. this.scope.exit();
  5142. return this.finishNode(node, "TSModuleBlock");
  5143. }
  5144. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  5145. node.id = this.parseIdentifier();
  5146. if (!nested) {
  5147. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  5148. }
  5149. if (this.eat(types.dot)) {
  5150. const inner = this.startNode();
  5151. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  5152. node.body = inner;
  5153. } else {
  5154. this.scope.enter(SCOPE_TS_MODULE);
  5155. this.prodParam.enter(PARAM);
  5156. node.body = this.tsParseModuleBlock();
  5157. this.prodParam.exit();
  5158. this.scope.exit();
  5159. }
  5160. return this.finishNode(node, "TSModuleDeclaration");
  5161. }
  5162. tsParseAmbientExternalModuleDeclaration(node) {
  5163. if (this.isContextual("global")) {
  5164. node.global = true;
  5165. node.id = this.parseIdentifier();
  5166. } else if (this.match(types.string)) {
  5167. node.id = this.parseExprAtom();
  5168. } else {
  5169. this.unexpected();
  5170. }
  5171. if (this.match(types.braceL)) {
  5172. this.scope.enter(SCOPE_TS_MODULE);
  5173. this.prodParam.enter(PARAM);
  5174. node.body = this.tsParseModuleBlock();
  5175. this.prodParam.exit();
  5176. this.scope.exit();
  5177. } else {
  5178. this.semicolon();
  5179. }
  5180. return this.finishNode(node, "TSModuleDeclaration");
  5181. }
  5182. tsParseImportEqualsDeclaration(node, isExport) {
  5183. node.isExport = isExport || false;
  5184. node.id = this.parseIdentifier();
  5185. this.checkLVal(node.id, BIND_LEXICAL, undefined, "import equals declaration");
  5186. this.expect(types.eq);
  5187. node.moduleReference = this.tsParseModuleReference();
  5188. this.semicolon();
  5189. return this.finishNode(node, "TSImportEqualsDeclaration");
  5190. }
  5191. tsIsExternalModuleReference() {
  5192. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5193. }
  5194. tsParseModuleReference() {
  5195. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5196. }
  5197. tsParseExternalModuleReference() {
  5198. const node = this.startNode();
  5199. this.expectContextual("require");
  5200. this.expect(types.parenL);
  5201. if (!this.match(types.string)) {
  5202. throw this.unexpected();
  5203. }
  5204. node.expression = this.parseExprAtom();
  5205. this.expect(types.parenR);
  5206. return this.finishNode(node, "TSExternalModuleReference");
  5207. }
  5208. tsLookAhead(f) {
  5209. const state = this.state.clone();
  5210. const res = f();
  5211. this.state = state;
  5212. return res;
  5213. }
  5214. tsTryParseAndCatch(f) {
  5215. const result = this.tryParse(abort => f() || abort());
  5216. if (result.aborted || !result.node) return undefined;
  5217. if (result.error) this.state = result.failState;
  5218. return result.node;
  5219. }
  5220. tsTryParse(f) {
  5221. const state = this.state.clone();
  5222. const result = f();
  5223. if (result !== undefined && result !== false) {
  5224. return result;
  5225. } else {
  5226. this.state = state;
  5227. return undefined;
  5228. }
  5229. }
  5230. tsTryParseDeclare(nany) {
  5231. if (this.isLineTerminator()) {
  5232. return;
  5233. }
  5234. let starttype = this.state.type;
  5235. let kind;
  5236. if (this.isContextual("let")) {
  5237. starttype = types._var;
  5238. kind = "let";
  5239. }
  5240. return this.tsInDeclareContext(() => {
  5241. switch (starttype) {
  5242. case types._function:
  5243. nany.declare = true;
  5244. return this.parseFunctionStatement(nany, false, true);
  5245. case types._class:
  5246. nany.declare = true;
  5247. return this.parseClass(nany, true, false);
  5248. case types._const:
  5249. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5250. this.expect(types._const);
  5251. this.expectContextual("enum");
  5252. return this.tsParseEnumDeclaration(nany, true);
  5253. }
  5254. case types._var:
  5255. kind = kind || this.state.value;
  5256. return this.parseVarStatement(nany, kind);
  5257. case types.name:
  5258. {
  5259. const value = this.state.value;
  5260. if (value === "global") {
  5261. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5262. } else {
  5263. return this.tsParseDeclaration(nany, value, true);
  5264. }
  5265. }
  5266. }
  5267. });
  5268. }
  5269. tsTryParseExportDeclaration() {
  5270. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5271. }
  5272. tsParseExpressionStatement(node, expr) {
  5273. switch (expr.name) {
  5274. case "declare":
  5275. {
  5276. const declaration = this.tsTryParseDeclare(node);
  5277. if (declaration) {
  5278. declaration.declare = true;
  5279. return declaration;
  5280. }
  5281. break;
  5282. }
  5283. case "global":
  5284. if (this.match(types.braceL)) {
  5285. this.scope.enter(SCOPE_TS_MODULE);
  5286. this.prodParam.enter(PARAM);
  5287. const mod = node;
  5288. mod.global = true;
  5289. mod.id = expr;
  5290. mod.body = this.tsParseModuleBlock();
  5291. this.scope.exit();
  5292. this.prodParam.exit();
  5293. return this.finishNode(mod, "TSModuleDeclaration");
  5294. }
  5295. break;
  5296. default:
  5297. return this.tsParseDeclaration(node, expr.name, false);
  5298. }
  5299. }
  5300. tsParseDeclaration(node, value, next) {
  5301. switch (value) {
  5302. case "abstract":
  5303. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  5304. const cls = node;
  5305. cls.abstract = true;
  5306. if (next) {
  5307. this.next();
  5308. if (!this.match(types._class)) {
  5309. this.unexpected(null, types._class);
  5310. }
  5311. }
  5312. return this.parseClass(cls, true, false);
  5313. }
  5314. break;
  5315. case "enum":
  5316. if (next || this.match(types.name)) {
  5317. if (next) this.next();
  5318. return this.tsParseEnumDeclaration(node, false);
  5319. }
  5320. break;
  5321. case "interface":
  5322. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5323. if (next) this.next();
  5324. return this.tsParseInterfaceDeclaration(node);
  5325. }
  5326. break;
  5327. case "module":
  5328. if (next) this.next();
  5329. if (this.match(types.string)) {
  5330. return this.tsParseAmbientExternalModuleDeclaration(node);
  5331. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5332. return this.tsParseModuleOrNamespaceDeclaration(node);
  5333. }
  5334. break;
  5335. case "namespace":
  5336. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5337. if (next) this.next();
  5338. return this.tsParseModuleOrNamespaceDeclaration(node);
  5339. }
  5340. break;
  5341. case "type":
  5342. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5343. if (next) this.next();
  5344. return this.tsParseTypeAliasDeclaration(node);
  5345. }
  5346. break;
  5347. }
  5348. }
  5349. tsCheckLineTerminatorAndMatch(tokenType, next) {
  5350. return (next || this.match(tokenType)) && !this.isLineTerminator();
  5351. }
  5352. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5353. if (!this.isRelational("<")) {
  5354. return undefined;
  5355. }
  5356. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5357. const oldYieldPos = this.state.yieldPos;
  5358. const oldAwaitPos = this.state.awaitPos;
  5359. this.state.maybeInArrowParameters = true;
  5360. this.state.yieldPos = -1;
  5361. this.state.awaitPos = -1;
  5362. const res = this.tsTryParseAndCatch(() => {
  5363. const node = this.startNodeAt(startPos, startLoc);
  5364. node.typeParameters = this.tsParseTypeParameters();
  5365. super.parseFunctionParams(node);
  5366. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5367. this.expect(types.arrow);
  5368. return node;
  5369. });
  5370. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5371. this.state.yieldPos = oldYieldPos;
  5372. this.state.awaitPos = oldAwaitPos;
  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, BIND_TS_AMBIENT, null, "function name");
  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. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5480. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5481. this.state.exprAllowed = false;
  5482. this.next();
  5483. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5484. nonNullExpression.expression = base;
  5485. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5486. }
  5487. if (this.isRelational("<")) {
  5488. const result = this.tsTryParseAndCatch(() => {
  5489. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5490. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5491. if (asyncArrowFn) {
  5492. return asyncArrowFn;
  5493. }
  5494. }
  5495. const node = this.startNodeAt(startPos, startLoc);
  5496. node.callee = base;
  5497. const typeArguments = this.tsParseTypeArguments();
  5498. if (typeArguments) {
  5499. if (!noCalls && this.eat(types.parenL)) {
  5500. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5501. this.tsCheckForInvalidTypeCasts(node.arguments);
  5502. node.typeParameters = typeArguments;
  5503. return this.finishCallExpression(node, state.optionalChainMember);
  5504. } else if (this.match(types.backQuote)) {
  5505. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  5506. result.typeParameters = typeArguments;
  5507. return result;
  5508. }
  5509. }
  5510. this.unexpected();
  5511. });
  5512. if (result) return result;
  5513. }
  5514. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5515. }
  5516. parseNewArguments(node) {
  5517. if (this.isRelational("<")) {
  5518. const typeParameters = this.tsTryParseAndCatch(() => {
  5519. const args = this.tsParseTypeArguments();
  5520. if (!this.match(types.parenL)) this.unexpected();
  5521. return args;
  5522. });
  5523. if (typeParameters) {
  5524. node.typeParameters = typeParameters;
  5525. }
  5526. }
  5527. super.parseNewArguments(node);
  5528. }
  5529. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  5530. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5531. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5532. node.expression = left;
  5533. const _const = this.tsTryNextParseConstantContext();
  5534. if (_const) {
  5535. node.typeAnnotation = _const;
  5536. } else {
  5537. node.typeAnnotation = this.tsNextThenParseType();
  5538. }
  5539. this.finishNode(node, "TSAsExpression");
  5540. this.reScan_lt_gt();
  5541. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  5542. }
  5543. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  5544. }
  5545. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5546. checkDuplicateExports() {}
  5547. parseImport(node) {
  5548. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5549. const ahead = this.lookahead();
  5550. if (this.match(types.name) && ahead.type === types.eq) {
  5551. return this.tsParseImportEqualsDeclaration(node);
  5552. }
  5553. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  5554. node.importKind = "type";
  5555. this.next();
  5556. } else {
  5557. node.importKind = "value";
  5558. }
  5559. }
  5560. const importNode = super.parseImport(node);
  5561. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5562. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5563. }
  5564. return importNode;
  5565. }
  5566. parseExport(node) {
  5567. if (this.match(types._import)) {
  5568. this.expect(types._import);
  5569. return this.tsParseImportEqualsDeclaration(node, true);
  5570. } else if (this.eat(types.eq)) {
  5571. const assign = node;
  5572. assign.expression = this.parseExpression();
  5573. this.semicolon();
  5574. return this.finishNode(assign, "TSExportAssignment");
  5575. } else if (this.eatContextual("as")) {
  5576. const decl = node;
  5577. this.expectContextual("namespace");
  5578. decl.id = this.parseIdentifier();
  5579. this.semicolon();
  5580. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5581. } else {
  5582. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5583. this.next();
  5584. node.exportKind = "type";
  5585. } else {
  5586. node.exportKind = "value";
  5587. }
  5588. return super.parseExport(node);
  5589. }
  5590. }
  5591. isAbstractClass() {
  5592. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5593. }
  5594. parseExportDefaultExpression() {
  5595. if (this.isAbstractClass()) {
  5596. const cls = this.startNode();
  5597. this.next();
  5598. this.parseClass(cls, true, true);
  5599. cls.abstract = true;
  5600. return cls;
  5601. }
  5602. if (this.state.value === "interface") {
  5603. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5604. if (result) return result;
  5605. }
  5606. return super.parseExportDefaultExpression();
  5607. }
  5608. parseStatementContent(context, topLevel) {
  5609. if (this.state.type === types._const) {
  5610. const ahead = this.lookahead();
  5611. if (ahead.type === types.name && ahead.value === "enum") {
  5612. const node = this.startNode();
  5613. this.expect(types._const);
  5614. this.expectContextual("enum");
  5615. return this.tsParseEnumDeclaration(node, true);
  5616. }
  5617. }
  5618. return super.parseStatementContent(context, topLevel);
  5619. }
  5620. parseAccessModifier() {
  5621. return this.tsParseModifier(["public", "protected", "private"]);
  5622. }
  5623. parseClassMember(classBody, member, state) {
  5624. this.tsParseModifiers(member, ["declare"]);
  5625. const accessibility = this.parseAccessModifier();
  5626. if (accessibility) member.accessibility = accessibility;
  5627. this.tsParseModifiers(member, ["declare"]);
  5628. const callParseClassMember = () => {
  5629. super.parseClassMember(classBody, member, state);
  5630. };
  5631. if (member.declare) {
  5632. this.tsInDeclareContext(callParseClassMember);
  5633. } else {
  5634. callParseClassMember();
  5635. }
  5636. }
  5637. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  5638. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5639. const idx = this.tsTryParseIndexSignature(member);
  5640. if (idx) {
  5641. classBody.body.push(idx);
  5642. if (member.abstract) {
  5643. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5644. }
  5645. if (isStatic) {
  5646. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5647. }
  5648. if (member.accessibility) {
  5649. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5650. }
  5651. if (member.declare) {
  5652. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  5653. }
  5654. return;
  5655. }
  5656. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  5657. }
  5658. parsePostMemberNameModifiers(methodOrProp) {
  5659. const optional = this.eat(types.question);
  5660. if (optional) methodOrProp.optional = true;
  5661. if (methodOrProp.readonly && this.match(types.parenL)) {
  5662. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5663. }
  5664. if (methodOrProp.declare && this.match(types.parenL)) {
  5665. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5666. }
  5667. }
  5668. parseExpressionStatement(node, expr) {
  5669. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5670. return decl || super.parseExpressionStatement(node, expr);
  5671. }
  5672. shouldParseExportDeclaration() {
  5673. if (this.tsIsDeclarationStart()) return true;
  5674. return super.shouldParseExportDeclaration();
  5675. }
  5676. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  5677. if (!refNeedsArrowPos || !this.match(types.question)) {
  5678. return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  5679. }
  5680. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  5681. if (!result.node) {
  5682. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5683. return expr;
  5684. }
  5685. if (result.error) this.state = result.failState;
  5686. return result.node;
  5687. }
  5688. parseParenItem(node, startPos, startLoc) {
  5689. node = super.parseParenItem(node, startPos, startLoc);
  5690. if (this.eat(types.question)) {
  5691. node.optional = true;
  5692. this.resetEndLocation(node);
  5693. }
  5694. if (this.match(types.colon)) {
  5695. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5696. typeCastNode.expression = node;
  5697. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5698. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5699. }
  5700. return node;
  5701. }
  5702. parseExportDeclaration(node) {
  5703. const startPos = this.state.start;
  5704. const startLoc = this.state.startLoc;
  5705. const isDeclare = this.eatContextual("declare");
  5706. let declaration;
  5707. if (this.match(types.name)) {
  5708. declaration = this.tsTryParseExportDeclaration();
  5709. }
  5710. if (!declaration) {
  5711. declaration = super.parseExportDeclaration(node);
  5712. }
  5713. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5714. node.exportKind = "type";
  5715. }
  5716. if (declaration && isDeclare) {
  5717. this.resetStartLocation(declaration, startPos, startLoc);
  5718. declaration.declare = true;
  5719. }
  5720. return declaration;
  5721. }
  5722. parseClassId(node, isStatement, optionalId) {
  5723. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5724. return;
  5725. }
  5726. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5727. const typeParameters = this.tsTryParseTypeParameters();
  5728. if (typeParameters) node.typeParameters = typeParameters;
  5729. }
  5730. parseClassPropertyAnnotation(node) {
  5731. if (!node.optional && this.eat(types.bang)) {
  5732. node.definite = true;
  5733. }
  5734. const type = this.tsTryParseTypeAnnotation();
  5735. if (type) node.typeAnnotation = type;
  5736. }
  5737. parseClassProperty(node) {
  5738. this.parseClassPropertyAnnotation(node);
  5739. if (this.state.isDeclareContext && this.match(types.eq)) {
  5740. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5741. }
  5742. return super.parseClassProperty(node);
  5743. }
  5744. parseClassPrivateProperty(node) {
  5745. if (node.abstract) {
  5746. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  5747. }
  5748. if (node.accessibility) {
  5749. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  5750. }
  5751. this.parseClassPropertyAnnotation(node);
  5752. return super.parseClassPrivateProperty(node);
  5753. }
  5754. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5755. const typeParameters = this.tsTryParseTypeParameters();
  5756. if (typeParameters && isConstructor) {
  5757. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  5758. }
  5759. if (typeParameters) method.typeParameters = typeParameters;
  5760. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5761. }
  5762. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5763. const typeParameters = this.tsTryParseTypeParameters();
  5764. if (typeParameters) method.typeParameters = typeParameters;
  5765. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5766. }
  5767. parseClassSuper(node) {
  5768. super.parseClassSuper(node);
  5769. if (node.superClass && this.isRelational("<")) {
  5770. node.superTypeParameters = this.tsParseTypeArguments();
  5771. }
  5772. if (this.eatContextual("implements")) {
  5773. node.implements = this.tsParseHeritageClause("implements");
  5774. }
  5775. }
  5776. parseObjPropValue(prop, ...args) {
  5777. const typeParameters = this.tsTryParseTypeParameters();
  5778. if (typeParameters) prop.typeParameters = typeParameters;
  5779. super.parseObjPropValue(prop, ...args);
  5780. }
  5781. parseFunctionParams(node, allowModifiers) {
  5782. const typeParameters = this.tsTryParseTypeParameters();
  5783. if (typeParameters) node.typeParameters = typeParameters;
  5784. super.parseFunctionParams(node, allowModifiers);
  5785. }
  5786. parseVarId(decl, kind) {
  5787. super.parseVarId(decl, kind);
  5788. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5789. decl.definite = true;
  5790. }
  5791. const type = this.tsTryParseTypeAnnotation();
  5792. if (type) {
  5793. decl.id.typeAnnotation = type;
  5794. this.resetEndLocation(decl.id);
  5795. }
  5796. }
  5797. parseAsyncArrowFromCallExpression(node, call) {
  5798. if (this.match(types.colon)) {
  5799. node.returnType = this.tsParseTypeAnnotation();
  5800. }
  5801. return super.parseAsyncArrowFromCallExpression(node, call);
  5802. }
  5803. parseMaybeAssign(...args) {
  5804. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  5805. let state;
  5806. let jsx;
  5807. let typeCast;
  5808. if (this.match(types.jsxTagStart)) {
  5809. state = this.state.clone();
  5810. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5811. if (!jsx.error) return jsx.node;
  5812. const {
  5813. context
  5814. } = this.state;
  5815. if (context[context.length - 1] === types$1.j_oTag) {
  5816. context.length -= 2;
  5817. } else if (context[context.length - 1] === types$1.j_expr) {
  5818. context.length -= 1;
  5819. }
  5820. }
  5821. if (!((_jsx = jsx) == null ? void 0 : _jsx.error) && !this.isRelational("<")) {
  5822. return super.parseMaybeAssign(...args);
  5823. }
  5824. let typeParameters;
  5825. state = state || this.state.clone();
  5826. const arrow = this.tryParse(abort => {
  5827. var _typeParameters;
  5828. typeParameters = this.tsParseTypeParameters();
  5829. const expr = super.parseMaybeAssign(...args);
  5830. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5831. abort();
  5832. }
  5833. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  5834. this.resetStartLocationFromNode(expr, typeParameters);
  5835. }
  5836. expr.typeParameters = typeParameters;
  5837. return expr;
  5838. }, state);
  5839. if (!arrow.error && !arrow.aborted) return arrow.node;
  5840. if (!jsx) {
  5841. assert(!this.hasPlugin("jsx"));
  5842. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5843. if (!typeCast.error) return typeCast.node;
  5844. }
  5845. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  5846. this.state = jsx.failState;
  5847. return jsx.node;
  5848. }
  5849. if (arrow.node) {
  5850. this.state = arrow.failState;
  5851. return arrow.node;
  5852. }
  5853. if ((_typeCast = typeCast) == null ? void 0 : _typeCast.node) {
  5854. this.state = typeCast.failState;
  5855. return typeCast.node;
  5856. }
  5857. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  5858. if (arrow.thrown) throw arrow.error;
  5859. if ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.thrown) throw typeCast.error;
  5860. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  5861. }
  5862. parseMaybeUnary(refExpressionErrors) {
  5863. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5864. return this.tsParseTypeAssertion();
  5865. } else {
  5866. return super.parseMaybeUnary(refExpressionErrors);
  5867. }
  5868. }
  5869. parseArrow(node) {
  5870. if (this.match(types.colon)) {
  5871. const result = this.tryParse(abort => {
  5872. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5873. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5874. return returnType;
  5875. });
  5876. if (result.aborted) return;
  5877. if (!result.thrown) {
  5878. if (result.error) this.state = result.failState;
  5879. node.returnType = result.node;
  5880. }
  5881. }
  5882. return super.parseArrow(node);
  5883. }
  5884. parseAssignableListItemTypes(param) {
  5885. if (this.eat(types.question)) {
  5886. if (param.type !== "Identifier" && !this.state.isDeclareContext) {
  5887. this.raise(param.start, TSErrors.PatternIsOptional);
  5888. }
  5889. param.optional = true;
  5890. }
  5891. const type = this.tsTryParseTypeAnnotation();
  5892. if (type) param.typeAnnotation = type;
  5893. this.resetEndLocation(param);
  5894. return param;
  5895. }
  5896. toAssignable(node) {
  5897. switch (node.type) {
  5898. case "TSTypeCastExpression":
  5899. return super.toAssignable(this.typeCastToParameter(node));
  5900. case "TSParameterProperty":
  5901. return super.toAssignable(node);
  5902. case "TSAsExpression":
  5903. case "TSNonNullExpression":
  5904. case "TSTypeAssertion":
  5905. node.expression = this.toAssignable(node.expression);
  5906. return node;
  5907. default:
  5908. return super.toAssignable(node);
  5909. }
  5910. }
  5911. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  5912. switch (expr.type) {
  5913. case "TSTypeCastExpression":
  5914. return;
  5915. case "TSParameterProperty":
  5916. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  5917. return;
  5918. case "TSAsExpression":
  5919. case "TSNonNullExpression":
  5920. case "TSTypeAssertion":
  5921. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  5922. return;
  5923. default:
  5924. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  5925. return;
  5926. }
  5927. }
  5928. parseBindingAtom() {
  5929. switch (this.state.type) {
  5930. case types._this:
  5931. return this.parseIdentifier(true);
  5932. default:
  5933. return super.parseBindingAtom();
  5934. }
  5935. }
  5936. parseMaybeDecoratorArguments(expr) {
  5937. if (this.isRelational("<")) {
  5938. const typeArguments = this.tsParseTypeArguments();
  5939. if (this.match(types.parenL)) {
  5940. const call = super.parseMaybeDecoratorArguments(expr);
  5941. call.typeParameters = typeArguments;
  5942. return call;
  5943. }
  5944. this.unexpected(this.state.start, types.parenL);
  5945. }
  5946. return super.parseMaybeDecoratorArguments(expr);
  5947. }
  5948. isClassMethod() {
  5949. return this.isRelational("<") || super.isClassMethod();
  5950. }
  5951. isClassProperty() {
  5952. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5953. }
  5954. parseMaybeDefault(...args) {
  5955. const node = super.parseMaybeDefault(...args);
  5956. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5957. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  5958. }
  5959. return node;
  5960. }
  5961. getTokenFromCode(code) {
  5962. if (this.state.inType && (code === 62 || code === 60)) {
  5963. return this.finishOp(types.relational, 1);
  5964. } else {
  5965. return super.getTokenFromCode(code);
  5966. }
  5967. }
  5968. reScan_lt_gt() {
  5969. if (this.match(types.relational)) {
  5970. const code = this.input.charCodeAt(this.state.start);
  5971. if (code === 60 || code === 62) {
  5972. this.state.pos -= 1;
  5973. this.readToken_lt_gt(code);
  5974. }
  5975. }
  5976. }
  5977. toAssignableList(exprList) {
  5978. for (let i = 0; i < exprList.length; i++) {
  5979. const expr = exprList[i];
  5980. if (!expr) continue;
  5981. switch (expr.type) {
  5982. case "TSTypeCastExpression":
  5983. exprList[i] = this.typeCastToParameter(expr);
  5984. break;
  5985. case "TSAsExpression":
  5986. case "TSTypeAssertion":
  5987. if (!this.state.maybeInArrowParameters) {
  5988. exprList[i] = this.typeCastToParameter(expr);
  5989. } else {
  5990. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  5991. }
  5992. break;
  5993. }
  5994. }
  5995. return super.toAssignableList(...arguments);
  5996. }
  5997. typeCastToParameter(node) {
  5998. node.expression.typeAnnotation = node.typeAnnotation;
  5999. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  6000. return node.expression;
  6001. }
  6002. shouldParseArrow() {
  6003. return this.match(types.colon) || super.shouldParseArrow();
  6004. }
  6005. shouldParseAsyncArrow() {
  6006. return this.match(types.colon) || super.shouldParseAsyncArrow();
  6007. }
  6008. canHaveLeadingDecorator() {
  6009. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  6010. }
  6011. jsxParseOpeningElementAfterName(node) {
  6012. if (this.isRelational("<")) {
  6013. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  6014. if (typeArguments) node.typeParameters = typeArguments;
  6015. }
  6016. return super.jsxParseOpeningElementAfterName(node);
  6017. }
  6018. getGetterSetterExpectedParamCount(method) {
  6019. const baseCount = super.getGetterSetterExpectedParamCount(method);
  6020. const firstParam = method.params[0];
  6021. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  6022. return hasContextParam ? baseCount + 1 : baseCount;
  6023. }
  6024. parseCatchClauseParam() {
  6025. const param = super.parseCatchClauseParam();
  6026. const type = this.tsTryParseTypeAnnotation();
  6027. if (type) {
  6028. param.typeAnnotation = type;
  6029. this.resetEndLocation(param);
  6030. }
  6031. return param;
  6032. }
  6033. tsInDeclareContext(cb) {
  6034. const oldIsDeclareContext = this.state.isDeclareContext;
  6035. this.state.isDeclareContext = true;
  6036. try {
  6037. return cb();
  6038. } finally {
  6039. this.state.isDeclareContext = oldIsDeclareContext;
  6040. }
  6041. }
  6042. });
  6043. types.placeholder = new TokenType("%%", {
  6044. startsExpr: true
  6045. });
  6046. var placeholders = (superClass => class extends superClass {
  6047. parsePlaceholder(expectedNode) {
  6048. if (this.match(types.placeholder)) {
  6049. const node = this.startNode();
  6050. this.next();
  6051. this.assertNoSpace("Unexpected space in placeholder.");
  6052. node.name = super.parseIdentifier(true);
  6053. this.assertNoSpace("Unexpected space in placeholder.");
  6054. this.expect(types.placeholder);
  6055. return this.finishPlaceholder(node, expectedNode);
  6056. }
  6057. }
  6058. finishPlaceholder(node, expectedNode) {
  6059. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  6060. node.expectedNode = expectedNode;
  6061. return isFinished ? node : this.finishNode(node, "Placeholder");
  6062. }
  6063. getTokenFromCode(code) {
  6064. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  6065. return this.finishOp(types.placeholder, 2);
  6066. }
  6067. return super.getTokenFromCode(...arguments);
  6068. }
  6069. parseExprAtom() {
  6070. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  6071. }
  6072. parseIdentifier() {
  6073. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  6074. }
  6075. checkReservedWord(word) {
  6076. if (word !== undefined) super.checkReservedWord(...arguments);
  6077. }
  6078. parseBindingAtom() {
  6079. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  6080. }
  6081. checkLVal(expr) {
  6082. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  6083. }
  6084. toAssignable(node) {
  6085. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  6086. node.expectedNode = "Pattern";
  6087. return node;
  6088. }
  6089. return super.toAssignable(...arguments);
  6090. }
  6091. verifyBreakContinue(node) {
  6092. if (node.label && node.label.type === "Placeholder") return;
  6093. super.verifyBreakContinue(...arguments);
  6094. }
  6095. parseExpressionStatement(node, expr) {
  6096. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  6097. return super.parseExpressionStatement(...arguments);
  6098. }
  6099. if (this.match(types.colon)) {
  6100. const stmt = node;
  6101. stmt.label = this.finishPlaceholder(expr, "Identifier");
  6102. this.next();
  6103. stmt.body = this.parseStatement("label");
  6104. return this.finishNode(stmt, "LabeledStatement");
  6105. }
  6106. this.semicolon();
  6107. node.name = expr.name;
  6108. return this.finishPlaceholder(node, "Statement");
  6109. }
  6110. parseBlock() {
  6111. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  6112. }
  6113. parseFunctionId() {
  6114. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  6115. }
  6116. parseClass(node, isStatement, optionalId) {
  6117. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  6118. this.next();
  6119. this.takeDecorators(node);
  6120. const oldStrict = this.state.strict;
  6121. const placeholder = this.parsePlaceholder("Identifier");
  6122. if (placeholder) {
  6123. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  6124. node.id = placeholder;
  6125. } else if (optionalId || !isStatement) {
  6126. node.id = null;
  6127. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  6128. return this.finishNode(node, type);
  6129. } else {
  6130. this.unexpected(null, "A class name is required");
  6131. }
  6132. } else {
  6133. this.parseClassId(node, isStatement, optionalId);
  6134. }
  6135. this.parseClassSuper(node);
  6136. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  6137. return this.finishNode(node, type);
  6138. }
  6139. parseExport(node) {
  6140. const placeholder = this.parsePlaceholder("Identifier");
  6141. if (!placeholder) return super.parseExport(...arguments);
  6142. if (!this.isContextual("from") && !this.match(types.comma)) {
  6143. node.specifiers = [];
  6144. node.source = null;
  6145. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  6146. return this.finishNode(node, "ExportNamedDeclaration");
  6147. }
  6148. this.expectPlugin("exportDefaultFrom");
  6149. const specifier = this.startNode();
  6150. specifier.exported = placeholder;
  6151. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  6152. return super.parseExport(node);
  6153. }
  6154. isExportDefaultSpecifier() {
  6155. if (this.match(types._default)) {
  6156. const next = this.nextTokenStart();
  6157. if (this.isUnparsedContextual(next, "from")) {
  6158. if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
  6159. return true;
  6160. }
  6161. }
  6162. }
  6163. return super.isExportDefaultSpecifier();
  6164. }
  6165. maybeParseExportDefaultSpecifier(node) {
  6166. if (node.specifiers && node.specifiers.length > 0) {
  6167. return true;
  6168. }
  6169. return super.maybeParseExportDefaultSpecifier(...arguments);
  6170. }
  6171. checkExport(node) {
  6172. const {
  6173. specifiers
  6174. } = node;
  6175. if (specifiers == null ? void 0 : specifiers.length) {
  6176. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  6177. }
  6178. super.checkExport(node);
  6179. node.specifiers = specifiers;
  6180. }
  6181. parseImport(node) {
  6182. const placeholder = this.parsePlaceholder("Identifier");
  6183. if (!placeholder) return super.parseImport(...arguments);
  6184. node.specifiers = [];
  6185. if (!this.isContextual("from") && !this.match(types.comma)) {
  6186. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  6187. this.semicolon();
  6188. return this.finishNode(node, "ImportDeclaration");
  6189. }
  6190. const specifier = this.startNodeAtNode(placeholder);
  6191. specifier.local = placeholder;
  6192. this.finishNode(specifier, "ImportDefaultSpecifier");
  6193. node.specifiers.push(specifier);
  6194. if (this.eat(types.comma)) {
  6195. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  6196. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  6197. }
  6198. this.expectContextual("from");
  6199. node.source = this.parseImportSource();
  6200. this.semicolon();
  6201. return this.finishNode(node, "ImportDeclaration");
  6202. }
  6203. parseImportSource() {
  6204. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  6205. }
  6206. });
  6207. var v8intrinsic = (superClass => class extends superClass {
  6208. parseV8Intrinsic() {
  6209. if (this.match(types.modulo)) {
  6210. const v8IntrinsicStart = this.state.start;
  6211. const node = this.startNode();
  6212. this.eat(types.modulo);
  6213. if (this.match(types.name)) {
  6214. const name = this.parseIdentifierName(this.state.start);
  6215. const identifier = this.createIdentifier(node, name);
  6216. identifier.type = "V8IntrinsicIdentifier";
  6217. if (this.match(types.parenL)) {
  6218. return identifier;
  6219. }
  6220. }
  6221. this.unexpected(v8IntrinsicStart);
  6222. }
  6223. }
  6224. parseExprAtom() {
  6225. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  6226. }
  6227. });
  6228. function hasPlugin(plugins, name) {
  6229. return plugins.some(plugin => {
  6230. if (Array.isArray(plugin)) {
  6231. return plugin[0] === name;
  6232. } else {
  6233. return plugin === name;
  6234. }
  6235. });
  6236. }
  6237. function getPluginOption(plugins, name, option) {
  6238. const plugin = plugins.find(plugin => {
  6239. if (Array.isArray(plugin)) {
  6240. return plugin[0] === name;
  6241. } else {
  6242. return plugin === name;
  6243. }
  6244. });
  6245. if (plugin && Array.isArray(plugin)) {
  6246. return plugin[1][option];
  6247. }
  6248. return null;
  6249. }
  6250. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6251. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6252. function validatePlugins(plugins) {
  6253. if (hasPlugin(plugins, "decorators")) {
  6254. if (hasPlugin(plugins, "decorators-legacy")) {
  6255. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6256. }
  6257. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6258. if (decoratorsBeforeExport == null) {
  6259. 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'.");
  6260. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6261. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6262. }
  6263. }
  6264. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6265. throw new Error("Cannot combine flow and typescript plugins.");
  6266. }
  6267. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6268. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6269. }
  6270. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6271. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6272. }
  6273. if (hasPlugin(plugins, "moduleAttributes")) {
  6274. if (hasPlugin(plugins, "importAssertions")) {
  6275. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  6276. }
  6277. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  6278. if (moduleAttributesVerionPluginOption !== "may-2020") {
  6279. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  6280. }
  6281. }
  6282. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6283. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6284. }
  6285. }
  6286. const mixinPlugins = {
  6287. estree,
  6288. jsx,
  6289. flow,
  6290. typescript,
  6291. v8intrinsic,
  6292. placeholders
  6293. };
  6294. const mixinPluginNames = Object.keys(mixinPlugins);
  6295. const defaultOptions = {
  6296. sourceType: "script",
  6297. sourceFilename: undefined,
  6298. startLine: 1,
  6299. allowAwaitOutsideFunction: false,
  6300. allowReturnOutsideFunction: false,
  6301. allowImportExportEverywhere: false,
  6302. allowSuperOutsideMethod: false,
  6303. allowUndeclaredExports: false,
  6304. plugins: [],
  6305. strictMode: null,
  6306. ranges: false,
  6307. tokens: false,
  6308. createParenthesizedExpressions: false,
  6309. errorRecovery: false
  6310. };
  6311. function getOptions(opts) {
  6312. const options = {};
  6313. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  6314. const key = _Object$keys[_i];
  6315. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6316. }
  6317. return options;
  6318. }
  6319. class State {
  6320. constructor() {
  6321. this.strict = void 0;
  6322. this.curLine = void 0;
  6323. this.startLoc = void 0;
  6324. this.endLoc = void 0;
  6325. this.errors = [];
  6326. this.potentialArrowAt = -1;
  6327. this.noArrowAt = [];
  6328. this.noArrowParamsConversionAt = [];
  6329. this.inParameters = false;
  6330. this.maybeInArrowParameters = false;
  6331. this.maybeInAsyncArrowHead = false;
  6332. this.inPipeline = false;
  6333. this.inType = false;
  6334. this.noAnonFunctionType = false;
  6335. this.inPropertyName = false;
  6336. this.hasFlowComment = false;
  6337. this.isIterator = false;
  6338. this.isDeclareContext = false;
  6339. this.topicContext = {
  6340. maxNumOfResolvableTopics: 0,
  6341. maxTopicIndex: null
  6342. };
  6343. this.soloAwait = false;
  6344. this.inFSharpPipelineDirectBody = false;
  6345. this.labels = [];
  6346. this.decoratorStack = [[]];
  6347. this.yieldPos = -1;
  6348. this.awaitPos = -1;
  6349. this.comments = [];
  6350. this.trailingComments = [];
  6351. this.leadingComments = [];
  6352. this.commentStack = [];
  6353. this.commentPreviousNode = null;
  6354. this.pos = 0;
  6355. this.lineStart = 0;
  6356. this.type = types.eof;
  6357. this.value = null;
  6358. this.start = 0;
  6359. this.end = 0;
  6360. this.lastTokEndLoc = null;
  6361. this.lastTokStartLoc = null;
  6362. this.lastTokStart = 0;
  6363. this.lastTokEnd = 0;
  6364. this.context = [types$1.braceStatement];
  6365. this.exprAllowed = true;
  6366. this.containsEsc = false;
  6367. this.octalPositions = [];
  6368. this.exportedIdentifiers = [];
  6369. this.tokensLength = 0;
  6370. }
  6371. init(options) {
  6372. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6373. this.curLine = options.startLine;
  6374. this.startLoc = this.endLoc = this.curPosition();
  6375. }
  6376. curPosition() {
  6377. return new Position(this.curLine, this.pos - this.lineStart);
  6378. }
  6379. clone(skipArrays) {
  6380. const state = new State();
  6381. const keys = Object.keys(this);
  6382. for (let i = 0, length = keys.length; i < length; i++) {
  6383. const key = keys[i];
  6384. let val = this[key];
  6385. if (!skipArrays && Array.isArray(val)) {
  6386. val = val.slice();
  6387. }
  6388. state[key] = val;
  6389. }
  6390. return state;
  6391. }
  6392. }
  6393. var _isDigit = function isDigit(code) {
  6394. return code >= 48 && code <= 57;
  6395. };
  6396. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6397. const forbiddenNumericSeparatorSiblings = {
  6398. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6399. hex: [46, 88, 95, 120]
  6400. };
  6401. const allowedNumericSeparatorSiblings = {};
  6402. allowedNumericSeparatorSiblings.bin = [48, 49];
  6403. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6404. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6405. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6406. class Token {
  6407. constructor(state) {
  6408. this.type = void 0;
  6409. this.value = void 0;
  6410. this.start = void 0;
  6411. this.end = void 0;
  6412. this.loc = void 0;
  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 (!this.match(types.num) && !this.match(types.string)) return;
  6484. this.state.pos = this.state.start;
  6485. while (this.state.pos < this.state.lineStart) {
  6486. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  6487. --this.state.curLine;
  6488. }
  6489. this.nextToken();
  6490. }
  6491. curContext() {
  6492. return this.state.context[this.state.context.length - 1];
  6493. }
  6494. nextToken() {
  6495. const curContext = this.curContext();
  6496. if (!(curContext == null ? void 0 : curContext.preserveSpace)) this.skipSpace();
  6497. this.state.octalPositions = [];
  6498. this.state.start = this.state.pos;
  6499. this.state.startLoc = this.state.curPosition();
  6500. if (this.state.pos >= this.length) {
  6501. this.finishToken(types.eof);
  6502. return;
  6503. }
  6504. const override = curContext == null ? void 0 : curContext.override;
  6505. if (override) {
  6506. override(this);
  6507. } else {
  6508. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6509. }
  6510. }
  6511. pushComment(block, text, start, end, startLoc, endLoc) {
  6512. const comment = {
  6513. type: block ? "CommentBlock" : "CommentLine",
  6514. value: text,
  6515. start: start,
  6516. end: end,
  6517. loc: new SourceLocation(startLoc, endLoc)
  6518. };
  6519. if (this.options.tokens) this.pushToken(comment);
  6520. this.state.comments.push(comment);
  6521. this.addComment(comment);
  6522. }
  6523. skipBlockComment() {
  6524. const startLoc = this.state.curPosition();
  6525. const start = this.state.pos;
  6526. const end = this.input.indexOf("*/", this.state.pos + 2);
  6527. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  6528. this.state.pos = end + 2;
  6529. lineBreakG.lastIndex = start;
  6530. let match;
  6531. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6532. ++this.state.curLine;
  6533. this.state.lineStart = match.index + match[0].length;
  6534. }
  6535. if (this.isLookahead) return;
  6536. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6537. }
  6538. skipLineComment(startSkip) {
  6539. const start = this.state.pos;
  6540. const startLoc = this.state.curPosition();
  6541. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6542. if (this.state.pos < this.length) {
  6543. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6544. ch = this.input.charCodeAt(this.state.pos);
  6545. }
  6546. }
  6547. if (this.isLookahead) return;
  6548. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6549. }
  6550. skipSpace() {
  6551. loop: while (this.state.pos < this.length) {
  6552. const ch = this.input.charCodeAt(this.state.pos);
  6553. switch (ch) {
  6554. case 32:
  6555. case 160:
  6556. case 9:
  6557. ++this.state.pos;
  6558. break;
  6559. case 13:
  6560. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6561. ++this.state.pos;
  6562. }
  6563. case 10:
  6564. case 8232:
  6565. case 8233:
  6566. ++this.state.pos;
  6567. ++this.state.curLine;
  6568. this.state.lineStart = this.state.pos;
  6569. break;
  6570. case 47:
  6571. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6572. case 42:
  6573. this.skipBlockComment();
  6574. break;
  6575. case 47:
  6576. this.skipLineComment(2);
  6577. break;
  6578. default:
  6579. break loop;
  6580. }
  6581. break;
  6582. default:
  6583. if (isWhitespace(ch)) {
  6584. ++this.state.pos;
  6585. } else {
  6586. break loop;
  6587. }
  6588. }
  6589. }
  6590. }
  6591. finishToken(type, val) {
  6592. this.state.end = this.state.pos;
  6593. this.state.endLoc = this.state.curPosition();
  6594. const prevType = this.state.type;
  6595. this.state.type = type;
  6596. this.state.value = val;
  6597. if (!this.isLookahead) this.updateContext(prevType);
  6598. }
  6599. readToken_numberSign() {
  6600. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6601. return;
  6602. }
  6603. const nextPos = this.state.pos + 1;
  6604. const next = this.input.charCodeAt(nextPos);
  6605. if (next >= 48 && next <= 57) {
  6606. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  6607. }
  6608. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  6609. this.expectPlugin("recordAndTuple");
  6610. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6611. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  6612. }
  6613. if (next === 123) {
  6614. this.finishToken(types.braceHashL);
  6615. } else {
  6616. this.finishToken(types.bracketHashL);
  6617. }
  6618. this.state.pos += 2;
  6619. } else {
  6620. this.finishOp(types.hash, 1);
  6621. }
  6622. }
  6623. readToken_dot() {
  6624. const next = this.input.charCodeAt(this.state.pos + 1);
  6625. if (next >= 48 && next <= 57) {
  6626. this.readNumber(true);
  6627. return;
  6628. }
  6629. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6630. this.state.pos += 3;
  6631. this.finishToken(types.ellipsis);
  6632. } else {
  6633. ++this.state.pos;
  6634. this.finishToken(types.dot);
  6635. }
  6636. }
  6637. readToken_slash() {
  6638. if (this.state.exprAllowed && !this.state.inType) {
  6639. ++this.state.pos;
  6640. this.readRegexp();
  6641. return;
  6642. }
  6643. const next = this.input.charCodeAt(this.state.pos + 1);
  6644. if (next === 61) {
  6645. this.finishOp(types.assign, 2);
  6646. } else {
  6647. this.finishOp(types.slash, 1);
  6648. }
  6649. }
  6650. readToken_interpreter() {
  6651. if (this.state.pos !== 0 || this.length < 2) return false;
  6652. let ch = this.input.charCodeAt(this.state.pos + 1);
  6653. if (ch !== 33) return false;
  6654. const start = this.state.pos;
  6655. this.state.pos += 1;
  6656. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6657. ch = this.input.charCodeAt(this.state.pos);
  6658. }
  6659. const value = this.input.slice(start + 2, this.state.pos);
  6660. this.finishToken(types.interpreterDirective, value);
  6661. return true;
  6662. }
  6663. readToken_mult_modulo(code) {
  6664. let type = code === 42 ? types.star : types.modulo;
  6665. let width = 1;
  6666. let next = this.input.charCodeAt(this.state.pos + 1);
  6667. const exprAllowed = this.state.exprAllowed;
  6668. if (code === 42 && next === 42) {
  6669. width++;
  6670. next = this.input.charCodeAt(this.state.pos + 2);
  6671. type = types.exponent;
  6672. }
  6673. if (next === 61 && !exprAllowed) {
  6674. width++;
  6675. type = types.assign;
  6676. }
  6677. this.finishOp(type, width);
  6678. }
  6679. readToken_pipe_amp(code) {
  6680. const next = this.input.charCodeAt(this.state.pos + 1);
  6681. if (next === code) {
  6682. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6683. this.finishOp(types.assign, 3);
  6684. } else {
  6685. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6686. }
  6687. return;
  6688. }
  6689. if (code === 124) {
  6690. if (next === 62) {
  6691. this.finishOp(types.pipeline, 2);
  6692. return;
  6693. }
  6694. if (this.hasPlugin("recordAndTuple") && next === 125) {
  6695. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6696. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  6697. }
  6698. this.finishOp(types.braceBarR, 2);
  6699. return;
  6700. }
  6701. if (this.hasPlugin("recordAndTuple") && next === 93) {
  6702. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6703. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  6704. }
  6705. this.finishOp(types.bracketBarR, 2);
  6706. return;
  6707. }
  6708. }
  6709. if (next === 61) {
  6710. this.finishOp(types.assign, 2);
  6711. return;
  6712. }
  6713. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6714. }
  6715. readToken_caret() {
  6716. const next = this.input.charCodeAt(this.state.pos + 1);
  6717. if (next === 61) {
  6718. this.finishOp(types.assign, 2);
  6719. } else {
  6720. this.finishOp(types.bitwiseXOR, 1);
  6721. }
  6722. }
  6723. readToken_plus_min(code) {
  6724. const next = this.input.charCodeAt(this.state.pos + 1);
  6725. if (next === code) {
  6726. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
  6727. this.skipLineComment(3);
  6728. this.skipSpace();
  6729. this.nextToken();
  6730. return;
  6731. }
  6732. this.finishOp(types.incDec, 2);
  6733. return;
  6734. }
  6735. if (next === 61) {
  6736. this.finishOp(types.assign, 2);
  6737. } else {
  6738. this.finishOp(types.plusMin, 1);
  6739. }
  6740. }
  6741. readToken_lt_gt(code) {
  6742. const next = this.input.charCodeAt(this.state.pos + 1);
  6743. let size = 1;
  6744. if (next === code) {
  6745. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6746. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6747. this.finishOp(types.assign, size + 1);
  6748. return;
  6749. }
  6750. this.finishOp(types.bitShift, size);
  6751. return;
  6752. }
  6753. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6754. this.skipLineComment(4);
  6755. this.skipSpace();
  6756. this.nextToken();
  6757. return;
  6758. }
  6759. if (next === 61) {
  6760. size = 2;
  6761. }
  6762. this.finishOp(types.relational, size);
  6763. }
  6764. readToken_eq_excl(code) {
  6765. const next = this.input.charCodeAt(this.state.pos + 1);
  6766. if (next === 61) {
  6767. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6768. return;
  6769. }
  6770. if (code === 61 && next === 62) {
  6771. this.state.pos += 2;
  6772. this.finishToken(types.arrow);
  6773. return;
  6774. }
  6775. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6776. }
  6777. readToken_question() {
  6778. const next = this.input.charCodeAt(this.state.pos + 1);
  6779. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6780. if (next === 63) {
  6781. if (next2 === 61) {
  6782. this.finishOp(types.assign, 3);
  6783. } else {
  6784. this.finishOp(types.nullishCoalescing, 2);
  6785. }
  6786. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6787. this.state.pos += 2;
  6788. this.finishToken(types.questionDot);
  6789. } else {
  6790. ++this.state.pos;
  6791. this.finishToken(types.question);
  6792. }
  6793. }
  6794. getTokenFromCode(code) {
  6795. switch (code) {
  6796. case 46:
  6797. this.readToken_dot();
  6798. return;
  6799. case 40:
  6800. ++this.state.pos;
  6801. this.finishToken(types.parenL);
  6802. return;
  6803. case 41:
  6804. ++this.state.pos;
  6805. this.finishToken(types.parenR);
  6806. return;
  6807. case 59:
  6808. ++this.state.pos;
  6809. this.finishToken(types.semi);
  6810. return;
  6811. case 44:
  6812. ++this.state.pos;
  6813. this.finishToken(types.comma);
  6814. return;
  6815. case 91:
  6816. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6817. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6818. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  6819. }
  6820. this.finishToken(types.bracketBarL);
  6821. this.state.pos += 2;
  6822. } else {
  6823. ++this.state.pos;
  6824. this.finishToken(types.bracketL);
  6825. }
  6826. return;
  6827. case 93:
  6828. ++this.state.pos;
  6829. this.finishToken(types.bracketR);
  6830. return;
  6831. case 123:
  6832. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6833. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6834. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  6835. }
  6836. this.finishToken(types.braceBarL);
  6837. this.state.pos += 2;
  6838. } else {
  6839. ++this.state.pos;
  6840. this.finishToken(types.braceL);
  6841. }
  6842. return;
  6843. case 125:
  6844. ++this.state.pos;
  6845. this.finishToken(types.braceR);
  6846. return;
  6847. case 58:
  6848. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6849. this.finishOp(types.doubleColon, 2);
  6850. } else {
  6851. ++this.state.pos;
  6852. this.finishToken(types.colon);
  6853. }
  6854. return;
  6855. case 63:
  6856. this.readToken_question();
  6857. return;
  6858. case 96:
  6859. ++this.state.pos;
  6860. this.finishToken(types.backQuote);
  6861. return;
  6862. case 48:
  6863. {
  6864. const next = this.input.charCodeAt(this.state.pos + 1);
  6865. if (next === 120 || next === 88) {
  6866. this.readRadixNumber(16);
  6867. return;
  6868. }
  6869. if (next === 111 || next === 79) {
  6870. this.readRadixNumber(8);
  6871. return;
  6872. }
  6873. if (next === 98 || next === 66) {
  6874. this.readRadixNumber(2);
  6875. return;
  6876. }
  6877. }
  6878. case 49:
  6879. case 50:
  6880. case 51:
  6881. case 52:
  6882. case 53:
  6883. case 54:
  6884. case 55:
  6885. case 56:
  6886. case 57:
  6887. this.readNumber(false);
  6888. return;
  6889. case 34:
  6890. case 39:
  6891. this.readString(code);
  6892. return;
  6893. case 47:
  6894. this.readToken_slash();
  6895. return;
  6896. case 37:
  6897. case 42:
  6898. this.readToken_mult_modulo(code);
  6899. return;
  6900. case 124:
  6901. case 38:
  6902. this.readToken_pipe_amp(code);
  6903. return;
  6904. case 94:
  6905. this.readToken_caret();
  6906. return;
  6907. case 43:
  6908. case 45:
  6909. this.readToken_plus_min(code);
  6910. return;
  6911. case 60:
  6912. case 62:
  6913. this.readToken_lt_gt(code);
  6914. return;
  6915. case 61:
  6916. case 33:
  6917. this.readToken_eq_excl(code);
  6918. return;
  6919. case 126:
  6920. this.finishOp(types.tilde, 1);
  6921. return;
  6922. case 64:
  6923. ++this.state.pos;
  6924. this.finishToken(types.at);
  6925. return;
  6926. case 35:
  6927. this.readToken_numberSign();
  6928. return;
  6929. case 92:
  6930. this.readWord();
  6931. return;
  6932. default:
  6933. if (isIdentifierStart(code)) {
  6934. this.readWord();
  6935. return;
  6936. }
  6937. }
  6938. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  6939. }
  6940. finishOp(type, size) {
  6941. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6942. this.state.pos += size;
  6943. this.finishToken(type, str);
  6944. }
  6945. readRegexp() {
  6946. const start = this.state.pos;
  6947. let escaped, inClass;
  6948. for (;;) {
  6949. if (this.state.pos >= this.length) {
  6950. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  6951. }
  6952. const ch = this.input.charAt(this.state.pos);
  6953. if (lineBreak.test(ch)) {
  6954. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  6955. }
  6956. if (escaped) {
  6957. escaped = false;
  6958. } else {
  6959. if (ch === "[") {
  6960. inClass = true;
  6961. } else if (ch === "]" && inClass) {
  6962. inClass = false;
  6963. } else if (ch === "/" && !inClass) {
  6964. break;
  6965. }
  6966. escaped = ch === "\\";
  6967. }
  6968. ++this.state.pos;
  6969. }
  6970. const content = this.input.slice(start, this.state.pos);
  6971. ++this.state.pos;
  6972. let mods = "";
  6973. while (this.state.pos < this.length) {
  6974. const char = this.input[this.state.pos];
  6975. const charCode = this.input.codePointAt(this.state.pos);
  6976. if (VALID_REGEX_FLAGS.has(char)) {
  6977. if (mods.indexOf(char) > -1) {
  6978. this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
  6979. }
  6980. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6981. this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
  6982. } else {
  6983. break;
  6984. }
  6985. ++this.state.pos;
  6986. mods += char;
  6987. }
  6988. this.finishToken(types.regexp, {
  6989. pattern: content,
  6990. flags: mods
  6991. });
  6992. }
  6993. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6994. const start = this.state.pos;
  6995. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6996. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6997. let invalid = false;
  6998. let total = 0;
  6999. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  7000. const code = this.input.charCodeAt(this.state.pos);
  7001. let val;
  7002. if (code === 95) {
  7003. const prev = this.input.charCodeAt(this.state.pos - 1);
  7004. const next = this.input.charCodeAt(this.state.pos + 1);
  7005. if (allowedSiblings.indexOf(next) === -1) {
  7006. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7007. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  7008. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7009. }
  7010. if (!allowNumSeparator) {
  7011. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  7012. }
  7013. ++this.state.pos;
  7014. continue;
  7015. }
  7016. if (code >= 97) {
  7017. val = code - 97 + 10;
  7018. } else if (code >= 65) {
  7019. val = code - 65 + 10;
  7020. } else if (_isDigit(code)) {
  7021. val = code - 48;
  7022. } else {
  7023. val = Infinity;
  7024. }
  7025. if (val >= radix) {
  7026. if (this.options.errorRecovery && val <= 9) {
  7027. val = 0;
  7028. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  7029. } else if (forceLen) {
  7030. val = 0;
  7031. invalid = true;
  7032. } else {
  7033. break;
  7034. }
  7035. }
  7036. ++this.state.pos;
  7037. total = total * radix + val;
  7038. }
  7039. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  7040. return null;
  7041. }
  7042. return total;
  7043. }
  7044. readRadixNumber(radix) {
  7045. const start = this.state.pos;
  7046. let isBigInt = false;
  7047. this.state.pos += 2;
  7048. const val = this.readInt(radix);
  7049. if (val == null) {
  7050. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  7051. }
  7052. const next = this.input.charCodeAt(this.state.pos);
  7053. if (next === 110) {
  7054. ++this.state.pos;
  7055. isBigInt = true;
  7056. } else if (next === 109) {
  7057. throw this.raise(start, ErrorMessages.InvalidDecimal);
  7058. }
  7059. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7060. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7061. }
  7062. if (isBigInt) {
  7063. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  7064. this.finishToken(types.bigint, str);
  7065. return;
  7066. }
  7067. this.finishToken(types.num, val);
  7068. }
  7069. readNumber(startsWithDot) {
  7070. const start = this.state.pos;
  7071. let isFloat = false;
  7072. let isBigInt = false;
  7073. let isDecimal = false;
  7074. let hasExponent = false;
  7075. let isOctal = false;
  7076. if (!startsWithDot && this.readInt(10) === null) {
  7077. this.raise(start, ErrorMessages.InvalidNumber);
  7078. }
  7079. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  7080. if (hasLeadingZero) {
  7081. const integer = this.input.slice(start, this.state.pos);
  7082. if (this.state.strict) {
  7083. this.raise(start, ErrorMessages.StrictOctalLiteral);
  7084. } else {
  7085. const underscorePos = integer.indexOf("_");
  7086. if (underscorePos > 0) {
  7087. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  7088. }
  7089. }
  7090. isOctal = hasLeadingZero && !/[89]/.test(integer);
  7091. }
  7092. let next = this.input.charCodeAt(this.state.pos);
  7093. if (next === 46 && !isOctal) {
  7094. ++this.state.pos;
  7095. this.readInt(10);
  7096. isFloat = true;
  7097. next = this.input.charCodeAt(this.state.pos);
  7098. }
  7099. if ((next === 69 || next === 101) && !isOctal) {
  7100. next = this.input.charCodeAt(++this.state.pos);
  7101. if (next === 43 || next === 45) {
  7102. ++this.state.pos;
  7103. }
  7104. if (this.readInt(10) === null) {
  7105. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  7106. }
  7107. isFloat = true;
  7108. hasExponent = true;
  7109. next = this.input.charCodeAt(this.state.pos);
  7110. }
  7111. if (next === 110) {
  7112. if (isFloat || hasLeadingZero) {
  7113. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  7114. }
  7115. ++this.state.pos;
  7116. isBigInt = true;
  7117. }
  7118. if (next === 109) {
  7119. this.expectPlugin("decimal", this.state.pos);
  7120. if (hasExponent || hasLeadingZero) {
  7121. this.raise(start, ErrorMessages.InvalidDecimal);
  7122. }
  7123. ++this.state.pos;
  7124. isDecimal = true;
  7125. }
  7126. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7127. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7128. }
  7129. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  7130. if (isBigInt) {
  7131. this.finishToken(types.bigint, str);
  7132. return;
  7133. }
  7134. if (isDecimal) {
  7135. this.finishToken(types.decimal, str);
  7136. return;
  7137. }
  7138. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  7139. this.finishToken(types.num, val);
  7140. }
  7141. readCodePoint(throwOnInvalid) {
  7142. const ch = this.input.charCodeAt(this.state.pos);
  7143. let code;
  7144. if (ch === 123) {
  7145. const codePos = ++this.state.pos;
  7146. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  7147. ++this.state.pos;
  7148. if (code !== null && code > 0x10ffff) {
  7149. if (throwOnInvalid) {
  7150. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  7151. } else {
  7152. return null;
  7153. }
  7154. }
  7155. } else {
  7156. code = this.readHexChar(4, false, throwOnInvalid);
  7157. }
  7158. return code;
  7159. }
  7160. readString(quote) {
  7161. let out = "",
  7162. chunkStart = ++this.state.pos;
  7163. for (;;) {
  7164. if (this.state.pos >= this.length) {
  7165. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7166. }
  7167. const ch = this.input.charCodeAt(this.state.pos);
  7168. if (ch === quote) break;
  7169. if (ch === 92) {
  7170. out += this.input.slice(chunkStart, this.state.pos);
  7171. out += this.readEscapedChar(false);
  7172. chunkStart = this.state.pos;
  7173. } else if (ch === 8232 || ch === 8233) {
  7174. ++this.state.pos;
  7175. ++this.state.curLine;
  7176. this.state.lineStart = this.state.pos;
  7177. } else if (isNewLine(ch)) {
  7178. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7179. } else {
  7180. ++this.state.pos;
  7181. }
  7182. }
  7183. out += this.input.slice(chunkStart, this.state.pos++);
  7184. this.finishToken(types.string, out);
  7185. }
  7186. readTmplToken() {
  7187. let out = "",
  7188. chunkStart = this.state.pos,
  7189. containsInvalid = false;
  7190. for (;;) {
  7191. if (this.state.pos >= this.length) {
  7192. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  7193. }
  7194. const ch = this.input.charCodeAt(this.state.pos);
  7195. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  7196. if (this.state.pos === this.state.start && this.match(types.template)) {
  7197. if (ch === 36) {
  7198. this.state.pos += 2;
  7199. this.finishToken(types.dollarBraceL);
  7200. return;
  7201. } else {
  7202. ++this.state.pos;
  7203. this.finishToken(types.backQuote);
  7204. return;
  7205. }
  7206. }
  7207. out += this.input.slice(chunkStart, this.state.pos);
  7208. this.finishToken(types.template, containsInvalid ? null : out);
  7209. return;
  7210. }
  7211. if (ch === 92) {
  7212. out += this.input.slice(chunkStart, this.state.pos);
  7213. const escaped = this.readEscapedChar(true);
  7214. if (escaped === null) {
  7215. containsInvalid = true;
  7216. } else {
  7217. out += escaped;
  7218. }
  7219. chunkStart = this.state.pos;
  7220. } else if (isNewLine(ch)) {
  7221. out += this.input.slice(chunkStart, this.state.pos);
  7222. ++this.state.pos;
  7223. switch (ch) {
  7224. case 13:
  7225. if (this.input.charCodeAt(this.state.pos) === 10) {
  7226. ++this.state.pos;
  7227. }
  7228. case 10:
  7229. out += "\n";
  7230. break;
  7231. default:
  7232. out += String.fromCharCode(ch);
  7233. break;
  7234. }
  7235. ++this.state.curLine;
  7236. this.state.lineStart = this.state.pos;
  7237. chunkStart = this.state.pos;
  7238. } else {
  7239. ++this.state.pos;
  7240. }
  7241. }
  7242. }
  7243. readEscapedChar(inTemplate) {
  7244. const throwOnInvalid = !inTemplate;
  7245. const ch = this.input.charCodeAt(++this.state.pos);
  7246. ++this.state.pos;
  7247. switch (ch) {
  7248. case 110:
  7249. return "\n";
  7250. case 114:
  7251. return "\r";
  7252. case 120:
  7253. {
  7254. const code = this.readHexChar(2, false, throwOnInvalid);
  7255. return code === null ? null : String.fromCharCode(code);
  7256. }
  7257. case 117:
  7258. {
  7259. const code = this.readCodePoint(throwOnInvalid);
  7260. return code === null ? null : String.fromCodePoint(code);
  7261. }
  7262. case 116:
  7263. return "\t";
  7264. case 98:
  7265. return "\b";
  7266. case 118:
  7267. return "\u000b";
  7268. case 102:
  7269. return "\f";
  7270. case 13:
  7271. if (this.input.charCodeAt(this.state.pos) === 10) {
  7272. ++this.state.pos;
  7273. }
  7274. case 10:
  7275. this.state.lineStart = this.state.pos;
  7276. ++this.state.curLine;
  7277. case 8232:
  7278. case 8233:
  7279. return "";
  7280. case 56:
  7281. case 57:
  7282. if (inTemplate) {
  7283. return null;
  7284. } else if (this.state.strict) {
  7285. this.raise(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  7286. }
  7287. default:
  7288. if (ch >= 48 && ch <= 55) {
  7289. const codePos = this.state.pos - 1;
  7290. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  7291. let octalStr = match[0];
  7292. let octal = parseInt(octalStr, 8);
  7293. if (octal > 255) {
  7294. octalStr = octalStr.slice(0, -1);
  7295. octal = parseInt(octalStr, 8);
  7296. }
  7297. this.state.pos += octalStr.length - 1;
  7298. const next = this.input.charCodeAt(this.state.pos);
  7299. if (octalStr !== "0" || next === 56 || next === 57) {
  7300. if (inTemplate) {
  7301. return null;
  7302. } else if (this.state.strict) {
  7303. this.raise(codePos, ErrorMessages.StrictNumericEscape);
  7304. } else {
  7305. this.state.octalPositions.push(codePos);
  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. checkYieldAwaitInDefaultParams() {
  7489. if (this.state.yieldPos !== -1 && (this.state.awaitPos === -1 || this.state.yieldPos < this.state.awaitPos)) {
  7490. this.raise(this.state.yieldPos, ErrorMessages.YieldBindingIdentifier);
  7491. }
  7492. if (this.state.awaitPos !== -1) {
  7493. this.raise(this.state.awaitPos, ErrorMessages.AwaitBindingIdentifier);
  7494. }
  7495. }
  7496. tryParse(fn, oldState = this.state.clone()) {
  7497. const abortSignal = {
  7498. node: null
  7499. };
  7500. try {
  7501. const node = fn((node = null) => {
  7502. abortSignal.node = node;
  7503. throw abortSignal;
  7504. });
  7505. if (this.state.errors.length > oldState.errors.length) {
  7506. const failState = this.state;
  7507. this.state = oldState;
  7508. return {
  7509. node,
  7510. error: failState.errors[oldState.errors.length],
  7511. thrown: false,
  7512. aborted: false,
  7513. failState
  7514. };
  7515. }
  7516. return {
  7517. node,
  7518. error: null,
  7519. thrown: false,
  7520. aborted: false,
  7521. failState: null
  7522. };
  7523. } catch (error) {
  7524. const failState = this.state;
  7525. this.state = oldState;
  7526. if (error instanceof SyntaxError) {
  7527. return {
  7528. node: null,
  7529. error,
  7530. thrown: true,
  7531. aborted: false,
  7532. failState
  7533. };
  7534. }
  7535. if (error === abortSignal) {
  7536. return {
  7537. node: abortSignal.node,
  7538. error: null,
  7539. thrown: false,
  7540. aborted: true,
  7541. failState
  7542. };
  7543. }
  7544. throw error;
  7545. }
  7546. }
  7547. checkExpressionErrors(refExpressionErrors, andThrow) {
  7548. if (!refExpressionErrors) return false;
  7549. const {
  7550. shorthandAssign,
  7551. doubleProto
  7552. } = refExpressionErrors;
  7553. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  7554. if (shorthandAssign >= 0) {
  7555. this.unexpected(shorthandAssign);
  7556. }
  7557. if (doubleProto >= 0) {
  7558. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  7559. }
  7560. }
  7561. isLiteralPropertyName() {
  7562. 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);
  7563. }
  7564. }
  7565. class ExpressionErrors {
  7566. constructor() {
  7567. this.shorthandAssign = -1;
  7568. this.doubleProto = -1;
  7569. }
  7570. }
  7571. class Node {
  7572. constructor(parser, pos, loc) {
  7573. this.type = void 0;
  7574. this.start = void 0;
  7575. this.end = void 0;
  7576. this.loc = void 0;
  7577. this.range = void 0;
  7578. this.leadingComments = void 0;
  7579. this.trailingComments = void 0;
  7580. this.innerComments = void 0;
  7581. this.extra = void 0;
  7582. this.type = "";
  7583. this.start = pos;
  7584. this.end = 0;
  7585. this.loc = new SourceLocation(loc);
  7586. if (parser == null ? void 0 : parser.options.ranges) this.range = [pos, 0];
  7587. if (parser == null ? void 0 : parser.filename) this.loc.filename = parser.filename;
  7588. }
  7589. __clone() {
  7590. const newNode = new Node();
  7591. const keys = Object.keys(this);
  7592. for (let i = 0, length = keys.length; i < length; i++) {
  7593. const key = keys[i];
  7594. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  7595. newNode[key] = this[key];
  7596. }
  7597. }
  7598. return newNode;
  7599. }
  7600. }
  7601. class NodeUtils extends UtilParser {
  7602. startNode() {
  7603. return new Node(this, this.state.start, this.state.startLoc);
  7604. }
  7605. startNodeAt(pos, loc) {
  7606. return new Node(this, pos, loc);
  7607. }
  7608. startNodeAtNode(type) {
  7609. return this.startNodeAt(type.start, type.loc.start);
  7610. }
  7611. finishNode(node, type) {
  7612. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  7613. }
  7614. finishNodeAt(node, type, pos, loc) {
  7615. node.type = type;
  7616. node.end = pos;
  7617. node.loc.end = loc;
  7618. if (this.options.ranges) node.range[1] = pos;
  7619. this.processComment(node);
  7620. return node;
  7621. }
  7622. resetStartLocation(node, start, startLoc) {
  7623. node.start = start;
  7624. node.loc.start = startLoc;
  7625. if (this.options.ranges) node.range[0] = start;
  7626. }
  7627. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  7628. node.end = end;
  7629. node.loc.end = endLoc;
  7630. if (this.options.ranges) node.range[1] = end;
  7631. }
  7632. resetStartLocationFromNode(node, locationNode) {
  7633. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  7634. }
  7635. }
  7636. const unwrapParenthesizedExpression = node => {
  7637. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7638. };
  7639. class LValParser extends NodeUtils {
  7640. toAssignable(node) {
  7641. var _node$extra, _node$extra3;
  7642. let parenthesized = undefined;
  7643. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  7644. parenthesized = unwrapParenthesizedExpression(node);
  7645. if (parenthesized.type !== "Identifier" && parenthesized.type !== "MemberExpression") {
  7646. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  7647. }
  7648. }
  7649. switch (node.type) {
  7650. case "Identifier":
  7651. case "ObjectPattern":
  7652. case "ArrayPattern":
  7653. case "AssignmentPattern":
  7654. break;
  7655. case "ObjectExpression":
  7656. node.type = "ObjectPattern";
  7657. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7658. var _node$extra2;
  7659. const prop = node.properties[i];
  7660. const isLast = i === last;
  7661. this.toAssignableObjectExpressionProp(prop, isLast);
  7662. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  7663. this.raiseRestNotLast(node.extra.trailingComma);
  7664. }
  7665. }
  7666. break;
  7667. case "ObjectProperty":
  7668. this.toAssignable(node.value);
  7669. break;
  7670. case "SpreadElement":
  7671. {
  7672. this.checkToRestConversion(node);
  7673. node.type = "RestElement";
  7674. const arg = node.argument;
  7675. this.toAssignable(arg);
  7676. break;
  7677. }
  7678. case "ArrayExpression":
  7679. node.type = "ArrayPattern";
  7680. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma);
  7681. break;
  7682. case "AssignmentExpression":
  7683. if (node.operator !== "=") {
  7684. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  7685. }
  7686. node.type = "AssignmentPattern";
  7687. delete node.operator;
  7688. this.toAssignable(node.left);
  7689. break;
  7690. case "ParenthesizedExpression":
  7691. this.toAssignable(parenthesized);
  7692. break;
  7693. }
  7694. return node;
  7695. }
  7696. toAssignableObjectExpressionProp(prop, isLast) {
  7697. if (prop.type === "ObjectMethod") {
  7698. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  7699. this.raise(prop.key.start, error);
  7700. } else if (prop.type === "SpreadElement" && !isLast) {
  7701. this.raiseRestNotLast(prop.start);
  7702. } else {
  7703. this.toAssignable(prop);
  7704. }
  7705. }
  7706. toAssignableList(exprList, trailingCommaPos) {
  7707. let end = exprList.length;
  7708. if (end) {
  7709. const last = exprList[end - 1];
  7710. if ((last == null ? void 0 : last.type) === "RestElement") {
  7711. --end;
  7712. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  7713. last.type = "RestElement";
  7714. const arg = last.argument;
  7715. this.toAssignable(arg);
  7716. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7717. this.unexpected(arg.start);
  7718. }
  7719. if (trailingCommaPos) {
  7720. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7721. }
  7722. --end;
  7723. }
  7724. }
  7725. for (let i = 0; i < end; i++) {
  7726. const elt = exprList[i];
  7727. if (elt) {
  7728. this.toAssignable(elt);
  7729. if (elt.type === "RestElement") {
  7730. this.raiseRestNotLast(elt.start);
  7731. }
  7732. }
  7733. }
  7734. return exprList;
  7735. }
  7736. toReferencedList(exprList, isParenthesizedExpr) {
  7737. return exprList;
  7738. }
  7739. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7740. this.toReferencedList(exprList, isParenthesizedExpr);
  7741. for (let _i = 0; _i < exprList.length; _i++) {
  7742. const expr = exprList[_i];
  7743. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  7744. this.toReferencedListDeep(expr.elements);
  7745. }
  7746. }
  7747. }
  7748. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  7749. const node = this.startNode();
  7750. this.next();
  7751. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  7752. return this.finishNode(node, "SpreadElement");
  7753. }
  7754. parseRestBinding() {
  7755. const node = this.startNode();
  7756. this.next();
  7757. node.argument = this.parseBindingAtom();
  7758. return this.finishNode(node, "RestElement");
  7759. }
  7760. parseBindingAtom() {
  7761. switch (this.state.type) {
  7762. case types.bracketL:
  7763. {
  7764. const node = this.startNode();
  7765. this.next();
  7766. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7767. return this.finishNode(node, "ArrayPattern");
  7768. }
  7769. case types.braceL:
  7770. return this.parseObjectLike(types.braceR, true);
  7771. }
  7772. return this.parseIdentifier();
  7773. }
  7774. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7775. const elts = [];
  7776. let first = true;
  7777. while (!this.eat(close)) {
  7778. if (first) {
  7779. first = false;
  7780. } else {
  7781. this.expect(types.comma);
  7782. }
  7783. if (allowEmpty && this.match(types.comma)) {
  7784. elts.push(null);
  7785. } else if (this.eat(close)) {
  7786. break;
  7787. } else if (this.match(types.ellipsis)) {
  7788. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7789. this.checkCommaAfterRest(closeCharCode);
  7790. this.expect(close);
  7791. break;
  7792. } else {
  7793. const decorators = [];
  7794. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7795. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  7796. }
  7797. while (this.match(types.at)) {
  7798. decorators.push(this.parseDecorator());
  7799. }
  7800. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7801. }
  7802. }
  7803. return elts;
  7804. }
  7805. parseAssignableListItem(allowModifiers, decorators) {
  7806. const left = this.parseMaybeDefault();
  7807. this.parseAssignableListItemTypes(left);
  7808. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7809. if (decorators.length) {
  7810. left.decorators = decorators;
  7811. }
  7812. return elt;
  7813. }
  7814. parseAssignableListItemTypes(param) {
  7815. return param;
  7816. }
  7817. parseMaybeDefault(startPos, startLoc, left) {
  7818. var _startLoc, _startPos, _left;
  7819. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  7820. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  7821. left = (_left = left) != null ? _left : this.parseBindingAtom();
  7822. if (!this.eat(types.eq)) return left;
  7823. const node = this.startNodeAt(startPos, startLoc);
  7824. node.left = left;
  7825. node.right = this.parseMaybeAssignAllowIn();
  7826. return this.finishNode(node, "AssignmentPattern");
  7827. }
  7828. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding, strictModeChanged = false) {
  7829. switch (expr.type) {
  7830. case "Identifier":
  7831. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) {
  7832. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, expr.name);
  7833. }
  7834. if (checkClashes) {
  7835. const key = `_${expr.name}`;
  7836. if (checkClashes[key]) {
  7837. this.raise(expr.start, ErrorMessages.ParamDupe);
  7838. } else {
  7839. checkClashes[key] = true;
  7840. }
  7841. }
  7842. if (disallowLetBinding && expr.name === "let") {
  7843. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  7844. }
  7845. if (!(bindingType & BIND_NONE)) {
  7846. this.scope.declareName(expr.name, bindingType, expr.start);
  7847. }
  7848. break;
  7849. case "MemberExpression":
  7850. if (bindingType !== BIND_NONE) {
  7851. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  7852. }
  7853. break;
  7854. case "ObjectPattern":
  7855. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7856. let prop = _expr$properties[_i2];
  7857. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  7858. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  7859. }
  7860. break;
  7861. case "ArrayPattern":
  7862. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7863. const elem = _expr$elements[_i3];
  7864. if (elem) {
  7865. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding);
  7866. }
  7867. }
  7868. break;
  7869. case "AssignmentPattern":
  7870. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  7871. break;
  7872. case "RestElement":
  7873. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  7874. break;
  7875. case "ParenthesizedExpression":
  7876. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  7877. break;
  7878. default:
  7879. {
  7880. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  7881. }
  7882. }
  7883. }
  7884. checkToRestConversion(node) {
  7885. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7886. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  7887. }
  7888. }
  7889. checkCommaAfterRest(close) {
  7890. if (this.match(types.comma)) {
  7891. if (this.lookaheadCharCode() === close) {
  7892. this.raiseTrailingCommaAfterRest(this.state.start);
  7893. } else {
  7894. this.raiseRestNotLast(this.state.start);
  7895. }
  7896. }
  7897. }
  7898. raiseRestNotLast(pos) {
  7899. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  7900. }
  7901. raiseTrailingCommaAfterRest(pos) {
  7902. this.raise(pos, ErrorMessages.RestTrailingComma);
  7903. }
  7904. }
  7905. class ExpressionParser extends LValParser {
  7906. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  7907. if (prop.type === "SpreadElement" || prop.type === "ObjectMethod" || prop.computed || prop.shorthand) {
  7908. return;
  7909. }
  7910. const key = prop.key;
  7911. const name = key.type === "Identifier" ? key.name : key.value;
  7912. if (name === "__proto__") {
  7913. if (isRecord) {
  7914. this.raise(key.start, ErrorMessages.RecordNoProto);
  7915. return;
  7916. }
  7917. if (protoRef.used) {
  7918. if (refExpressionErrors) {
  7919. if (refExpressionErrors.doubleProto === -1) {
  7920. refExpressionErrors.doubleProto = key.start;
  7921. }
  7922. } else {
  7923. this.raise(key.start, ErrorMessages.DuplicateProto);
  7924. }
  7925. }
  7926. protoRef.used = true;
  7927. }
  7928. }
  7929. shouldExitDescending(expr, potentialArrowAt) {
  7930. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  7931. }
  7932. getExpression() {
  7933. let paramFlags = PARAM;
  7934. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  7935. paramFlags |= PARAM_AWAIT;
  7936. }
  7937. this.scope.enter(SCOPE_PROGRAM);
  7938. this.prodParam.enter(paramFlags);
  7939. this.nextToken();
  7940. const expr = this.parseExpression();
  7941. if (!this.match(types.eof)) {
  7942. this.unexpected();
  7943. }
  7944. expr.comments = this.state.comments;
  7945. expr.errors = this.state.errors;
  7946. return expr;
  7947. }
  7948. parseExpression(disallowIn, refExpressionErrors) {
  7949. if (disallowIn) {
  7950. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  7951. }
  7952. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  7953. }
  7954. parseExpressionBase(refExpressionErrors) {
  7955. const startPos = this.state.start;
  7956. const startLoc = this.state.startLoc;
  7957. const expr = this.parseMaybeAssign(refExpressionErrors);
  7958. if (this.match(types.comma)) {
  7959. const node = this.startNodeAt(startPos, startLoc);
  7960. node.expressions = [expr];
  7961. while (this.eat(types.comma)) {
  7962. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  7963. }
  7964. this.toReferencedList(node.expressions);
  7965. return this.finishNode(node, "SequenceExpression");
  7966. }
  7967. return expr;
  7968. }
  7969. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  7970. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  7971. }
  7972. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  7973. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  7974. }
  7975. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  7976. const startPos = this.state.start;
  7977. const startLoc = this.state.startLoc;
  7978. if (this.isContextual("yield")) {
  7979. if (this.prodParam.hasYield) {
  7980. let left = this.parseYield();
  7981. if (afterLeftParse) {
  7982. left = afterLeftParse.call(this, left, startPos, startLoc);
  7983. }
  7984. return left;
  7985. } else {
  7986. this.state.exprAllowed = false;
  7987. }
  7988. }
  7989. let ownExpressionErrors;
  7990. if (refExpressionErrors) {
  7991. ownExpressionErrors = false;
  7992. } else {
  7993. refExpressionErrors = new ExpressionErrors();
  7994. ownExpressionErrors = true;
  7995. }
  7996. if (this.match(types.parenL) || this.match(types.name)) {
  7997. this.state.potentialArrowAt = this.state.start;
  7998. }
  7999. let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
  8000. if (afterLeftParse) {
  8001. left = afterLeftParse.call(this, left, startPos, startLoc);
  8002. }
  8003. if (this.state.type.isAssign) {
  8004. const node = this.startNodeAt(startPos, startLoc);
  8005. const operator = this.state.value;
  8006. node.operator = operator;
  8007. if (this.match(types.eq)) {
  8008. node.left = this.toAssignable(left);
  8009. refExpressionErrors.doubleProto = -1;
  8010. } else {
  8011. node.left = left;
  8012. }
  8013. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  8014. refExpressionErrors.shorthandAssign = -1;
  8015. }
  8016. this.checkLVal(left, undefined, undefined, "assignment expression");
  8017. this.next();
  8018. node.right = this.parseMaybeAssign();
  8019. return this.finishNode(node, "AssignmentExpression");
  8020. } else if (ownExpressionErrors) {
  8021. this.checkExpressionErrors(refExpressionErrors, true);
  8022. }
  8023. return left;
  8024. }
  8025. parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
  8026. const startPos = this.state.start;
  8027. const startLoc = this.state.startLoc;
  8028. const potentialArrowAt = this.state.potentialArrowAt;
  8029. const expr = this.parseExprOps(refExpressionErrors);
  8030. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8031. return expr;
  8032. }
  8033. return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  8034. }
  8035. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  8036. if (this.eat(types.question)) {
  8037. const node = this.startNodeAt(startPos, startLoc);
  8038. node.test = expr;
  8039. node.consequent = this.parseMaybeAssignAllowIn();
  8040. this.expect(types.colon);
  8041. node.alternate = this.parseMaybeAssign();
  8042. return this.finishNode(node, "ConditionalExpression");
  8043. }
  8044. return expr;
  8045. }
  8046. parseExprOps(refExpressionErrors) {
  8047. const startPos = this.state.start;
  8048. const startLoc = this.state.startLoc;
  8049. const potentialArrowAt = this.state.potentialArrowAt;
  8050. const expr = this.parseMaybeUnary(refExpressionErrors);
  8051. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8052. return expr;
  8053. }
  8054. return this.parseExprOp(expr, startPos, startLoc, -1);
  8055. }
  8056. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8057. let prec = this.state.type.binop;
  8058. if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
  8059. if (prec > minPrec) {
  8060. const op = this.state.type;
  8061. if (op === types.pipeline) {
  8062. this.expectPlugin("pipelineOperator");
  8063. if (this.state.inFSharpPipelineDirectBody) {
  8064. return left;
  8065. }
  8066. this.state.inPipeline = true;
  8067. this.checkPipelineAtInfixOperator(left, leftStartPos);
  8068. }
  8069. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8070. node.left = left;
  8071. node.operator = this.state.value;
  8072. if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  8073. this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  8074. }
  8075. const logical = op === types.logicalOR || op === types.logicalAND;
  8076. const coalesce = op === types.nullishCoalescing;
  8077. if (coalesce) {
  8078. prec = types.logicalAND.binop;
  8079. }
  8080. this.next();
  8081. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  8082. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  8083. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  8084. }
  8085. }
  8086. node.right = this.parseExprOpRightExpr(op, prec);
  8087. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  8088. const nextOp = this.state.type;
  8089. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  8090. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  8091. }
  8092. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8093. }
  8094. }
  8095. return left;
  8096. }
  8097. parseExprOpRightExpr(op, prec) {
  8098. const startPos = this.state.start;
  8099. const startLoc = this.state.startLoc;
  8100. switch (op) {
  8101. case types.pipeline:
  8102. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  8103. case "smart":
  8104. return this.withTopicPermittingContext(() => {
  8105. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  8106. });
  8107. case "fsharp":
  8108. return this.withSoloAwaitPermittingContext(() => {
  8109. return this.parseFSharpPipelineBody(prec);
  8110. });
  8111. }
  8112. default:
  8113. return this.parseExprOpBaseRightExpr(op, prec);
  8114. }
  8115. }
  8116. parseExprOpBaseRightExpr(op, prec) {
  8117. const startPos = this.state.start;
  8118. const startLoc = this.state.startLoc;
  8119. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
  8120. }
  8121. parseMaybeUnary(refExpressionErrors) {
  8122. if (this.isContextual("await") && this.isAwaitAllowed()) {
  8123. return this.parseAwait();
  8124. }
  8125. const update = this.match(types.incDec);
  8126. const node = this.startNode();
  8127. if (this.state.type.prefix) {
  8128. node.operator = this.state.value;
  8129. node.prefix = true;
  8130. if (this.match(types._throw)) {
  8131. this.expectPlugin("throwExpressions");
  8132. }
  8133. const isDelete = this.match(types._delete);
  8134. this.next();
  8135. node.argument = this.parseMaybeUnary();
  8136. this.checkExpressionErrors(refExpressionErrors, true);
  8137. if (this.state.strict && isDelete) {
  8138. const arg = node.argument;
  8139. if (arg.type === "Identifier") {
  8140. this.raise(node.start, ErrorMessages.StrictDelete);
  8141. } else if ((arg.type === "MemberExpression" || arg.type === "OptionalMemberExpression") && arg.property.type === "PrivateName") {
  8142. this.raise(node.start, ErrorMessages.DeletePrivateField);
  8143. }
  8144. }
  8145. if (!update) {
  8146. return this.finishNode(node, "UnaryExpression");
  8147. }
  8148. }
  8149. return this.parseUpdate(node, update, refExpressionErrors);
  8150. }
  8151. parseUpdate(node, update, refExpressionErrors) {
  8152. if (update) {
  8153. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  8154. return this.finishNode(node, "UpdateExpression");
  8155. }
  8156. const startPos = this.state.start;
  8157. const startLoc = this.state.startLoc;
  8158. let expr = this.parseExprSubscripts(refExpressionErrors);
  8159. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  8160. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  8161. const node = this.startNodeAt(startPos, startLoc);
  8162. node.operator = this.state.value;
  8163. node.prefix = false;
  8164. node.argument = expr;
  8165. this.checkLVal(expr, undefined, undefined, "postfix operation");
  8166. this.next();
  8167. expr = this.finishNode(node, "UpdateExpression");
  8168. }
  8169. return expr;
  8170. }
  8171. parseExprSubscripts(refExpressionErrors) {
  8172. const startPos = this.state.start;
  8173. const startLoc = this.state.startLoc;
  8174. const potentialArrowAt = this.state.potentialArrowAt;
  8175. const expr = this.parseExprAtom(refExpressionErrors);
  8176. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8177. return expr;
  8178. }
  8179. return this.parseSubscripts(expr, startPos, startLoc);
  8180. }
  8181. parseSubscripts(base, startPos, startLoc, noCalls) {
  8182. const state = {
  8183. optionalChainMember: false,
  8184. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  8185. stop: false
  8186. };
  8187. do {
  8188. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  8189. if (state.maybeAsyncArrow) {
  8190. this.state.maybeInAsyncArrowHead = true;
  8191. }
  8192. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  8193. state.maybeAsyncArrow = false;
  8194. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  8195. } while (!state.stop);
  8196. return base;
  8197. }
  8198. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8199. if (!noCalls && this.eat(types.doubleColon)) {
  8200. return this.parseBind(base, startPos, startLoc, noCalls, state);
  8201. } else if (this.match(types.backQuote)) {
  8202. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8203. }
  8204. let optional = false;
  8205. if (this.match(types.questionDot)) {
  8206. state.optionalChainMember = optional = true;
  8207. if (noCalls && this.lookaheadCharCode() === 40) {
  8208. state.stop = true;
  8209. return base;
  8210. }
  8211. this.next();
  8212. }
  8213. if (!noCalls && this.match(types.parenL)) {
  8214. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  8215. } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
  8216. return this.parseMember(base, startPos, startLoc, state, optional);
  8217. } else {
  8218. state.stop = true;
  8219. return base;
  8220. }
  8221. }
  8222. parseMember(base, startPos, startLoc, state, optional) {
  8223. const node = this.startNodeAt(startPos, startLoc);
  8224. const computed = this.eat(types.bracketL);
  8225. node.object = base;
  8226. node.computed = computed;
  8227. const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
  8228. if (property.type === "PrivateName") {
  8229. if (node.object.type === "Super") {
  8230. this.raise(startPos, ErrorMessages.SuperPrivateField);
  8231. }
  8232. this.classScope.usePrivateName(property.id.name, property.start);
  8233. }
  8234. node.property = property;
  8235. if (computed) {
  8236. this.expect(types.bracketR);
  8237. }
  8238. if (state.optionalChainMember) {
  8239. node.optional = optional;
  8240. return this.finishNode(node, "OptionalMemberExpression");
  8241. } else {
  8242. return this.finishNode(node, "MemberExpression");
  8243. }
  8244. }
  8245. parseBind(base, startPos, startLoc, noCalls, state) {
  8246. const node = this.startNodeAt(startPos, startLoc);
  8247. node.object = base;
  8248. node.callee = this.parseNoCallExpr();
  8249. state.stop = true;
  8250. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  8251. }
  8252. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  8253. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8254. const oldYieldPos = this.state.yieldPos;
  8255. const oldAwaitPos = this.state.awaitPos;
  8256. this.state.maybeInArrowParameters = true;
  8257. this.state.yieldPos = -1;
  8258. this.state.awaitPos = -1;
  8259. this.next();
  8260. let node = this.startNodeAt(startPos, startLoc);
  8261. node.callee = base;
  8262. if (state.optionalChainMember) {
  8263. node.optional = optional;
  8264. }
  8265. if (optional) {
  8266. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8267. } else {
  8268. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  8269. }
  8270. this.finishCallExpression(node, state.optionalChainMember);
  8271. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  8272. state.stop = true;
  8273. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  8274. this.checkYieldAwaitInDefaultParams();
  8275. this.state.yieldPos = oldYieldPos;
  8276. this.state.awaitPos = oldAwaitPos;
  8277. } else {
  8278. this.toReferencedListDeep(node.arguments);
  8279. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  8280. if (!this.isAwaitAllowed() && !oldMaybeInArrowParameters || oldAwaitPos !== -1) {
  8281. this.state.awaitPos = oldAwaitPos;
  8282. }
  8283. }
  8284. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8285. return node;
  8286. }
  8287. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  8288. const node = this.startNodeAt(startPos, startLoc);
  8289. node.tag = base;
  8290. node.quasi = this.parseTemplate(true);
  8291. if (state.optionalChainMember) {
  8292. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  8293. }
  8294. return this.finishNode(node, "TaggedTemplateExpression");
  8295. }
  8296. atPossibleAsyncArrow(base) {
  8297. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  8298. }
  8299. finishCallExpression(node, optional) {
  8300. if (node.callee.type === "Import") {
  8301. if (node.arguments.length === 2) {
  8302. if (!this.hasPlugin("moduleAttributes")) {
  8303. this.expectPlugin("importAssertions");
  8304. }
  8305. }
  8306. if (node.arguments.length === 0 || node.arguments.length > 2) {
  8307. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  8308. } else {
  8309. for (let _i = 0, _node$arguments = node.arguments; _i < _node$arguments.length; _i++) {
  8310. const arg = _node$arguments[_i];
  8311. if (arg.type === "SpreadElement") {
  8312. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  8313. }
  8314. }
  8315. }
  8316. }
  8317. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  8318. }
  8319. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  8320. const elts = [];
  8321. let innerParenStart;
  8322. let first = true;
  8323. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8324. this.state.inFSharpPipelineDirectBody = false;
  8325. while (!this.eat(close)) {
  8326. if (first) {
  8327. first = false;
  8328. } else {
  8329. this.expect(types.comma);
  8330. if (this.match(close)) {
  8331. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  8332. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  8333. }
  8334. if (nodeForExtra) {
  8335. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8336. }
  8337. this.next();
  8338. break;
  8339. }
  8340. }
  8341. if (this.match(types.parenL) && !innerParenStart) {
  8342. innerParenStart = this.state.start;
  8343. }
  8344. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8345. start: 0
  8346. } : undefined, allowPlaceholder));
  8347. }
  8348. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  8349. this.unexpected();
  8350. }
  8351. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8352. return elts;
  8353. }
  8354. shouldParseAsyncArrow() {
  8355. return this.match(types.arrow) && !this.canInsertSemicolon();
  8356. }
  8357. parseAsyncArrowFromCallExpression(node, call) {
  8358. var _call$extra;
  8359. this.expect(types.arrow);
  8360. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8361. return node;
  8362. }
  8363. parseNoCallExpr() {
  8364. const startPos = this.state.start;
  8365. const startLoc = this.state.startLoc;
  8366. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8367. }
  8368. parseExprAtom(refExpressionErrors) {
  8369. if (this.state.type === types.slash) this.readRegexp();
  8370. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8371. let node;
  8372. switch (this.state.type) {
  8373. case types._super:
  8374. return this.parseSuper();
  8375. case types._import:
  8376. node = this.startNode();
  8377. this.next();
  8378. if (this.match(types.dot)) {
  8379. return this.parseImportMetaProperty(node);
  8380. }
  8381. if (!this.match(types.parenL)) {
  8382. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  8383. }
  8384. return this.finishNode(node, "Import");
  8385. case types._this:
  8386. node = this.startNode();
  8387. this.next();
  8388. return this.finishNode(node, "ThisExpression");
  8389. case types.name:
  8390. {
  8391. const containsEsc = this.state.containsEsc;
  8392. const id = this.parseIdentifier();
  8393. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  8394. if (this.match(types._function)) {
  8395. const last = this.state.context.length - 1;
  8396. if (this.state.context[last] !== types$1.functionStatement) {
  8397. throw new Error("Internal error");
  8398. }
  8399. this.state.context[last] = types$1.functionExpression;
  8400. this.next();
  8401. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  8402. } else if (this.match(types.name)) {
  8403. return this.parseAsyncArrowUnaryFunction(id);
  8404. }
  8405. }
  8406. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8407. this.next();
  8408. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  8409. }
  8410. return id;
  8411. }
  8412. case types._do:
  8413. {
  8414. return this.parseDo();
  8415. }
  8416. case types.regexp:
  8417. {
  8418. const value = this.state.value;
  8419. node = this.parseLiteral(value.value, "RegExpLiteral");
  8420. node.pattern = value.pattern;
  8421. node.flags = value.flags;
  8422. return node;
  8423. }
  8424. case types.num:
  8425. return this.parseLiteral(this.state.value, "NumericLiteral");
  8426. case types.bigint:
  8427. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8428. case types.decimal:
  8429. return this.parseLiteral(this.state.value, "DecimalLiteral");
  8430. case types.string:
  8431. return this.parseLiteral(this.state.value, "StringLiteral");
  8432. case types._null:
  8433. node = this.startNode();
  8434. this.next();
  8435. return this.finishNode(node, "NullLiteral");
  8436. case types._true:
  8437. case types._false:
  8438. return this.parseBooleanLiteral();
  8439. case types.parenL:
  8440. return this.parseParenAndDistinguishExpression(canBeArrow);
  8441. case types.bracketBarL:
  8442. case types.bracketHashL:
  8443. {
  8444. return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
  8445. }
  8446. case types.bracketL:
  8447. {
  8448. return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
  8449. }
  8450. case types.braceBarL:
  8451. case types.braceHashL:
  8452. {
  8453. return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
  8454. }
  8455. case types.braceL:
  8456. {
  8457. return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
  8458. }
  8459. case types._function:
  8460. return this.parseFunctionOrFunctionSent();
  8461. case types.at:
  8462. this.parseDecorators();
  8463. case types._class:
  8464. node = this.startNode();
  8465. this.takeDecorators(node);
  8466. return this.parseClass(node, false);
  8467. case types._new:
  8468. return this.parseNewOrNewTarget();
  8469. case types.backQuote:
  8470. return this.parseTemplate(false);
  8471. case types.doubleColon:
  8472. {
  8473. node = this.startNode();
  8474. this.next();
  8475. node.object = null;
  8476. const callee = node.callee = this.parseNoCallExpr();
  8477. if (callee.type === "MemberExpression") {
  8478. return this.finishNode(node, "BindExpression");
  8479. } else {
  8480. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  8481. }
  8482. }
  8483. case types.hash:
  8484. {
  8485. if (this.state.inPipeline) {
  8486. node = this.startNode();
  8487. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  8488. this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
  8489. }
  8490. this.next();
  8491. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  8492. this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
  8493. }
  8494. this.registerTopicReference();
  8495. return this.finishNode(node, "PipelinePrimaryTopicReference");
  8496. }
  8497. const nextCh = this.input.codePointAt(this.state.end);
  8498. if (isIdentifierStart(nextCh) || nextCh === 92) {
  8499. const start = this.state.start;
  8500. node = this.parseMaybePrivateName(true);
  8501. if (this.match(types._in)) {
  8502. this.expectPlugin("privateIn");
  8503. this.classScope.usePrivateName(node.id.name, node.start);
  8504. } else if (this.hasPlugin("privateIn")) {
  8505. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, node.id.name);
  8506. } else {
  8507. throw this.unexpected(start);
  8508. }
  8509. return node;
  8510. }
  8511. }
  8512. case types.relational:
  8513. {
  8514. if (this.state.value === "<") {
  8515. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  8516. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  8517. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  8518. }
  8519. }
  8520. }
  8521. default:
  8522. throw this.unexpected();
  8523. }
  8524. }
  8525. parseAsyncArrowUnaryFunction(id) {
  8526. const node = this.startNodeAtNode(id);
  8527. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8528. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  8529. const oldYieldPos = this.state.yieldPos;
  8530. const oldAwaitPos = this.state.awaitPos;
  8531. this.state.maybeInArrowParameters = true;
  8532. this.state.maybeInAsyncArrowHead = true;
  8533. this.state.yieldPos = -1;
  8534. this.state.awaitPos = -1;
  8535. const params = [this.parseIdentifier()];
  8536. if (this.hasPrecedingLineBreak()) {
  8537. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  8538. }
  8539. this.expect(types.arrow);
  8540. this.checkYieldAwaitInDefaultParams();
  8541. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8542. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  8543. this.state.yieldPos = oldYieldPos;
  8544. this.state.awaitPos = oldAwaitPos;
  8545. this.parseArrowExpression(node, params, true);
  8546. return node;
  8547. }
  8548. parseDo() {
  8549. this.expectPlugin("doExpressions");
  8550. const node = this.startNode();
  8551. this.next();
  8552. const oldLabels = this.state.labels;
  8553. this.state.labels = [];
  8554. node.body = this.parseBlock();
  8555. this.state.labels = oldLabels;
  8556. return this.finishNode(node, "DoExpression");
  8557. }
  8558. parseSuper() {
  8559. const node = this.startNode();
  8560. this.next();
  8561. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  8562. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  8563. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  8564. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  8565. }
  8566. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  8567. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  8568. }
  8569. return this.finishNode(node, "Super");
  8570. }
  8571. parseBooleanLiteral() {
  8572. const node = this.startNode();
  8573. node.value = this.match(types._true);
  8574. this.next();
  8575. return this.finishNode(node, "BooleanLiteral");
  8576. }
  8577. parseMaybePrivateName(isPrivateNameAllowed) {
  8578. const isPrivate = this.match(types.hash);
  8579. if (isPrivate) {
  8580. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  8581. if (!isPrivateNameAllowed) {
  8582. this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
  8583. }
  8584. const node = this.startNode();
  8585. this.next();
  8586. this.assertNoSpace("Unexpected space between # and identifier");
  8587. node.id = this.parseIdentifier(true);
  8588. return this.finishNode(node, "PrivateName");
  8589. } else {
  8590. return this.parseIdentifier(true);
  8591. }
  8592. }
  8593. parseFunctionOrFunctionSent() {
  8594. const node = this.startNode();
  8595. this.next();
  8596. if (this.prodParam.hasYield && this.match(types.dot)) {
  8597. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  8598. this.next();
  8599. return this.parseMetaProperty(node, meta, "sent");
  8600. }
  8601. return this.parseFunction(node);
  8602. }
  8603. parseMetaProperty(node, meta, propertyName) {
  8604. node.meta = meta;
  8605. if (meta.name === "function" && propertyName === "sent") {
  8606. if (this.isContextual(propertyName)) {
  8607. this.expectPlugin("functionSent");
  8608. } else if (!this.hasPlugin("functionSent")) {
  8609. this.unexpected();
  8610. }
  8611. }
  8612. const containsEsc = this.state.containsEsc;
  8613. node.property = this.parseIdentifier(true);
  8614. if (node.property.name !== propertyName || containsEsc) {
  8615. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  8616. }
  8617. return this.finishNode(node, "MetaProperty");
  8618. }
  8619. parseImportMetaProperty(node) {
  8620. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  8621. this.next();
  8622. if (this.isContextual("meta")) {
  8623. if (!this.inModule) {
  8624. this.raiseWithData(id.start, {
  8625. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8626. }, ErrorMessages.ImportMetaOutsideModule);
  8627. }
  8628. this.sawUnambiguousESM = true;
  8629. }
  8630. return this.parseMetaProperty(node, id, "meta");
  8631. }
  8632. parseLiteral(value, type, startPos, startLoc) {
  8633. startPos = startPos || this.state.start;
  8634. startLoc = startLoc || this.state.startLoc;
  8635. const node = this.startNodeAt(startPos, startLoc);
  8636. this.addExtra(node, "rawValue", value);
  8637. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  8638. node.value = value;
  8639. this.next();
  8640. return this.finishNode(node, type);
  8641. }
  8642. parseParenAndDistinguishExpression(canBeArrow) {
  8643. const startPos = this.state.start;
  8644. const startLoc = this.state.startLoc;
  8645. let val;
  8646. this.next();
  8647. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8648. const oldYieldPos = this.state.yieldPos;
  8649. const oldAwaitPos = this.state.awaitPos;
  8650. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8651. this.state.maybeInArrowParameters = true;
  8652. this.state.yieldPos = -1;
  8653. this.state.awaitPos = -1;
  8654. this.state.inFSharpPipelineDirectBody = false;
  8655. const innerStartPos = this.state.start;
  8656. const innerStartLoc = this.state.startLoc;
  8657. const exprList = [];
  8658. const refExpressionErrors = new ExpressionErrors();
  8659. const refNeedsArrowPos = {
  8660. start: 0
  8661. };
  8662. let first = true;
  8663. let spreadStart;
  8664. let optionalCommaStart;
  8665. while (!this.match(types.parenR)) {
  8666. if (first) {
  8667. first = false;
  8668. } else {
  8669. this.expect(types.comma, refNeedsArrowPos.start || null);
  8670. if (this.match(types.parenR)) {
  8671. optionalCommaStart = this.state.start;
  8672. break;
  8673. }
  8674. }
  8675. if (this.match(types.ellipsis)) {
  8676. const spreadNodeStartPos = this.state.start;
  8677. const spreadNodeStartLoc = this.state.startLoc;
  8678. spreadStart = this.state.start;
  8679. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  8680. this.checkCommaAfterRest(41);
  8681. break;
  8682. } else {
  8683. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  8684. }
  8685. }
  8686. const innerEndPos = this.state.lastTokEnd;
  8687. const innerEndLoc = this.state.lastTokEndLoc;
  8688. this.expect(types.parenR);
  8689. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8690. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8691. let arrowNode = this.startNodeAt(startPos, startLoc);
  8692. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  8693. if (!this.isAwaitAllowed() && !this.state.maybeInAsyncArrowHead) {
  8694. this.state.awaitPos = oldAwaitPos;
  8695. }
  8696. this.checkYieldAwaitInDefaultParams();
  8697. this.state.yieldPos = oldYieldPos;
  8698. this.state.awaitPos = oldAwaitPos;
  8699. for (let _i2 = 0; _i2 < exprList.length; _i2++) {
  8700. const param = exprList[_i2];
  8701. if (param.extra && param.extra.parenthesized) {
  8702. this.unexpected(param.extra.parenStart);
  8703. }
  8704. }
  8705. this.parseArrowExpression(arrowNode, exprList, false);
  8706. return arrowNode;
  8707. }
  8708. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  8709. if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
  8710. if (!exprList.length) {
  8711. this.unexpected(this.state.lastTokStart);
  8712. }
  8713. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8714. if (spreadStart) this.unexpected(spreadStart);
  8715. this.checkExpressionErrors(refExpressionErrors, true);
  8716. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8717. this.toReferencedListDeep(exprList, true);
  8718. if (exprList.length > 1) {
  8719. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8720. val.expressions = exprList;
  8721. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8722. } else {
  8723. val = exprList[0];
  8724. }
  8725. if (!this.options.createParenthesizedExpressions) {
  8726. this.addExtra(val, "parenthesized", true);
  8727. this.addExtra(val, "parenStart", startPos);
  8728. return val;
  8729. }
  8730. const parenExpression = this.startNodeAt(startPos, startLoc);
  8731. parenExpression.expression = val;
  8732. this.finishNode(parenExpression, "ParenthesizedExpression");
  8733. return parenExpression;
  8734. }
  8735. shouldParseArrow() {
  8736. return !this.canInsertSemicolon();
  8737. }
  8738. parseArrow(node) {
  8739. if (this.eat(types.arrow)) {
  8740. return node;
  8741. }
  8742. }
  8743. parseParenItem(node, startPos, startLoc) {
  8744. return node;
  8745. }
  8746. parseNewOrNewTarget() {
  8747. const node = this.startNode();
  8748. this.next();
  8749. if (this.match(types.dot)) {
  8750. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  8751. this.next();
  8752. const metaProp = this.parseMetaProperty(node, meta, "target");
  8753. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  8754. let error = ErrorMessages.UnexpectedNewTarget;
  8755. if (this.hasPlugin("classProperties")) {
  8756. error += " or class properties";
  8757. }
  8758. this.raise(metaProp.start, error);
  8759. }
  8760. return metaProp;
  8761. }
  8762. return this.parseNew(node);
  8763. }
  8764. parseNew(node) {
  8765. node.callee = this.parseNoCallExpr();
  8766. if (node.callee.type === "Import") {
  8767. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  8768. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  8769. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  8770. } else if (this.eat(types.questionDot)) {
  8771. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  8772. }
  8773. this.parseNewArguments(node);
  8774. return this.finishNode(node, "NewExpression");
  8775. }
  8776. parseNewArguments(node) {
  8777. if (this.eat(types.parenL)) {
  8778. const args = this.parseExprList(types.parenR);
  8779. this.toReferencedList(args);
  8780. node.arguments = args;
  8781. } else {
  8782. node.arguments = [];
  8783. }
  8784. }
  8785. parseTemplateElement(isTagged) {
  8786. const elem = this.startNode();
  8787. if (this.state.value === null) {
  8788. if (!isTagged) {
  8789. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  8790. }
  8791. }
  8792. elem.value = {
  8793. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8794. cooked: this.state.value
  8795. };
  8796. this.next();
  8797. elem.tail = this.match(types.backQuote);
  8798. return this.finishNode(elem, "TemplateElement");
  8799. }
  8800. parseTemplate(isTagged) {
  8801. const node = this.startNode();
  8802. this.next();
  8803. node.expressions = [];
  8804. let curElt = this.parseTemplateElement(isTagged);
  8805. node.quasis = [curElt];
  8806. while (!curElt.tail) {
  8807. this.expect(types.dollarBraceL);
  8808. node.expressions.push(this.parseTemplateSubstitution());
  8809. this.expect(types.braceR);
  8810. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8811. }
  8812. this.next();
  8813. return this.finishNode(node, "TemplateLiteral");
  8814. }
  8815. parseTemplateSubstitution() {
  8816. return this.parseExpression();
  8817. }
  8818. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  8819. if (isRecord) {
  8820. this.expectPlugin("recordAndTuple");
  8821. }
  8822. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8823. this.state.inFSharpPipelineDirectBody = false;
  8824. const propHash = Object.create(null);
  8825. let first = true;
  8826. const node = this.startNode();
  8827. node.properties = [];
  8828. this.next();
  8829. while (!this.eat(close)) {
  8830. if (first) {
  8831. first = false;
  8832. } else {
  8833. this.expect(types.comma);
  8834. if (this.match(close)) {
  8835. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8836. this.next();
  8837. break;
  8838. }
  8839. }
  8840. const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
  8841. if (!isPattern) {
  8842. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  8843. }
  8844. if (isRecord && prop.type !== "ObjectProperty" && prop.type !== "SpreadElement") {
  8845. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  8846. }
  8847. if (prop.shorthand) {
  8848. this.addExtra(prop, "shorthand", true);
  8849. }
  8850. node.properties.push(prop);
  8851. }
  8852. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8853. let type = "ObjectExpression";
  8854. if (isPattern) {
  8855. type = "ObjectPattern";
  8856. } else if (isRecord) {
  8857. type = "RecordExpression";
  8858. }
  8859. return this.finishNode(node, type);
  8860. }
  8861. maybeAsyncOrAccessorProp(prop) {
  8862. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
  8863. }
  8864. parsePropertyDefinition(isPattern, refExpressionErrors) {
  8865. let decorators = [];
  8866. if (this.match(types.at)) {
  8867. if (this.hasPlugin("decorators")) {
  8868. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  8869. }
  8870. while (this.match(types.at)) {
  8871. decorators.push(this.parseDecorator());
  8872. }
  8873. }
  8874. const prop = this.startNode();
  8875. let isGenerator = false;
  8876. let isAsync = false;
  8877. let isAccessor = false;
  8878. let startPos;
  8879. let startLoc;
  8880. if (this.match(types.ellipsis)) {
  8881. if (decorators.length) this.unexpected();
  8882. if (isPattern) {
  8883. this.next();
  8884. prop.argument = this.parseIdentifier();
  8885. this.checkCommaAfterRest(125);
  8886. return this.finishNode(prop, "RestElement");
  8887. }
  8888. return this.parseSpread();
  8889. }
  8890. if (decorators.length) {
  8891. prop.decorators = decorators;
  8892. decorators = [];
  8893. }
  8894. prop.method = false;
  8895. if (isPattern || refExpressionErrors) {
  8896. startPos = this.state.start;
  8897. startLoc = this.state.startLoc;
  8898. }
  8899. if (!isPattern) {
  8900. isGenerator = this.eat(types.star);
  8901. }
  8902. const containsEsc = this.state.containsEsc;
  8903. const key = this.parsePropertyName(prop, false);
  8904. if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  8905. const keyName = key.name;
  8906. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  8907. isAsync = true;
  8908. isGenerator = this.eat(types.star);
  8909. this.parsePropertyName(prop, false);
  8910. }
  8911. if (keyName === "get" || keyName === "set") {
  8912. isAccessor = true;
  8913. prop.kind = keyName;
  8914. if (this.match(types.star)) {
  8915. isGenerator = true;
  8916. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  8917. this.next();
  8918. }
  8919. this.parsePropertyName(prop, false);
  8920. }
  8921. }
  8922. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  8923. return prop;
  8924. }
  8925. getGetterSetterExpectedParamCount(method) {
  8926. return method.kind === "get" ? 0 : 1;
  8927. }
  8928. getObjectOrClassMethodParams(method) {
  8929. return method.params;
  8930. }
  8931. checkGetterSetterParams(method) {
  8932. var _params;
  8933. const paramCount = this.getGetterSetterExpectedParamCount(method);
  8934. const params = this.getObjectOrClassMethodParams(method);
  8935. const start = method.start;
  8936. if (params.length !== paramCount) {
  8937. if (method.kind === "get") {
  8938. this.raise(start, ErrorMessages.BadGetterArity);
  8939. } else {
  8940. this.raise(start, ErrorMessages.BadSetterArity);
  8941. }
  8942. }
  8943. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  8944. this.raise(start, ErrorMessages.BadSetterRestParameter);
  8945. }
  8946. }
  8947. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  8948. if (isAccessor) {
  8949. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  8950. this.checkGetterSetterParams(prop);
  8951. return prop;
  8952. }
  8953. if (isAsync || isGenerator || this.match(types.parenL)) {
  8954. if (isPattern) this.unexpected();
  8955. prop.kind = "method";
  8956. prop.method = true;
  8957. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  8958. }
  8959. }
  8960. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  8961. prop.shorthand = false;
  8962. if (this.eat(types.colon)) {
  8963. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  8964. return this.finishNode(prop, "ObjectProperty");
  8965. }
  8966. if (!prop.computed && prop.key.type === "Identifier") {
  8967. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  8968. if (isPattern) {
  8969. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8970. } else if (this.match(types.eq) && refExpressionErrors) {
  8971. if (refExpressionErrors.shorthandAssign === -1) {
  8972. refExpressionErrors.shorthandAssign = this.state.start;
  8973. }
  8974. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8975. } else {
  8976. prop.value = prop.key.__clone();
  8977. }
  8978. prop.shorthand = true;
  8979. return this.finishNode(prop, "ObjectProperty");
  8980. }
  8981. }
  8982. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  8983. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  8984. if (!node) this.unexpected();
  8985. return node;
  8986. }
  8987. parsePropertyName(prop, isPrivateNameAllowed) {
  8988. if (this.eat(types.bracketL)) {
  8989. prop.computed = true;
  8990. prop.key = this.parseMaybeAssignAllowIn();
  8991. this.expect(types.bracketR);
  8992. } else {
  8993. const oldInPropertyName = this.state.inPropertyName;
  8994. this.state.inPropertyName = true;
  8995. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  8996. if (prop.key.type !== "PrivateName") {
  8997. prop.computed = false;
  8998. }
  8999. this.state.inPropertyName = oldInPropertyName;
  9000. }
  9001. return prop.key;
  9002. }
  9003. initFunction(node, isAsync) {
  9004. node.id = null;
  9005. node.generator = false;
  9006. node.async = !!isAsync;
  9007. }
  9008. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  9009. const oldYieldPos = this.state.yieldPos;
  9010. const oldAwaitPos = this.state.awaitPos;
  9011. this.state.yieldPos = -1;
  9012. this.state.awaitPos = -1;
  9013. this.initFunction(node, isAsync);
  9014. node.generator = !!isGenerator;
  9015. const allowModifiers = isConstructor;
  9016. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  9017. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9018. this.parseFunctionParams(node, allowModifiers);
  9019. this.parseFunctionBodyAndFinish(node, type, true);
  9020. this.prodParam.exit();
  9021. this.scope.exit();
  9022. this.state.yieldPos = oldYieldPos;
  9023. this.state.awaitPos = oldAwaitPos;
  9024. return node;
  9025. }
  9026. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  9027. if (isTuple) {
  9028. this.expectPlugin("recordAndTuple");
  9029. }
  9030. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9031. this.state.inFSharpPipelineDirectBody = false;
  9032. const node = this.startNode();
  9033. this.next();
  9034. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  9035. if (canBePattern && !this.state.maybeInArrowParameters) {
  9036. this.toReferencedList(node.elements);
  9037. }
  9038. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9039. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  9040. }
  9041. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  9042. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  9043. let flags = functionFlags(isAsync, false);
  9044. if (!this.match(types.bracketL) && this.prodParam.hasIn) {
  9045. flags |= PARAM_IN;
  9046. }
  9047. this.prodParam.enter(flags);
  9048. this.initFunction(node, isAsync);
  9049. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9050. const oldYieldPos = this.state.yieldPos;
  9051. const oldAwaitPos = this.state.awaitPos;
  9052. if (params) {
  9053. this.state.maybeInArrowParameters = true;
  9054. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  9055. }
  9056. this.state.maybeInArrowParameters = false;
  9057. this.state.yieldPos = -1;
  9058. this.state.awaitPos = -1;
  9059. this.parseFunctionBody(node, true);
  9060. this.prodParam.exit();
  9061. this.scope.exit();
  9062. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9063. this.state.yieldPos = oldYieldPos;
  9064. this.state.awaitPos = oldAwaitPos;
  9065. return this.finishNode(node, "ArrowFunctionExpression");
  9066. }
  9067. setArrowFunctionParameters(node, params, trailingCommaPos) {
  9068. node.params = this.toAssignableList(params, trailingCommaPos);
  9069. }
  9070. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  9071. this.parseFunctionBody(node, false, isMethod);
  9072. this.finishNode(node, type);
  9073. }
  9074. parseFunctionBody(node, allowExpression, isMethod = false) {
  9075. const isExpression = allowExpression && !this.match(types.braceL);
  9076. const oldInParameters = this.state.inParameters;
  9077. this.state.inParameters = false;
  9078. if (isExpression) {
  9079. node.body = this.parseMaybeAssign();
  9080. this.checkParams(node, false, allowExpression, false);
  9081. } else {
  9082. const oldStrict = this.state.strict;
  9083. const oldLabels = this.state.labels;
  9084. this.state.labels = [];
  9085. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  9086. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  9087. const nonSimple = !this.isSimpleParamList(node.params);
  9088. if (hasStrictModeDirective && nonSimple) {
  9089. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  9090. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  9091. }
  9092. const strictModeChanged = !oldStrict && this.state.strict;
  9093. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  9094. if (this.state.strict && node.id) {
  9095. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, strictModeChanged);
  9096. }
  9097. });
  9098. this.prodParam.exit();
  9099. this.state.labels = oldLabels;
  9100. }
  9101. this.state.inParameters = oldInParameters;
  9102. }
  9103. isSimpleParamList(params) {
  9104. for (let i = 0, len = params.length; i < len; i++) {
  9105. if (params[i].type !== "Identifier") return false;
  9106. }
  9107. return true;
  9108. }
  9109. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  9110. const nameHash = Object.create(null);
  9111. for (let i = 0; i < node.params.length; i++) {
  9112. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged);
  9113. }
  9114. }
  9115. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  9116. const elts = [];
  9117. let first = true;
  9118. while (!this.eat(close)) {
  9119. if (first) {
  9120. first = false;
  9121. } else {
  9122. this.expect(types.comma);
  9123. if (this.match(close)) {
  9124. if (nodeForExtra) {
  9125. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  9126. }
  9127. this.next();
  9128. break;
  9129. }
  9130. }
  9131. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  9132. }
  9133. return elts;
  9134. }
  9135. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  9136. let elt;
  9137. if (this.match(types.comma)) {
  9138. if (!allowEmpty) {
  9139. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  9140. }
  9141. elt = null;
  9142. } else if (this.match(types.ellipsis)) {
  9143. const spreadNodeStartPos = this.state.start;
  9144. const spreadNodeStartLoc = this.state.startLoc;
  9145. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  9146. } else if (this.match(types.question)) {
  9147. this.expectPlugin("partialApplication");
  9148. if (!allowPlaceholder) {
  9149. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  9150. }
  9151. const node = this.startNode();
  9152. this.next();
  9153. elt = this.finishNode(node, "ArgumentPlaceholder");
  9154. } else {
  9155. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  9156. }
  9157. return elt;
  9158. }
  9159. parseIdentifier(liberal) {
  9160. const node = this.startNode();
  9161. const name = this.parseIdentifierName(node.start, liberal);
  9162. return this.createIdentifier(node, name);
  9163. }
  9164. createIdentifier(node, name) {
  9165. node.name = name;
  9166. node.loc.identifierName = name;
  9167. return this.finishNode(node, "Identifier");
  9168. }
  9169. parseIdentifierName(pos, liberal) {
  9170. let name;
  9171. const {
  9172. start,
  9173. type
  9174. } = this.state;
  9175. if (type === types.name) {
  9176. name = this.state.value;
  9177. } else if (type.keyword) {
  9178. name = type.keyword;
  9179. const curContext = this.curContext();
  9180. if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
  9181. this.state.context.pop();
  9182. }
  9183. } else {
  9184. throw this.unexpected();
  9185. }
  9186. if (liberal) {
  9187. this.state.type = types.name;
  9188. } else {
  9189. this.checkReservedWord(name, start, !!type.keyword, false);
  9190. }
  9191. this.next();
  9192. return name;
  9193. }
  9194. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9195. if (this.prodParam.hasYield && word === "yield") {
  9196. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  9197. return;
  9198. }
  9199. if (word === "await") {
  9200. if (this.prodParam.hasAwait) {
  9201. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9202. return;
  9203. }
  9204. if (this.state.awaitPos === -1 && (this.state.maybeInAsyncArrowHead || this.isAwaitAllowed())) {
  9205. this.state.awaitPos = this.state.start;
  9206. }
  9207. }
  9208. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  9209. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  9210. return;
  9211. }
  9212. if (checkKeywords && isKeyword(word)) {
  9213. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  9214. return;
  9215. }
  9216. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  9217. if (reservedTest(word, this.inModule)) {
  9218. if (!this.prodParam.hasAwait && word === "await") {
  9219. this.raise(startLoc, ErrorMessages.AwaitNotInAsyncFunction);
  9220. } else {
  9221. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  9222. }
  9223. }
  9224. }
  9225. isAwaitAllowed() {
  9226. if (this.scope.inFunction) return this.prodParam.hasAwait;
  9227. if (this.options.allowAwaitOutsideFunction) return true;
  9228. if (this.hasPlugin("topLevelAwait")) {
  9229. return this.inModule && this.prodParam.hasAwait;
  9230. }
  9231. return false;
  9232. }
  9233. parseAwait() {
  9234. const node = this.startNode();
  9235. this.next();
  9236. if (this.state.inParameters) {
  9237. this.raise(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  9238. } else if (this.state.awaitPos === -1) {
  9239. this.state.awaitPos = node.start;
  9240. }
  9241. if (this.eat(types.star)) {
  9242. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  9243. }
  9244. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  9245. 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)) {
  9246. this.ambiguousScriptDifferentAst = true;
  9247. } else {
  9248. this.sawUnambiguousESM = true;
  9249. }
  9250. }
  9251. if (!this.state.soloAwait) {
  9252. node.argument = this.parseMaybeUnary();
  9253. }
  9254. return this.finishNode(node, "AwaitExpression");
  9255. }
  9256. parseYield() {
  9257. const node = this.startNode();
  9258. if (this.state.inParameters) {
  9259. this.raise(node.start, ErrorMessages.YieldInParameter);
  9260. } else if (this.state.yieldPos === -1) {
  9261. this.state.yieldPos = node.start;
  9262. }
  9263. this.next();
  9264. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  9265. node.delegate = false;
  9266. node.argument = null;
  9267. } else {
  9268. node.delegate = this.eat(types.star);
  9269. node.argument = this.parseMaybeAssign();
  9270. }
  9271. return this.finishNode(node, "YieldExpression");
  9272. }
  9273. checkPipelineAtInfixOperator(left, leftStartPos) {
  9274. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  9275. if (left.type === "SequenceExpression") {
  9276. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  9277. }
  9278. }
  9279. }
  9280. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  9281. this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
  9282. return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
  9283. }
  9284. checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
  9285. if (this.match(types.arrow)) {
  9286. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  9287. } else if (childExpression.type === "SequenceExpression") {
  9288. this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
  9289. }
  9290. }
  9291. parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
  9292. const bodyNode = this.startNodeAt(startPos, startLoc);
  9293. const isSimpleReference = this.isSimpleReference(childExpression);
  9294. if (isSimpleReference) {
  9295. bodyNode.callee = childExpression;
  9296. } else {
  9297. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  9298. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  9299. }
  9300. bodyNode.expression = childExpression;
  9301. }
  9302. return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
  9303. }
  9304. isSimpleReference(expression) {
  9305. switch (expression.type) {
  9306. case "MemberExpression":
  9307. return !expression.computed && this.isSimpleReference(expression.object);
  9308. case "Identifier":
  9309. return true;
  9310. default:
  9311. return false;
  9312. }
  9313. }
  9314. withTopicPermittingContext(callback) {
  9315. const outerContextTopicState = this.state.topicContext;
  9316. this.state.topicContext = {
  9317. maxNumOfResolvableTopics: 1,
  9318. maxTopicIndex: null
  9319. };
  9320. try {
  9321. return callback();
  9322. } finally {
  9323. this.state.topicContext = outerContextTopicState;
  9324. }
  9325. }
  9326. withTopicForbiddingContext(callback) {
  9327. const outerContextTopicState = this.state.topicContext;
  9328. this.state.topicContext = {
  9329. maxNumOfResolvableTopics: 0,
  9330. maxTopicIndex: null
  9331. };
  9332. try {
  9333. return callback();
  9334. } finally {
  9335. this.state.topicContext = outerContextTopicState;
  9336. }
  9337. }
  9338. withSoloAwaitPermittingContext(callback) {
  9339. const outerContextSoloAwaitState = this.state.soloAwait;
  9340. this.state.soloAwait = true;
  9341. try {
  9342. return callback();
  9343. } finally {
  9344. this.state.soloAwait = outerContextSoloAwaitState;
  9345. }
  9346. }
  9347. allowInAnd(callback) {
  9348. const flags = this.prodParam.currentFlags();
  9349. const prodParamToSet = PARAM_IN & ~flags;
  9350. if (prodParamToSet) {
  9351. this.prodParam.enter(flags | PARAM_IN);
  9352. try {
  9353. return callback();
  9354. } finally {
  9355. this.prodParam.exit();
  9356. }
  9357. }
  9358. return callback();
  9359. }
  9360. disallowInAnd(callback) {
  9361. const flags = this.prodParam.currentFlags();
  9362. const prodParamToClear = PARAM_IN & flags;
  9363. if (prodParamToClear) {
  9364. this.prodParam.enter(flags & ~PARAM_IN);
  9365. try {
  9366. return callback();
  9367. } finally {
  9368. this.prodParam.exit();
  9369. }
  9370. }
  9371. return callback();
  9372. }
  9373. registerTopicReference() {
  9374. this.state.topicContext.maxTopicIndex = 0;
  9375. }
  9376. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  9377. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  9378. }
  9379. topicReferenceWasUsedInCurrentTopicContext() {
  9380. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  9381. }
  9382. parseFSharpPipelineBody(prec) {
  9383. const startPos = this.state.start;
  9384. const startLoc = this.state.startLoc;
  9385. this.state.potentialArrowAt = this.state.start;
  9386. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9387. this.state.inFSharpPipelineDirectBody = true;
  9388. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
  9389. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9390. return ret;
  9391. }
  9392. }
  9393. const loopLabel = {
  9394. kind: "loop"
  9395. },
  9396. switchLabel = {
  9397. kind: "switch"
  9398. };
  9399. const FUNC_NO_FLAGS = 0b000,
  9400. FUNC_STATEMENT = 0b001,
  9401. FUNC_HANGING_STATEMENT = 0b010,
  9402. FUNC_NULLABLE_ID = 0b100;
  9403. const loneSurrogate = /[\uD800-\uDFFF]/u;
  9404. class StatementParser extends ExpressionParser {
  9405. parseTopLevel(file, program) {
  9406. program.sourceType = this.options.sourceType;
  9407. program.interpreter = this.parseInterpreterDirective();
  9408. this.parseBlockBody(program, true, true, types.eof);
  9409. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9410. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  9411. const [name] = _Array$from[_i];
  9412. const pos = this.scope.undefinedExports.get(name);
  9413. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  9414. }
  9415. }
  9416. file.program = this.finishNode(program, "Program");
  9417. file.comments = this.state.comments;
  9418. if (this.options.tokens) file.tokens = this.tokens;
  9419. return this.finishNode(file, "File");
  9420. }
  9421. stmtToDirective(stmt) {
  9422. const expr = stmt.expression;
  9423. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9424. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9425. const raw = this.input.slice(expr.start, expr.end);
  9426. const val = directiveLiteral.value = raw.slice(1, -1);
  9427. this.addExtra(directiveLiteral, "raw", raw);
  9428. this.addExtra(directiveLiteral, "rawValue", val);
  9429. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9430. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9431. }
  9432. parseInterpreterDirective() {
  9433. if (!this.match(types.interpreterDirective)) {
  9434. return null;
  9435. }
  9436. const node = this.startNode();
  9437. node.value = this.state.value;
  9438. this.next();
  9439. return this.finishNode(node, "InterpreterDirective");
  9440. }
  9441. isLet(context) {
  9442. if (!this.isContextual("let")) {
  9443. return false;
  9444. }
  9445. const next = this.nextTokenStart();
  9446. const nextCh = this.input.charCodeAt(next);
  9447. if (nextCh === 91) return true;
  9448. if (context) return false;
  9449. if (nextCh === 123) return true;
  9450. if (isIdentifierStart(nextCh)) {
  9451. let pos = next + 1;
  9452. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9453. ++pos;
  9454. }
  9455. const ident = this.input.slice(next, pos);
  9456. if (!keywordRelationalOperator.test(ident)) return true;
  9457. }
  9458. return false;
  9459. }
  9460. parseStatement(context, topLevel) {
  9461. if (this.match(types.at)) {
  9462. this.parseDecorators(true);
  9463. }
  9464. return this.parseStatementContent(context, topLevel);
  9465. }
  9466. parseStatementContent(context, topLevel) {
  9467. let starttype = this.state.type;
  9468. const node = this.startNode();
  9469. let kind;
  9470. if (this.isLet(context)) {
  9471. starttype = types._var;
  9472. kind = "let";
  9473. }
  9474. switch (starttype) {
  9475. case types._break:
  9476. case types._continue:
  9477. return this.parseBreakContinueStatement(node, starttype.keyword);
  9478. case types._debugger:
  9479. return this.parseDebuggerStatement(node);
  9480. case types._do:
  9481. return this.parseDoStatement(node);
  9482. case types._for:
  9483. return this.parseForStatement(node);
  9484. case types._function:
  9485. if (this.lookaheadCharCode() === 46) break;
  9486. if (context) {
  9487. if (this.state.strict) {
  9488. this.raise(this.state.start, ErrorMessages.StrictFunction);
  9489. } else if (context !== "if" && context !== "label") {
  9490. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  9491. }
  9492. }
  9493. return this.parseFunctionStatement(node, false, !context);
  9494. case types._class:
  9495. if (context) this.unexpected();
  9496. return this.parseClass(node, true);
  9497. case types._if:
  9498. return this.parseIfStatement(node);
  9499. case types._return:
  9500. return this.parseReturnStatement(node);
  9501. case types._switch:
  9502. return this.parseSwitchStatement(node);
  9503. case types._throw:
  9504. return this.parseThrowStatement(node);
  9505. case types._try:
  9506. return this.parseTryStatement(node);
  9507. case types._const:
  9508. case types._var:
  9509. kind = kind || this.state.value;
  9510. if (context && kind !== "var") {
  9511. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  9512. }
  9513. return this.parseVarStatement(node, kind);
  9514. case types._while:
  9515. return this.parseWhileStatement(node);
  9516. case types._with:
  9517. return this.parseWithStatement(node);
  9518. case types.braceL:
  9519. return this.parseBlock();
  9520. case types.semi:
  9521. return this.parseEmptyStatement(node);
  9522. case types._import:
  9523. {
  9524. const nextTokenCharCode = this.lookaheadCharCode();
  9525. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  9526. break;
  9527. }
  9528. }
  9529. case types._export:
  9530. {
  9531. if (!this.options.allowImportExportEverywhere && !topLevel) {
  9532. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  9533. }
  9534. this.next();
  9535. let result;
  9536. if (starttype === types._import) {
  9537. result = this.parseImport(node);
  9538. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  9539. this.sawUnambiguousESM = true;
  9540. }
  9541. } else {
  9542. result = this.parseExport(node);
  9543. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  9544. this.sawUnambiguousESM = true;
  9545. }
  9546. }
  9547. this.assertModuleNodeAllowed(node);
  9548. return result;
  9549. }
  9550. default:
  9551. {
  9552. if (this.isAsyncFunction()) {
  9553. if (context) {
  9554. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  9555. }
  9556. this.next();
  9557. return this.parseFunctionStatement(node, true, !context);
  9558. }
  9559. }
  9560. }
  9561. const maybeName = this.state.value;
  9562. const expr = this.parseExpression();
  9563. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  9564. return this.parseLabeledStatement(node, maybeName, expr, context);
  9565. } else {
  9566. return this.parseExpressionStatement(node, expr);
  9567. }
  9568. }
  9569. assertModuleNodeAllowed(node) {
  9570. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  9571. this.raiseWithData(node.start, {
  9572. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9573. }, ErrorMessages.ImportOutsideModule);
  9574. }
  9575. }
  9576. takeDecorators(node) {
  9577. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9578. if (decorators.length) {
  9579. node.decorators = decorators;
  9580. this.resetStartLocationFromNode(node, decorators[0]);
  9581. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  9582. }
  9583. }
  9584. canHaveLeadingDecorator() {
  9585. return this.match(types._class);
  9586. }
  9587. parseDecorators(allowExport) {
  9588. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9589. while (this.match(types.at)) {
  9590. const decorator = this.parseDecorator();
  9591. currentContextDecorators.push(decorator);
  9592. }
  9593. if (this.match(types._export)) {
  9594. if (!allowExport) {
  9595. this.unexpected();
  9596. }
  9597. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9598. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  9599. }
  9600. } else if (!this.canHaveLeadingDecorator()) {
  9601. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  9602. }
  9603. }
  9604. parseDecorator() {
  9605. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  9606. const node = this.startNode();
  9607. this.next();
  9608. if (this.hasPlugin("decorators")) {
  9609. this.state.decoratorStack.push([]);
  9610. const startPos = this.state.start;
  9611. const startLoc = this.state.startLoc;
  9612. let expr;
  9613. if (this.eat(types.parenL)) {
  9614. expr = this.parseExpression();
  9615. this.expect(types.parenR);
  9616. } else {
  9617. expr = this.parseIdentifier(false);
  9618. while (this.eat(types.dot)) {
  9619. const node = this.startNodeAt(startPos, startLoc);
  9620. node.object = expr;
  9621. node.property = this.parseIdentifier(true);
  9622. node.computed = false;
  9623. expr = this.finishNode(node, "MemberExpression");
  9624. }
  9625. }
  9626. node.expression = this.parseMaybeDecoratorArguments(expr);
  9627. this.state.decoratorStack.pop();
  9628. } else {
  9629. node.expression = this.parseExprSubscripts();
  9630. }
  9631. return this.finishNode(node, "Decorator");
  9632. }
  9633. parseMaybeDecoratorArguments(expr) {
  9634. if (this.eat(types.parenL)) {
  9635. const node = this.startNodeAtNode(expr);
  9636. node.callee = expr;
  9637. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  9638. this.toReferencedList(node.arguments);
  9639. return this.finishNode(node, "CallExpression");
  9640. }
  9641. return expr;
  9642. }
  9643. parseBreakContinueStatement(node, keyword) {
  9644. const isBreak = keyword === "break";
  9645. this.next();
  9646. if (this.isLineTerminator()) {
  9647. node.label = null;
  9648. } else {
  9649. node.label = this.parseIdentifier();
  9650. this.semicolon();
  9651. }
  9652. this.verifyBreakContinue(node, keyword);
  9653. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  9654. }
  9655. verifyBreakContinue(node, keyword) {
  9656. const isBreak = keyword === "break";
  9657. let i;
  9658. for (i = 0; i < this.state.labels.length; ++i) {
  9659. const lab = this.state.labels[i];
  9660. if (node.label == null || lab.name === node.label.name) {
  9661. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  9662. if (node.label && isBreak) break;
  9663. }
  9664. }
  9665. if (i === this.state.labels.length) {
  9666. this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
  9667. }
  9668. }
  9669. parseDebuggerStatement(node) {
  9670. this.next();
  9671. this.semicolon();
  9672. return this.finishNode(node, "DebuggerStatement");
  9673. }
  9674. parseHeaderExpression() {
  9675. this.expect(types.parenL);
  9676. const val = this.parseExpression();
  9677. this.expect(types.parenR);
  9678. return val;
  9679. }
  9680. parseDoStatement(node) {
  9681. this.next();
  9682. this.state.labels.push(loopLabel);
  9683. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  9684. this.state.labels.pop();
  9685. this.expect(types._while);
  9686. node.test = this.parseHeaderExpression();
  9687. this.eat(types.semi);
  9688. return this.finishNode(node, "DoWhileStatement");
  9689. }
  9690. parseForStatement(node) {
  9691. this.next();
  9692. this.state.labels.push(loopLabel);
  9693. let awaitAt = -1;
  9694. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  9695. awaitAt = this.state.lastTokStart;
  9696. }
  9697. this.scope.enter(SCOPE_OTHER);
  9698. this.expect(types.parenL);
  9699. if (this.match(types.semi)) {
  9700. if (awaitAt > -1) {
  9701. this.unexpected(awaitAt);
  9702. }
  9703. return this.parseFor(node, null);
  9704. }
  9705. const isLet = this.isLet();
  9706. if (this.match(types._var) || this.match(types._const) || isLet) {
  9707. const init = this.startNode();
  9708. const kind = isLet ? "let" : this.state.value;
  9709. this.next();
  9710. this.parseVar(init, true, kind);
  9711. this.finishNode(init, "VariableDeclaration");
  9712. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  9713. return this.parseForIn(node, init, awaitAt);
  9714. }
  9715. if (awaitAt > -1) {
  9716. this.unexpected(awaitAt);
  9717. }
  9718. return this.parseFor(node, init);
  9719. }
  9720. const refExpressionErrors = new ExpressionErrors();
  9721. const init = this.parseExpression(true, refExpressionErrors);
  9722. if (this.match(types._in) || this.isContextual("of")) {
  9723. this.toAssignable(init);
  9724. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  9725. this.checkLVal(init, undefined, undefined, description);
  9726. return this.parseForIn(node, init, awaitAt);
  9727. } else {
  9728. this.checkExpressionErrors(refExpressionErrors, true);
  9729. }
  9730. if (awaitAt > -1) {
  9731. this.unexpected(awaitAt);
  9732. }
  9733. return this.parseFor(node, init);
  9734. }
  9735. parseFunctionStatement(node, isAsync, declarationPosition) {
  9736. this.next();
  9737. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  9738. }
  9739. parseIfStatement(node) {
  9740. this.next();
  9741. node.test = this.parseHeaderExpression();
  9742. node.consequent = this.parseStatement("if");
  9743. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  9744. return this.finishNode(node, "IfStatement");
  9745. }
  9746. parseReturnStatement(node) {
  9747. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  9748. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  9749. }
  9750. this.next();
  9751. if (this.isLineTerminator()) {
  9752. node.argument = null;
  9753. } else {
  9754. node.argument = this.parseExpression();
  9755. this.semicolon();
  9756. }
  9757. return this.finishNode(node, "ReturnStatement");
  9758. }
  9759. parseSwitchStatement(node) {
  9760. this.next();
  9761. node.discriminant = this.parseHeaderExpression();
  9762. const cases = node.cases = [];
  9763. this.expect(types.braceL);
  9764. this.state.labels.push(switchLabel);
  9765. this.scope.enter(SCOPE_OTHER);
  9766. let cur;
  9767. for (let sawDefault; !this.match(types.braceR);) {
  9768. if (this.match(types._case) || this.match(types._default)) {
  9769. const isCase = this.match(types._case);
  9770. if (cur) this.finishNode(cur, "SwitchCase");
  9771. cases.push(cur = this.startNode());
  9772. cur.consequent = [];
  9773. this.next();
  9774. if (isCase) {
  9775. cur.test = this.parseExpression();
  9776. } else {
  9777. if (sawDefault) {
  9778. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  9779. }
  9780. sawDefault = true;
  9781. cur.test = null;
  9782. }
  9783. this.expect(types.colon);
  9784. } else {
  9785. if (cur) {
  9786. cur.consequent.push(this.parseStatement(null));
  9787. } else {
  9788. this.unexpected();
  9789. }
  9790. }
  9791. }
  9792. this.scope.exit();
  9793. if (cur) this.finishNode(cur, "SwitchCase");
  9794. this.next();
  9795. this.state.labels.pop();
  9796. return this.finishNode(node, "SwitchStatement");
  9797. }
  9798. parseThrowStatement(node) {
  9799. this.next();
  9800. if (this.hasPrecedingLineBreak()) {
  9801. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  9802. }
  9803. node.argument = this.parseExpression();
  9804. this.semicolon();
  9805. return this.finishNode(node, "ThrowStatement");
  9806. }
  9807. parseCatchClauseParam() {
  9808. const param = this.parseBindingAtom();
  9809. const simple = param.type === "Identifier";
  9810. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9811. this.checkLVal(param, BIND_LEXICAL, null, "catch clause");
  9812. return param;
  9813. }
  9814. parseTryStatement(node) {
  9815. this.next();
  9816. node.block = this.parseBlock();
  9817. node.handler = null;
  9818. if (this.match(types._catch)) {
  9819. const clause = this.startNode();
  9820. this.next();
  9821. if (this.match(types.parenL)) {
  9822. this.expect(types.parenL);
  9823. clause.param = this.parseCatchClauseParam();
  9824. this.expect(types.parenR);
  9825. } else {
  9826. clause.param = null;
  9827. this.scope.enter(SCOPE_OTHER);
  9828. }
  9829. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9830. this.scope.exit();
  9831. node.handler = this.finishNode(clause, "CatchClause");
  9832. }
  9833. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9834. if (!node.handler && !node.finalizer) {
  9835. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  9836. }
  9837. return this.finishNode(node, "TryStatement");
  9838. }
  9839. parseVarStatement(node, kind) {
  9840. this.next();
  9841. this.parseVar(node, false, kind);
  9842. this.semicolon();
  9843. return this.finishNode(node, "VariableDeclaration");
  9844. }
  9845. parseWhileStatement(node) {
  9846. this.next();
  9847. node.test = this.parseHeaderExpression();
  9848. this.state.labels.push(loopLabel);
  9849. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9850. this.state.labels.pop();
  9851. return this.finishNode(node, "WhileStatement");
  9852. }
  9853. parseWithStatement(node) {
  9854. if (this.state.strict) {
  9855. this.raise(this.state.start, ErrorMessages.StrictWith);
  9856. }
  9857. this.next();
  9858. node.object = this.parseHeaderExpression();
  9859. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9860. return this.finishNode(node, "WithStatement");
  9861. }
  9862. parseEmptyStatement(node) {
  9863. this.next();
  9864. return this.finishNode(node, "EmptyStatement");
  9865. }
  9866. parseLabeledStatement(node, maybeName, expr, context) {
  9867. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9868. const label = _this$state$labels[_i2];
  9869. if (label.name === maybeName) {
  9870. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  9871. }
  9872. }
  9873. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9874. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9875. const label = this.state.labels[i];
  9876. if (label.statementStart === node.start) {
  9877. label.statementStart = this.state.start;
  9878. label.kind = kind;
  9879. } else {
  9880. break;
  9881. }
  9882. }
  9883. this.state.labels.push({
  9884. name: maybeName,
  9885. kind: kind,
  9886. statementStart: this.state.start
  9887. });
  9888. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9889. this.state.labels.pop();
  9890. node.label = expr;
  9891. return this.finishNode(node, "LabeledStatement");
  9892. }
  9893. parseExpressionStatement(node, expr) {
  9894. node.expression = expr;
  9895. this.semicolon();
  9896. return this.finishNode(node, "ExpressionStatement");
  9897. }
  9898. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  9899. const node = this.startNode();
  9900. this.expect(types.braceL);
  9901. if (createNewLexicalScope) {
  9902. this.scope.enter(SCOPE_OTHER);
  9903. }
  9904. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  9905. if (createNewLexicalScope) {
  9906. this.scope.exit();
  9907. }
  9908. return this.finishNode(node, "BlockStatement");
  9909. }
  9910. isValidDirective(stmt) {
  9911. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9912. }
  9913. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  9914. const body = node.body = [];
  9915. const directives = node.directives = [];
  9916. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  9917. }
  9918. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  9919. const octalPositions = [];
  9920. const oldStrict = this.state.strict;
  9921. let hasStrictModeDirective = false;
  9922. let parsedNonDirective = false;
  9923. while (!this.match(end)) {
  9924. if (!parsedNonDirective && this.state.octalPositions.length) {
  9925. octalPositions.push(...this.state.octalPositions);
  9926. }
  9927. const stmt = this.parseStatement(null, topLevel);
  9928. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  9929. const directive = this.stmtToDirective(stmt);
  9930. directives.push(directive);
  9931. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  9932. hasStrictModeDirective = true;
  9933. this.setStrict(true);
  9934. }
  9935. continue;
  9936. }
  9937. parsedNonDirective = true;
  9938. body.push(stmt);
  9939. }
  9940. if (this.state.strict && octalPositions.length) {
  9941. for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
  9942. const pos = octalPositions[_i3];
  9943. this.raise(pos, ErrorMessages.StrictOctalLiteral);
  9944. }
  9945. }
  9946. if (afterBlockParse) {
  9947. afterBlockParse.call(this, hasStrictModeDirective);
  9948. }
  9949. if (!oldStrict) {
  9950. this.setStrict(false);
  9951. }
  9952. this.next();
  9953. }
  9954. parseFor(node, init) {
  9955. node.init = init;
  9956. this.expect(types.semi);
  9957. node.test = this.match(types.semi) ? null : this.parseExpression();
  9958. this.expect(types.semi);
  9959. node.update = this.match(types.parenR) ? null : this.parseExpression();
  9960. this.expect(types.parenR);
  9961. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9962. this.scope.exit();
  9963. this.state.labels.pop();
  9964. return this.finishNode(node, "ForStatement");
  9965. }
  9966. parseForIn(node, init, awaitAt) {
  9967. const isForIn = this.match(types._in);
  9968. this.next();
  9969. if (isForIn) {
  9970. if (awaitAt > -1) this.unexpected(awaitAt);
  9971. } else {
  9972. node.await = awaitAt > -1;
  9973. }
  9974. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  9975. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  9976. } else if (init.type === "AssignmentPattern") {
  9977. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  9978. }
  9979. node.left = init;
  9980. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  9981. this.expect(types.parenR);
  9982. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9983. this.scope.exit();
  9984. this.state.labels.pop();
  9985. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  9986. }
  9987. parseVar(node, isFor, kind) {
  9988. const declarations = node.declarations = [];
  9989. const isTypescript = this.hasPlugin("typescript");
  9990. node.kind = kind;
  9991. for (;;) {
  9992. const decl = this.startNode();
  9993. this.parseVarId(decl, kind);
  9994. if (this.eat(types.eq)) {
  9995. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  9996. } else {
  9997. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  9998. if (!isTypescript) {
  9999. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  10000. }
  10001. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  10002. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  10003. }
  10004. decl.init = null;
  10005. }
  10006. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  10007. if (!this.eat(types.comma)) break;
  10008. }
  10009. return node;
  10010. }
  10011. parseVarId(decl, kind) {
  10012. decl.id = this.parseBindingAtom();
  10013. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var");
  10014. }
  10015. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  10016. const isStatement = statement & FUNC_STATEMENT;
  10017. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  10018. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  10019. this.initFunction(node, isAsync);
  10020. if (this.match(types.star) && isHangingStatement) {
  10021. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  10022. }
  10023. node.generator = this.eat(types.star);
  10024. if (isStatement) {
  10025. node.id = this.parseFunctionId(requireId);
  10026. }
  10027. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10028. const oldYieldPos = this.state.yieldPos;
  10029. const oldAwaitPos = this.state.awaitPos;
  10030. this.state.maybeInArrowParameters = false;
  10031. this.state.yieldPos = -1;
  10032. this.state.awaitPos = -1;
  10033. this.scope.enter(SCOPE_FUNCTION);
  10034. this.prodParam.enter(functionFlags(isAsync, node.generator));
  10035. if (!isStatement) {
  10036. node.id = this.parseFunctionId();
  10037. }
  10038. this.parseFunctionParams(node, false);
  10039. this.withTopicForbiddingContext(() => {
  10040. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  10041. });
  10042. this.prodParam.exit();
  10043. this.scope.exit();
  10044. if (isStatement && !isHangingStatement) {
  10045. this.registerFunctionStatementId(node);
  10046. }
  10047. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10048. this.state.yieldPos = oldYieldPos;
  10049. this.state.awaitPos = oldAwaitPos;
  10050. return node;
  10051. }
  10052. parseFunctionId(requireId) {
  10053. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  10054. }
  10055. parseFunctionParams(node, allowModifiers) {
  10056. const oldInParameters = this.state.inParameters;
  10057. this.state.inParameters = true;
  10058. this.expect(types.parenL);
  10059. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  10060. this.state.inParameters = oldInParameters;
  10061. this.checkYieldAwaitInDefaultParams();
  10062. }
  10063. registerFunctionStatementId(node) {
  10064. if (!node.id) return;
  10065. 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);
  10066. }
  10067. parseClass(node, isStatement, optionalId) {
  10068. this.next();
  10069. this.takeDecorators(node);
  10070. const oldStrict = this.state.strict;
  10071. this.state.strict = true;
  10072. this.parseClassId(node, isStatement, optionalId);
  10073. this.parseClassSuper(node);
  10074. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  10075. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  10076. }
  10077. isClassProperty() {
  10078. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  10079. }
  10080. isClassMethod() {
  10081. return this.match(types.parenL);
  10082. }
  10083. isNonstaticConstructor(method) {
  10084. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  10085. }
  10086. parseClassBody(constructorAllowsSuper, oldStrict) {
  10087. this.classScope.enter();
  10088. const state = {
  10089. constructorAllowsSuper,
  10090. hadConstructor: false,
  10091. hadStaticBlock: false
  10092. };
  10093. let decorators = [];
  10094. const classBody = this.startNode();
  10095. classBody.body = [];
  10096. this.expect(types.braceL);
  10097. this.withTopicForbiddingContext(() => {
  10098. while (!this.match(types.braceR)) {
  10099. if (this.eat(types.semi)) {
  10100. if (decorators.length > 0) {
  10101. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  10102. }
  10103. continue;
  10104. }
  10105. if (this.match(types.at)) {
  10106. decorators.push(this.parseDecorator());
  10107. continue;
  10108. }
  10109. const member = this.startNode();
  10110. if (decorators.length) {
  10111. member.decorators = decorators;
  10112. this.resetStartLocationFromNode(member, decorators[0]);
  10113. decorators = [];
  10114. }
  10115. this.parseClassMember(classBody, member, state);
  10116. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  10117. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  10118. }
  10119. }
  10120. });
  10121. this.state.strict = oldStrict;
  10122. this.next();
  10123. if (decorators.length) {
  10124. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  10125. }
  10126. this.classScope.exit();
  10127. return this.finishNode(classBody, "ClassBody");
  10128. }
  10129. parseClassMemberFromModifier(classBody, member) {
  10130. const key = this.parseIdentifier(true);
  10131. if (this.isClassMethod()) {
  10132. const method = member;
  10133. method.kind = "method";
  10134. method.computed = false;
  10135. method.key = key;
  10136. method.static = false;
  10137. this.pushClassMethod(classBody, method, false, false, false, false);
  10138. return true;
  10139. } else if (this.isClassProperty()) {
  10140. const prop = member;
  10141. prop.computed = false;
  10142. prop.key = key;
  10143. prop.static = false;
  10144. classBody.body.push(this.parseClassProperty(prop));
  10145. return true;
  10146. }
  10147. return false;
  10148. }
  10149. parseClassMember(classBody, member, state) {
  10150. const isStatic = this.isContextual("static");
  10151. if (isStatic) {
  10152. if (this.parseClassMemberFromModifier(classBody, member)) {
  10153. return;
  10154. }
  10155. if (this.eat(types.braceL)) {
  10156. this.parseClassStaticBlock(classBody, member, state);
  10157. return;
  10158. }
  10159. }
  10160. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  10161. }
  10162. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  10163. const publicMethod = member;
  10164. const privateMethod = member;
  10165. const publicProp = member;
  10166. const privateProp = member;
  10167. const method = publicMethod;
  10168. const publicMember = publicMethod;
  10169. member.static = isStatic;
  10170. if (this.eat(types.star)) {
  10171. method.kind = "method";
  10172. this.parseClassElementName(method);
  10173. if (method.key.type === "PrivateName") {
  10174. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  10175. return;
  10176. }
  10177. if (this.isNonstaticConstructor(publicMethod)) {
  10178. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  10179. }
  10180. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  10181. return;
  10182. }
  10183. const containsEsc = this.state.containsEsc;
  10184. const key = this.parseClassElementName(member);
  10185. const isPrivate = key.type === "PrivateName";
  10186. const isSimple = key.type === "Identifier";
  10187. const maybeQuestionTokenStart = this.state.start;
  10188. this.parsePostMemberNameModifiers(publicMember);
  10189. if (this.isClassMethod()) {
  10190. method.kind = "method";
  10191. if (isPrivate) {
  10192. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10193. return;
  10194. }
  10195. const isConstructor = this.isNonstaticConstructor(publicMethod);
  10196. let allowsDirectSuper = false;
  10197. if (isConstructor) {
  10198. publicMethod.kind = "constructor";
  10199. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  10200. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  10201. }
  10202. state.hadConstructor = true;
  10203. allowsDirectSuper = state.constructorAllowsSuper;
  10204. }
  10205. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  10206. } else if (this.isClassProperty()) {
  10207. if (isPrivate) {
  10208. this.pushClassPrivateProperty(classBody, privateProp);
  10209. } else {
  10210. this.pushClassProperty(classBody, publicProp);
  10211. }
  10212. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  10213. const isGenerator = this.eat(types.star);
  10214. if (publicMember.optional) {
  10215. this.unexpected(maybeQuestionTokenStart);
  10216. }
  10217. method.kind = "method";
  10218. this.parseClassElementName(method);
  10219. this.parsePostMemberNameModifiers(publicMember);
  10220. if (method.key.type === "PrivateName") {
  10221. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  10222. } else {
  10223. if (this.isNonstaticConstructor(publicMethod)) {
  10224. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  10225. }
  10226. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  10227. }
  10228. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  10229. method.kind = key.name;
  10230. this.parseClassElementName(publicMethod);
  10231. if (method.key.type === "PrivateName") {
  10232. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10233. } else {
  10234. if (this.isNonstaticConstructor(publicMethod)) {
  10235. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  10236. }
  10237. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  10238. }
  10239. this.checkGetterSetterParams(publicMethod);
  10240. } else if (this.isLineTerminator()) {
  10241. if (isPrivate) {
  10242. this.pushClassPrivateProperty(classBody, privateProp);
  10243. } else {
  10244. this.pushClassProperty(classBody, publicProp);
  10245. }
  10246. } else {
  10247. this.unexpected();
  10248. }
  10249. }
  10250. parseClassElementName(member) {
  10251. const key = this.parsePropertyName(member, true);
  10252. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  10253. this.raise(key.start, ErrorMessages.StaticPrototype);
  10254. }
  10255. if (key.type === "PrivateName" && key.id.name === "constructor") {
  10256. this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
  10257. }
  10258. return key;
  10259. }
  10260. parseClassStaticBlock(classBody, member, state) {
  10261. var _member$decorators;
  10262. this.expectPlugin("classStaticBlock", member.start);
  10263. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10264. const oldLabels = this.state.labels;
  10265. this.state.labels = [];
  10266. this.prodParam.enter(PARAM);
  10267. const body = member.body = [];
  10268. this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
  10269. this.prodParam.exit();
  10270. this.scope.exit();
  10271. this.state.labels = oldLabels;
  10272. classBody.body.push(this.finishNode(member, "StaticBlock"));
  10273. if (state.hadStaticBlock) {
  10274. this.raise(member.start, ErrorMessages.DuplicateStaticBlock);
  10275. }
  10276. if ((_member$decorators = member.decorators) == null ? void 0 : _member$decorators.length) {
  10277. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  10278. }
  10279. state.hadStaticBlock = true;
  10280. }
  10281. pushClassProperty(classBody, prop) {
  10282. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  10283. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  10284. }
  10285. classBody.body.push(this.parseClassProperty(prop));
  10286. }
  10287. pushClassPrivateProperty(classBody, prop) {
  10288. this.expectPlugin("classPrivateProperties", prop.key.start);
  10289. const node = this.parseClassPrivateProperty(prop);
  10290. classBody.body.push(node);
  10291. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  10292. }
  10293. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  10294. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  10295. }
  10296. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  10297. this.expectPlugin("classPrivateMethods", method.key.start);
  10298. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  10299. classBody.body.push(node);
  10300. 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;
  10301. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  10302. }
  10303. parsePostMemberNameModifiers(methodOrProp) {}
  10304. parseClassPrivateProperty(node) {
  10305. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10306. this.prodParam.enter(PARAM);
  10307. node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
  10308. this.semicolon();
  10309. this.prodParam.exit();
  10310. this.scope.exit();
  10311. return this.finishNode(node, "ClassPrivateProperty");
  10312. }
  10313. parseClassProperty(node) {
  10314. if (!node.typeAnnotation) {
  10315. this.expectPlugin("classProperties");
  10316. }
  10317. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10318. this.prodParam.enter(PARAM);
  10319. if (this.match(types.eq)) {
  10320. this.expectPlugin("classProperties");
  10321. this.next();
  10322. node.value = this.parseMaybeAssignAllowIn();
  10323. } else {
  10324. node.value = null;
  10325. }
  10326. this.semicolon();
  10327. this.prodParam.exit();
  10328. this.scope.exit();
  10329. return this.finishNode(node, "ClassProperty");
  10330. }
  10331. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  10332. if (this.match(types.name)) {
  10333. node.id = this.parseIdentifier();
  10334. if (isStatement) {
  10335. this.checkLVal(node.id, bindingType, undefined, "class name");
  10336. }
  10337. } else {
  10338. if (optionalId || !isStatement) {
  10339. node.id = null;
  10340. } else {
  10341. this.unexpected(null, ErrorMessages.MissingClassName);
  10342. }
  10343. }
  10344. }
  10345. parseClassSuper(node) {
  10346. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  10347. }
  10348. parseExport(node) {
  10349. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  10350. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  10351. const hasStar = parseAfterDefault && this.eatExportStar(node);
  10352. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  10353. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  10354. const isFromRequired = hasDefault || hasStar;
  10355. if (hasStar && !hasNamespace) {
  10356. if (hasDefault) this.unexpected();
  10357. this.parseExportFrom(node, true);
  10358. return this.finishNode(node, "ExportAllDeclaration");
  10359. }
  10360. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  10361. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  10362. throw this.unexpected(null, types.braceL);
  10363. }
  10364. let hasDeclaration;
  10365. if (isFromRequired || hasSpecifiers) {
  10366. hasDeclaration = false;
  10367. this.parseExportFrom(node, isFromRequired);
  10368. } else {
  10369. hasDeclaration = this.maybeParseExportDeclaration(node);
  10370. }
  10371. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  10372. this.checkExport(node, true, false, !!node.source);
  10373. return this.finishNode(node, "ExportNamedDeclaration");
  10374. }
  10375. if (this.eat(types._default)) {
  10376. node.declaration = this.parseExportDefaultExpression();
  10377. this.checkExport(node, true, true);
  10378. return this.finishNode(node, "ExportDefaultDeclaration");
  10379. }
  10380. throw this.unexpected(null, types.braceL);
  10381. }
  10382. eatExportStar(node) {
  10383. return this.eat(types.star);
  10384. }
  10385. maybeParseExportDefaultSpecifier(node) {
  10386. if (this.isExportDefaultSpecifier()) {
  10387. this.expectPlugin("exportDefaultFrom");
  10388. const specifier = this.startNode();
  10389. specifier.exported = this.parseIdentifier(true);
  10390. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10391. return true;
  10392. }
  10393. return false;
  10394. }
  10395. maybeParseExportNamespaceSpecifier(node) {
  10396. if (this.isContextual("as")) {
  10397. if (!node.specifiers) node.specifiers = [];
  10398. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  10399. this.next();
  10400. specifier.exported = this.parseModuleExportName();
  10401. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  10402. return true;
  10403. }
  10404. return false;
  10405. }
  10406. maybeParseExportNamedSpecifiers(node) {
  10407. if (this.match(types.braceL)) {
  10408. if (!node.specifiers) node.specifiers = [];
  10409. node.specifiers.push(...this.parseExportSpecifiers());
  10410. node.source = null;
  10411. node.declaration = null;
  10412. return true;
  10413. }
  10414. return false;
  10415. }
  10416. maybeParseExportDeclaration(node) {
  10417. if (this.shouldParseExportDeclaration()) {
  10418. node.specifiers = [];
  10419. node.source = null;
  10420. node.declaration = this.parseExportDeclaration(node);
  10421. return true;
  10422. }
  10423. return false;
  10424. }
  10425. isAsyncFunction() {
  10426. if (!this.isContextual("async")) return false;
  10427. const next = this.nextTokenStart();
  10428. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10429. }
  10430. parseExportDefaultExpression() {
  10431. const expr = this.startNode();
  10432. const isAsync = this.isAsyncFunction();
  10433. if (this.match(types._function) || isAsync) {
  10434. this.next();
  10435. if (isAsync) {
  10436. this.next();
  10437. }
  10438. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10439. } else if (this.match(types._class)) {
  10440. return this.parseClass(expr, true, true);
  10441. } else if (this.match(types.at)) {
  10442. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10443. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10444. }
  10445. this.parseDecorators(false);
  10446. return this.parseClass(expr, true, true);
  10447. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10448. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  10449. } else {
  10450. const res = this.parseMaybeAssignAllowIn();
  10451. this.semicolon();
  10452. return res;
  10453. }
  10454. }
  10455. parseExportDeclaration(node) {
  10456. return this.parseStatement(null);
  10457. }
  10458. isExportDefaultSpecifier() {
  10459. if (this.match(types.name)) {
  10460. const value = this.state.value;
  10461. if (value === "async" && !this.state.containsEsc || value === "let") {
  10462. return false;
  10463. }
  10464. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  10465. const l = this.lookahead();
  10466. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  10467. this.expectOnePlugin(["flow", "typescript"]);
  10468. return false;
  10469. }
  10470. }
  10471. } else if (!this.match(types._default)) {
  10472. return false;
  10473. }
  10474. const next = this.nextTokenStart();
  10475. const hasFrom = this.isUnparsedContextual(next, "from");
  10476. if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
  10477. return true;
  10478. }
  10479. if (this.match(types._default) && hasFrom) {
  10480. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  10481. return nextAfterFrom === 34 || nextAfterFrom === 39;
  10482. }
  10483. return false;
  10484. }
  10485. parseExportFrom(node, expect) {
  10486. if (this.eatContextual("from")) {
  10487. node.source = this.parseImportSource();
  10488. this.checkExport(node);
  10489. } else {
  10490. if (expect) {
  10491. this.unexpected();
  10492. } else {
  10493. node.source = null;
  10494. }
  10495. }
  10496. this.semicolon();
  10497. }
  10498. shouldParseExportDeclaration() {
  10499. if (this.match(types.at)) {
  10500. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  10501. if (this.hasPlugin("decorators")) {
  10502. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10503. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10504. } else {
  10505. return true;
  10506. }
  10507. }
  10508. }
  10509. 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();
  10510. }
  10511. checkExport(node, checkNames, isDefault, isFrom) {
  10512. if (checkNames) {
  10513. if (isDefault) {
  10514. this.checkDuplicateExports(node, "default");
  10515. if (this.hasPlugin("exportDefaultFrom")) {
  10516. var _declaration$extra;
  10517. const declaration = node.declaration;
  10518. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) == null ? void 0 : _declaration$extra.parenthesized)) {
  10519. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  10520. }
  10521. }
  10522. } else if (node.specifiers && node.specifiers.length) {
  10523. for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
  10524. const specifier = _node$specifiers[_i4];
  10525. const {
  10526. exported
  10527. } = specifier;
  10528. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  10529. this.checkDuplicateExports(specifier, exportedName);
  10530. if (!isFrom && specifier.local) {
  10531. const {
  10532. local
  10533. } = specifier;
  10534. if (local.type === "StringLiteral") {
  10535. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.extra.raw, exportedName);
  10536. } else {
  10537. this.checkReservedWord(local.name, local.start, true, false);
  10538. this.scope.checkLocalExport(local);
  10539. }
  10540. }
  10541. }
  10542. } else if (node.declaration) {
  10543. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  10544. const id = node.declaration.id;
  10545. if (!id) throw new Error("Assertion failure");
  10546. this.checkDuplicateExports(node, id.name);
  10547. } else if (node.declaration.type === "VariableDeclaration") {
  10548. for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
  10549. const declaration = _node$declaration$dec[_i5];
  10550. this.checkDeclaration(declaration.id);
  10551. }
  10552. }
  10553. }
  10554. }
  10555. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10556. if (currentContextDecorators.length) {
  10557. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  10558. }
  10559. }
  10560. checkDeclaration(node) {
  10561. if (node.type === "Identifier") {
  10562. this.checkDuplicateExports(node, node.name);
  10563. } else if (node.type === "ObjectPattern") {
  10564. for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
  10565. const prop = _node$properties[_i6];
  10566. this.checkDeclaration(prop);
  10567. }
  10568. } else if (node.type === "ArrayPattern") {
  10569. for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
  10570. const elem = _node$elements[_i7];
  10571. if (elem) {
  10572. this.checkDeclaration(elem);
  10573. }
  10574. }
  10575. } else if (node.type === "ObjectProperty") {
  10576. this.checkDeclaration(node.value);
  10577. } else if (node.type === "RestElement") {
  10578. this.checkDeclaration(node.argument);
  10579. } else if (node.type === "AssignmentPattern") {
  10580. this.checkDeclaration(node.left);
  10581. }
  10582. }
  10583. checkDuplicateExports(node, name) {
  10584. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  10585. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  10586. }
  10587. this.state.exportedIdentifiers.push(name);
  10588. }
  10589. parseExportSpecifiers() {
  10590. const nodes = [];
  10591. let first = true;
  10592. this.expect(types.braceL);
  10593. while (!this.eat(types.braceR)) {
  10594. if (first) {
  10595. first = false;
  10596. } else {
  10597. this.expect(types.comma);
  10598. if (this.eat(types.braceR)) break;
  10599. }
  10600. const node = this.startNode();
  10601. node.local = this.parseModuleExportName();
  10602. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
  10603. nodes.push(this.finishNode(node, "ExportSpecifier"));
  10604. }
  10605. return nodes;
  10606. }
  10607. parseModuleExportName() {
  10608. if (this.match(types.string)) {
  10609. this.expectPlugin("moduleStringNames");
  10610. const result = this.parseLiteral(this.state.value, "StringLiteral");
  10611. const surrogate = result.value.match(loneSurrogate);
  10612. if (surrogate) {
  10613. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  10614. }
  10615. return result;
  10616. }
  10617. return this.parseIdentifier(true);
  10618. }
  10619. parseImport(node) {
  10620. node.specifiers = [];
  10621. if (!this.match(types.string)) {
  10622. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  10623. const parseNext = !hasDefault || this.eat(types.comma);
  10624. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  10625. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  10626. this.expectContextual("from");
  10627. }
  10628. node.source = this.parseImportSource();
  10629. const assertions = this.maybeParseImportAssertions();
  10630. if (assertions) {
  10631. node.assertions = assertions;
  10632. } else {
  10633. const attributes = this.maybeParseModuleAttributes();
  10634. if (attributes) {
  10635. node.attributes = attributes;
  10636. }
  10637. }
  10638. this.semicolon();
  10639. return this.finishNode(node, "ImportDeclaration");
  10640. }
  10641. parseImportSource() {
  10642. if (!this.match(types.string)) this.unexpected();
  10643. return this.parseExprAtom();
  10644. }
  10645. shouldParseDefaultImport(node) {
  10646. return this.match(types.name);
  10647. }
  10648. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  10649. specifier.local = this.parseIdentifier();
  10650. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  10651. node.specifiers.push(this.finishNode(specifier, type));
  10652. }
  10653. parseAssertEntries() {
  10654. this.expectPlugin("importAssertions");
  10655. const attrs = [];
  10656. const attrNames = new Set();
  10657. do {
  10658. if (this.match(types.braceR)) {
  10659. break;
  10660. }
  10661. const node = this.startNode();
  10662. let assertionKeyNode;
  10663. if (this.match(types.string)) {
  10664. assertionKeyNode = this.parseLiteral(this.state.value, "StringLiteral");
  10665. } else {
  10666. assertionKeyNode = this.parseIdentifier(true);
  10667. }
  10668. this.next();
  10669. node.key = assertionKeyNode;
  10670. if (node.key.name !== "type") {
  10671. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  10672. }
  10673. if (attrNames.has(node.key.name)) {
  10674. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  10675. }
  10676. attrNames.add(node.key.name);
  10677. if (!this.match(types.string)) {
  10678. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  10679. }
  10680. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  10681. this.finishNode(node, "ImportAttribute");
  10682. attrs.push(node);
  10683. } while (this.eat(types.comma));
  10684. return attrs;
  10685. }
  10686. maybeParseModuleAttributes() {
  10687. if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
  10688. this.expectPlugin("moduleAttributes");
  10689. this.next();
  10690. } else {
  10691. if (this.hasPlugin("moduleAttributes")) return [];
  10692. return null;
  10693. }
  10694. const attrs = [];
  10695. const attributes = new Set();
  10696. do {
  10697. const node = this.startNode();
  10698. node.key = this.parseIdentifier(true);
  10699. if (node.key.name !== "type") {
  10700. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  10701. }
  10702. if (attributes.has(node.key.name)) {
  10703. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  10704. }
  10705. attributes.add(node.key.name);
  10706. this.expect(types.colon);
  10707. if (!this.match(types.string)) {
  10708. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  10709. }
  10710. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  10711. this.finishNode(node, "ImportAttribute");
  10712. attrs.push(node);
  10713. } while (this.eat(types.comma));
  10714. return attrs;
  10715. }
  10716. maybeParseImportAssertions() {
  10717. if (this.match(types.name) && this.state.value === "assert" && !this.hasPrecedingLineBreak()) {
  10718. this.expectPlugin("importAssertions");
  10719. this.next();
  10720. } else {
  10721. if (this.hasPlugin("importAssertions")) return [];
  10722. return null;
  10723. }
  10724. this.eat(types.braceL);
  10725. const attrs = this.parseAssertEntries();
  10726. this.eat(types.braceR);
  10727. return attrs;
  10728. }
  10729. maybeParseDefaultImportSpecifier(node) {
  10730. if (this.shouldParseDefaultImport(node)) {
  10731. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  10732. return true;
  10733. }
  10734. return false;
  10735. }
  10736. maybeParseStarImportSpecifier(node) {
  10737. if (this.match(types.star)) {
  10738. const specifier = this.startNode();
  10739. this.next();
  10740. this.expectContextual("as");
  10741. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  10742. return true;
  10743. }
  10744. return false;
  10745. }
  10746. parseNamedImportSpecifiers(node) {
  10747. let first = true;
  10748. this.expect(types.braceL);
  10749. while (!this.eat(types.braceR)) {
  10750. if (first) {
  10751. first = false;
  10752. } else {
  10753. if (this.eat(types.colon)) {
  10754. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  10755. }
  10756. this.expect(types.comma);
  10757. if (this.eat(types.braceR)) break;
  10758. }
  10759. this.parseImportSpecifier(node);
  10760. }
  10761. }
  10762. parseImportSpecifier(node) {
  10763. const specifier = this.startNode();
  10764. specifier.imported = this.parseModuleExportName();
  10765. if (this.eatContextual("as")) {
  10766. specifier.local = this.parseIdentifier();
  10767. } else {
  10768. const {
  10769. imported
  10770. } = specifier;
  10771. if (imported.type === "StringLiteral") {
  10772. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  10773. }
  10774. this.checkReservedWord(imported.name, specifier.start, true, true);
  10775. specifier.local = imported.__clone();
  10776. }
  10777. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  10778. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  10779. }
  10780. }
  10781. class ClassScope {
  10782. constructor() {
  10783. this.privateNames = new Set();
  10784. this.loneAccessors = new Map();
  10785. this.undefinedPrivateNames = new Map();
  10786. }
  10787. }
  10788. class ClassScopeHandler {
  10789. constructor(raise) {
  10790. this.stack = [];
  10791. this.raise = void 0;
  10792. this.undefinedPrivateNames = new Map();
  10793. this.raise = raise;
  10794. }
  10795. current() {
  10796. return this.stack[this.stack.length - 1];
  10797. }
  10798. enter() {
  10799. this.stack.push(new ClassScope());
  10800. }
  10801. exit() {
  10802. const oldClassScope = this.stack.pop();
  10803. const current = this.current();
  10804. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  10805. const [name, pos] = _Array$from[_i];
  10806. if (current) {
  10807. if (!current.undefinedPrivateNames.has(name)) {
  10808. current.undefinedPrivateNames.set(name, pos);
  10809. }
  10810. } else {
  10811. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  10812. }
  10813. }
  10814. }
  10815. declarePrivateName(name, elementType, pos) {
  10816. const classScope = this.current();
  10817. let redefined = classScope.privateNames.has(name);
  10818. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  10819. const accessor = redefined && classScope.loneAccessors.get(name);
  10820. if (accessor) {
  10821. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  10822. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  10823. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  10824. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  10825. redefined = oldKind === newKind || oldStatic !== newStatic;
  10826. if (!redefined) classScope.loneAccessors.delete(name);
  10827. } else if (!redefined) {
  10828. classScope.loneAccessors.set(name, elementType);
  10829. }
  10830. }
  10831. if (redefined) {
  10832. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  10833. }
  10834. classScope.privateNames.add(name);
  10835. classScope.undefinedPrivateNames.delete(name);
  10836. }
  10837. usePrivateName(name, pos) {
  10838. let classScope;
  10839. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  10840. classScope = _this$stack[_i2];
  10841. if (classScope.privateNames.has(name)) return;
  10842. }
  10843. if (classScope) {
  10844. classScope.undefinedPrivateNames.set(name, pos);
  10845. } else {
  10846. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  10847. }
  10848. }
  10849. }
  10850. class Parser extends StatementParser {
  10851. constructor(options, input) {
  10852. options = getOptions(options);
  10853. super(options, input);
  10854. const ScopeHandler = this.getScopeHandler();
  10855. this.options = options;
  10856. this.inModule = this.options.sourceType === "module";
  10857. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  10858. this.prodParam = new ProductionParameterHandler();
  10859. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  10860. this.plugins = pluginsMap(this.options.plugins);
  10861. this.filename = options.sourceFilename;
  10862. }
  10863. getScopeHandler() {
  10864. return ScopeHandler;
  10865. }
  10866. parse() {
  10867. let paramFlags = PARAM;
  10868. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  10869. paramFlags |= PARAM_AWAIT;
  10870. }
  10871. this.scope.enter(SCOPE_PROGRAM);
  10872. this.prodParam.enter(paramFlags);
  10873. const file = this.startNode();
  10874. const program = this.startNode();
  10875. this.nextToken();
  10876. file.errors = null;
  10877. this.parseTopLevel(file, program);
  10878. file.errors = this.state.errors;
  10879. return file;
  10880. }
  10881. }
  10882. function pluginsMap(plugins) {
  10883. const pluginMap = new Map();
  10884. for (let _i = 0; _i < plugins.length; _i++) {
  10885. const plugin = plugins[_i];
  10886. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  10887. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  10888. }
  10889. return pluginMap;
  10890. }
  10891. function parse(input, options) {
  10892. var _options;
  10893. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  10894. options = Object.assign({}, options);
  10895. try {
  10896. options.sourceType = "module";
  10897. const parser = getParser(options, input);
  10898. const ast = parser.parse();
  10899. if (parser.sawUnambiguousESM) {
  10900. return ast;
  10901. }
  10902. if (parser.ambiguousScriptDifferentAst) {
  10903. try {
  10904. options.sourceType = "script";
  10905. return getParser(options, input).parse();
  10906. } catch (_unused) {}
  10907. } else {
  10908. ast.program.sourceType = "script";
  10909. }
  10910. return ast;
  10911. } catch (moduleError) {
  10912. try {
  10913. options.sourceType = "script";
  10914. return getParser(options, input).parse();
  10915. } catch (_unused2) {}
  10916. throw moduleError;
  10917. }
  10918. } else {
  10919. return getParser(options, input).parse();
  10920. }
  10921. }
  10922. function parseExpression(input, options) {
  10923. const parser = getParser(options, input);
  10924. if (parser.options.strictMode) {
  10925. parser.state.strict = true;
  10926. }
  10927. return parser.getExpression();
  10928. }
  10929. function getParser(options, input) {
  10930. let cls = Parser;
  10931. if (options == null ? void 0 : options.plugins) {
  10932. validatePlugins(options.plugins);
  10933. cls = getParserClass(options.plugins);
  10934. }
  10935. return new cls(options, input);
  10936. }
  10937. const parserClassCache = {};
  10938. function getParserClass(pluginsFromOptions) {
  10939. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  10940. const key = pluginList.join("/");
  10941. let cls = parserClassCache[key];
  10942. if (!cls) {
  10943. cls = Parser;
  10944. for (let _i = 0; _i < pluginList.length; _i++) {
  10945. const plugin = pluginList[_i];
  10946. cls = mixinPlugins[plugin](cls);
  10947. }
  10948. parserClassCache[key] = cls;
  10949. }
  10950. return cls;
  10951. }
  10952. exports.parse = parse;
  10953. exports.parseExpression = parseExpression;
  10954. exports.tokTypes = types;
  10955. //# sourceMappingURL=index.js.map