index.js 377 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const beforeExpr = true;
  4. const startsExpr = true;
  5. const isLoop = true;
  6. const isAssign = true;
  7. const prefix = true;
  8. const postfix = true;
  9. class TokenType {
  10. constructor(label, conf = {}) {
  11. this.label = label;
  12. this.keyword = conf.keyword;
  13. this.beforeExpr = !!conf.beforeExpr;
  14. this.startsExpr = !!conf.startsExpr;
  15. this.rightAssociative = !!conf.rightAssociative;
  16. this.isLoop = !!conf.isLoop;
  17. this.isAssign = !!conf.isAssign;
  18. this.prefix = !!conf.prefix;
  19. this.postfix = !!conf.postfix;
  20. this.binop = conf.binop != null ? conf.binop : null;
  21. this.updateContext = null;
  22. }
  23. }
  24. const keywords = new Map();
  25. function createKeyword(name, options = {}) {
  26. options.keyword = name;
  27. const token = new TokenType(name, options);
  28. keywords.set(name, token);
  29. return token;
  30. }
  31. function createBinop(name, binop) {
  32. return new TokenType(name, {
  33. beforeExpr,
  34. binop
  35. });
  36. }
  37. const types = {
  38. num: new TokenType("num", {
  39. startsExpr
  40. }),
  41. bigint: new TokenType("bigint", {
  42. startsExpr
  43. }),
  44. regexp: new TokenType("regexp", {
  45. startsExpr
  46. }),
  47. string: new TokenType("string", {
  48. startsExpr
  49. }),
  50. name: new TokenType("name", {
  51. startsExpr
  52. }),
  53. eof: new TokenType("eof"),
  54. bracketL: new TokenType("[", {
  55. beforeExpr,
  56. startsExpr
  57. }),
  58. bracketHashL: new TokenType("#[", {
  59. beforeExpr,
  60. startsExpr
  61. }),
  62. bracketBarL: new TokenType("[|", {
  63. beforeExpr,
  64. startsExpr
  65. }),
  66. bracketR: new TokenType("]"),
  67. bracketBarR: new TokenType("|]"),
  68. braceL: new TokenType("{", {
  69. beforeExpr,
  70. startsExpr
  71. }),
  72. braceBarL: new TokenType("{|", {
  73. beforeExpr,
  74. startsExpr
  75. }),
  76. braceHashL: new TokenType("#{", {
  77. beforeExpr,
  78. startsExpr
  79. }),
  80. braceR: new TokenType("}"),
  81. braceBarR: new TokenType("|}"),
  82. parenL: new TokenType("(", {
  83. beforeExpr,
  84. startsExpr
  85. }),
  86. parenR: new TokenType(")"),
  87. comma: new TokenType(",", {
  88. beforeExpr
  89. }),
  90. semi: new TokenType(";", {
  91. beforeExpr
  92. }),
  93. colon: new TokenType(":", {
  94. beforeExpr
  95. }),
  96. doubleColon: new TokenType("::", {
  97. beforeExpr
  98. }),
  99. dot: new TokenType("."),
  100. question: new TokenType("?", {
  101. beforeExpr
  102. }),
  103. questionDot: new TokenType("?."),
  104. arrow: new TokenType("=>", {
  105. beforeExpr
  106. }),
  107. template: new TokenType("template"),
  108. ellipsis: new TokenType("...", {
  109. beforeExpr
  110. }),
  111. backQuote: new TokenType("`", {
  112. startsExpr
  113. }),
  114. dollarBraceL: new TokenType("${", {
  115. beforeExpr,
  116. startsExpr
  117. }),
  118. at: new TokenType("@"),
  119. hash: new TokenType("#", {
  120. startsExpr
  121. }),
  122. interpreterDirective: new TokenType("#!..."),
  123. eq: new TokenType("=", {
  124. beforeExpr,
  125. isAssign
  126. }),
  127. assign: new TokenType("_=", {
  128. beforeExpr,
  129. isAssign
  130. }),
  131. incDec: new TokenType("++/--", {
  132. prefix,
  133. postfix,
  134. startsExpr
  135. }),
  136. bang: new TokenType("!", {
  137. beforeExpr,
  138. prefix,
  139. startsExpr
  140. }),
  141. tilde: new TokenType("~", {
  142. beforeExpr,
  143. prefix,
  144. startsExpr
  145. }),
  146. pipeline: createBinop("|>", 0),
  147. nullishCoalescing: createBinop("??", 1),
  148. logicalOR: createBinop("||", 1),
  149. logicalAND: createBinop("&&", 2),
  150. bitwiseOR: createBinop("|", 3),
  151. bitwiseXOR: createBinop("^", 4),
  152. bitwiseAND: createBinop("&", 5),
  153. equality: createBinop("==/!=/===/!==", 6),
  154. relational: createBinop("</>/<=/>=", 7),
  155. bitShift: createBinop("<</>>/>>>", 8),
  156. plusMin: new TokenType("+/-", {
  157. beforeExpr,
  158. binop: 9,
  159. prefix,
  160. startsExpr
  161. }),
  162. modulo: new TokenType("%", {
  163. beforeExpr,
  164. binop: 10,
  165. startsExpr
  166. }),
  167. star: createBinop("*", 10),
  168. slash: createBinop("/", 10),
  169. exponent: new TokenType("**", {
  170. beforeExpr,
  171. binop: 11,
  172. rightAssociative: true
  173. }),
  174. _break: createKeyword("break"),
  175. _case: createKeyword("case", {
  176. beforeExpr
  177. }),
  178. _catch: createKeyword("catch"),
  179. _continue: createKeyword("continue"),
  180. _debugger: createKeyword("debugger"),
  181. _default: createKeyword("default", {
  182. beforeExpr
  183. }),
  184. _do: createKeyword("do", {
  185. isLoop,
  186. beforeExpr
  187. }),
  188. _else: createKeyword("else", {
  189. beforeExpr
  190. }),
  191. _finally: createKeyword("finally"),
  192. _for: createKeyword("for", {
  193. isLoop
  194. }),
  195. _function: createKeyword("function", {
  196. startsExpr
  197. }),
  198. _if: createKeyword("if"),
  199. _return: createKeyword("return", {
  200. beforeExpr
  201. }),
  202. _switch: createKeyword("switch"),
  203. _throw: createKeyword("throw", {
  204. beforeExpr,
  205. prefix,
  206. startsExpr
  207. }),
  208. _try: createKeyword("try"),
  209. _var: createKeyword("var"),
  210. _const: createKeyword("const"),
  211. _while: createKeyword("while", {
  212. isLoop
  213. }),
  214. _with: createKeyword("with"),
  215. _new: createKeyword("new", {
  216. beforeExpr,
  217. startsExpr
  218. }),
  219. _this: createKeyword("this", {
  220. startsExpr
  221. }),
  222. _super: createKeyword("super", {
  223. startsExpr
  224. }),
  225. _class: createKeyword("class", {
  226. startsExpr
  227. }),
  228. _extends: createKeyword("extends", {
  229. beforeExpr
  230. }),
  231. _export: createKeyword("export"),
  232. _import: createKeyword("import", {
  233. startsExpr
  234. }),
  235. _null: createKeyword("null", {
  236. startsExpr
  237. }),
  238. _true: createKeyword("true", {
  239. startsExpr
  240. }),
  241. _false: createKeyword("false", {
  242. startsExpr
  243. }),
  244. _in: createKeyword("in", {
  245. beforeExpr,
  246. binop: 7
  247. }),
  248. _instanceof: createKeyword("instanceof", {
  249. beforeExpr,
  250. binop: 7
  251. }),
  252. _typeof: createKeyword("typeof", {
  253. beforeExpr,
  254. prefix,
  255. startsExpr
  256. }),
  257. _void: createKeyword("void", {
  258. beforeExpr,
  259. prefix,
  260. startsExpr
  261. }),
  262. _delete: createKeyword("delete", {
  263. beforeExpr,
  264. prefix,
  265. startsExpr
  266. })
  267. };
  268. const SCOPE_OTHER = 0b00000000,
  269. SCOPE_PROGRAM = 0b00000001,
  270. SCOPE_FUNCTION = 0b00000010,
  271. SCOPE_ARROW = 0b00000100,
  272. SCOPE_SIMPLE_CATCH = 0b00001000,
  273. SCOPE_SUPER = 0b00010000,
  274. SCOPE_DIRECT_SUPER = 0b00100000,
  275. SCOPE_CLASS = 0b01000000,
  276. SCOPE_TS_MODULE = 0b10000000,
  277. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  278. const BIND_KIND_VALUE = 0b00000000001,
  279. BIND_KIND_TYPE = 0b00000000010,
  280. BIND_SCOPE_VAR = 0b00000000100,
  281. BIND_SCOPE_LEXICAL = 0b00000001000,
  282. BIND_SCOPE_FUNCTION = 0b00000010000,
  283. BIND_FLAGS_NONE = 0b00001000000,
  284. BIND_FLAGS_CLASS = 0b00010000000,
  285. BIND_FLAGS_TS_ENUM = 0b00100000000,
  286. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  287. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  288. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  289. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  290. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  291. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  292. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  293. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  294. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  295. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  296. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  297. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  298. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  299. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  300. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  301. CLASS_ELEMENT_KIND_GETTER = 0b010,
  302. CLASS_ELEMENT_KIND_SETTER = 0b001,
  303. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  304. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  305. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  306. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  307. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  308. CLASS_ELEMENT_OTHER = 0;
  309. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  310. const lineBreakG = new RegExp(lineBreak.source, "g");
  311. function isNewLine(code) {
  312. switch (code) {
  313. case 10:
  314. case 13:
  315. case 8232:
  316. case 8233:
  317. return true;
  318. default:
  319. return false;
  320. }
  321. }
  322. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  323. function isWhitespace(code) {
  324. switch (code) {
  325. case 0x0009:
  326. case 0x000b:
  327. case 0x000c:
  328. case 32:
  329. case 160:
  330. case 5760:
  331. case 0x2000:
  332. case 0x2001:
  333. case 0x2002:
  334. case 0x2003:
  335. case 0x2004:
  336. case 0x2005:
  337. case 0x2006:
  338. case 0x2007:
  339. case 0x2008:
  340. case 0x2009:
  341. case 0x200a:
  342. case 0x202f:
  343. case 0x205f:
  344. case 0x3000:
  345. case 0xfeff:
  346. return true;
  347. default:
  348. return false;
  349. }
  350. }
  351. class Position {
  352. constructor(line, col) {
  353. this.line = line;
  354. this.column = col;
  355. }
  356. }
  357. class SourceLocation {
  358. constructor(start, end) {
  359. this.start = start;
  360. this.end = end;
  361. }
  362. }
  363. function getLineInfo(input, offset) {
  364. let line = 1;
  365. let lineStart = 0;
  366. let match;
  367. lineBreakG.lastIndex = 0;
  368. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  369. line++;
  370. lineStart = lineBreakG.lastIndex;
  371. }
  372. return new Position(line, offset - lineStart);
  373. }
  374. class BaseParser {
  375. constructor() {
  376. this.sawUnambiguousESM = false;
  377. this.ambiguousScriptDifferentAst = false;
  378. }
  379. hasPlugin(name) {
  380. return this.plugins.has(name);
  381. }
  382. getPluginOption(plugin, name) {
  383. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  384. }
  385. }
  386. function last(stack) {
  387. return stack[stack.length - 1];
  388. }
  389. class CommentsParser extends BaseParser {
  390. addComment(comment) {
  391. if (this.filename) comment.loc.filename = this.filename;
  392. this.state.trailingComments.push(comment);
  393. this.state.leadingComments.push(comment);
  394. }
  395. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  396. if (this.state.leadingComments.length === 0) {
  397. return;
  398. }
  399. let lastElement = null;
  400. let i = elements.length;
  401. while (lastElement === null && i > 0) {
  402. lastElement = elements[--i];
  403. }
  404. if (lastElement === null) {
  405. return;
  406. }
  407. for (let j = 0; j < this.state.leadingComments.length; j++) {
  408. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  409. this.state.leadingComments.splice(j, 1);
  410. j--;
  411. }
  412. }
  413. const newTrailingComments = [];
  414. for (let i = 0; i < this.state.leadingComments.length; i++) {
  415. const leadingComment = this.state.leadingComments[i];
  416. if (leadingComment.end < node.end) {
  417. newTrailingComments.push(leadingComment);
  418. if (!takeAllComments) {
  419. this.state.leadingComments.splice(i, 1);
  420. i--;
  421. }
  422. } else {
  423. if (node.trailingComments === undefined) {
  424. node.trailingComments = [];
  425. }
  426. node.trailingComments.push(leadingComment);
  427. }
  428. }
  429. if (takeAllComments) this.state.leadingComments = [];
  430. if (newTrailingComments.length > 0) {
  431. lastElement.trailingComments = newTrailingComments;
  432. } else if (lastElement.trailingComments !== undefined) {
  433. lastElement.trailingComments = [];
  434. }
  435. }
  436. processComment(node) {
  437. if (node.type === "Program" && node.body.length > 0) return;
  438. const stack = this.state.commentStack;
  439. let firstChild, lastChild, trailingComments, i, j;
  440. if (this.state.trailingComments.length > 0) {
  441. if (this.state.trailingComments[0].start >= node.end) {
  442. trailingComments = this.state.trailingComments;
  443. this.state.trailingComments = [];
  444. } else {
  445. this.state.trailingComments.length = 0;
  446. }
  447. } else if (stack.length > 0) {
  448. const lastInStack = last(stack);
  449. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  450. trailingComments = lastInStack.trailingComments;
  451. delete lastInStack.trailingComments;
  452. }
  453. }
  454. if (stack.length > 0 && last(stack).start >= node.start) {
  455. firstChild = stack.pop();
  456. }
  457. while (stack.length > 0 && last(stack).start >= node.start) {
  458. lastChild = stack.pop();
  459. }
  460. if (!lastChild && firstChild) lastChild = firstChild;
  461. if (firstChild) {
  462. switch (node.type) {
  463. case "ObjectExpression":
  464. this.adjustCommentsAfterTrailingComma(node, node.properties);
  465. break;
  466. case "ObjectPattern":
  467. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  468. break;
  469. case "CallExpression":
  470. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  471. break;
  472. case "ArrayExpression":
  473. this.adjustCommentsAfterTrailingComma(node, node.elements);
  474. break;
  475. case "ArrayPattern":
  476. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  477. break;
  478. }
  479. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  480. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  481. }
  482. if (lastChild) {
  483. if (lastChild.leadingComments) {
  484. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  485. node.leadingComments = lastChild.leadingComments;
  486. delete lastChild.leadingComments;
  487. } else {
  488. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  489. if (lastChild.leadingComments[i].end <= node.start) {
  490. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  491. break;
  492. }
  493. }
  494. }
  495. }
  496. } else if (this.state.leadingComments.length > 0) {
  497. if (last(this.state.leadingComments).end <= node.start) {
  498. if (this.state.commentPreviousNode) {
  499. for (j = 0; j < this.state.leadingComments.length; j++) {
  500. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  501. this.state.leadingComments.splice(j, 1);
  502. j--;
  503. }
  504. }
  505. }
  506. if (this.state.leadingComments.length > 0) {
  507. node.leadingComments = this.state.leadingComments;
  508. this.state.leadingComments = [];
  509. }
  510. } else {
  511. for (i = 0; i < this.state.leadingComments.length; i++) {
  512. if (this.state.leadingComments[i].end > node.start) {
  513. break;
  514. }
  515. }
  516. const leadingComments = this.state.leadingComments.slice(0, i);
  517. if (leadingComments.length) {
  518. node.leadingComments = leadingComments;
  519. }
  520. trailingComments = this.state.leadingComments.slice(i);
  521. if (trailingComments.length === 0) {
  522. trailingComments = null;
  523. }
  524. }
  525. }
  526. this.state.commentPreviousNode = node;
  527. if (trailingComments) {
  528. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  529. node.innerComments = trailingComments;
  530. } else {
  531. node.trailingComments = trailingComments;
  532. }
  533. }
  534. stack.push(node);
  535. }
  536. }
  537. const Errors = Object.freeze({
  538. ArgumentsDisallowedInInitializer: "'arguments' is not allowed in class field initializer",
  539. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  540. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  541. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  542. AwaitNotInAsyncFunction: "Can not use keyword 'await' outside an async function",
  543. BadGetterArity: "getter must not have any formal parameters",
  544. BadSetterArity: "setter must have exactly one formal parameter",
  545. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  546. ConstructorClassField: "Classes may not have a field named 'constructor'",
  547. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  548. ConstructorIsAccessor: "Class constructor may not be an accessor",
  549. ConstructorIsAsync: "Constructor can't be an async function",
  550. ConstructorIsGenerator: "Constructor can't be a generator",
  551. DeclarationMissingInitializer: "%0 require an initialization value",
  552. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  553. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  554. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  555. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  556. DeletePrivateField: "Deleting a private field is not allowed",
  557. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  558. DuplicateConstructor: "Duplicate constructor in the same class",
  559. DuplicateDefaultExport: "Only one default export allowed per module.",
  560. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  561. DuplicateProto: "Redefinition of __proto__ property",
  562. DuplicateRegExpFlags: "Duplicate regular expression flag",
  563. ElementAfterRest: "Rest element must be last element",
  564. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  565. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  566. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  567. IllegalBreakContinue: "Unsyntactic %0",
  568. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  569. IllegalReturn: "'return' outside of function",
  570. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  571. ImportCallArity: "import() requires exactly one argument",
  572. ImportCallArityLtOne: "Dynamic imports require a parameter: import('a.js')",
  573. ImportCallNotNewExpression: "Cannot use new with import(...)",
  574. ImportCallSpreadArgument: "... is not allowed in import()",
  575. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  576. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  577. InvalidCodePoint: "Code point out of bounds",
  578. InvalidDigit: "Expected number in radix %0",
  579. InvalidEscapeSequence: "Bad character escape sequence",
  580. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  581. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  582. InvalidIdentifier: "Invalid identifier %0",
  583. InvalidLhs: "Invalid left-hand side in %0",
  584. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  585. InvalidNumber: "Invalid number",
  586. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  587. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  588. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  589. InvalidPropertyBindingPattern: "Binding member expression",
  590. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  591. LabelRedeclaration: "Label '%0' is already declared",
  592. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  593. MalformedRegExpFlags: "Invalid regular expression flag",
  594. MissingClassName: "A class name is required",
  595. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  596. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  597. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  598. ModuleExportUndefined: "Export '%0' is not defined",
  599. MultipleDefaultsInSwitch: "Multiple default clauses",
  600. NewlineAfterThrow: "Illegal newline after throw",
  601. NoCatchOrFinally: "Missing catch or finally clause",
  602. NumberIdentifier: "Identifier directly after number",
  603. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  604. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  605. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  606. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  607. ParamDupe: "Argument name clash",
  608. PatternHasAccessor: "Object pattern can't contain getter or setter",
  609. PatternHasMethod: "Object pattern can't contain methods",
  610. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  611. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  612. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  613. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  614. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  615. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  616. PrivateNameRedeclaration: "Duplicate private name #%0",
  617. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  618. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  619. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  620. RestTrailingComma: "Unexpected trailing comma after rest element",
  621. SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement",
  622. StaticPrototype: "Classes may not have static property named prototype",
  623. StrictDelete: "Deleting local variable in strict mode",
  624. StrictEvalArguments: "Assigning to '%0' in strict mode",
  625. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  626. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  627. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  628. StrictWith: "'with' in strict mode",
  629. SuperNotAllowed: "super() is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  630. SuperPrivateField: "Private fields can't be accessed on super",
  631. TrailingDecorator: "Decorators must be attached to a class element",
  632. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  633. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  634. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  635. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  636. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  637. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  638. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  639. UnexpectedKeyword: "Unexpected keyword '%0'",
  640. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  641. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  642. UnexpectedNewTarget: "new.target can only be used in functions",
  643. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  644. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  645. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  646. UnexpectedSuper: "super is only allowed in object methods and classes",
  647. UnexpectedToken: "Unexpected token '%'",
  648. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  649. UnsupportedBind: "Binding should be performed on object property.",
  650. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  651. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  652. UnsupportedImport: "import can only be used in import() or import.meta",
  653. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  654. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  655. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  656. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  657. UnterminatedComment: "Unterminated comment",
  658. UnterminatedRegExp: "Unterminated regular expression",
  659. UnterminatedString: "Unterminated string constant",
  660. UnterminatedTemplate: "Unterminated template",
  661. VarRedeclaration: "Identifier '%0' has already been declared",
  662. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  663. YieldInParameter: "yield is not allowed in generator parameters",
  664. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  665. });
  666. class LocationParser extends CommentsParser {
  667. getLocationForPosition(pos) {
  668. let loc;
  669. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  670. return loc;
  671. }
  672. raise(pos, errorTemplate, ...params) {
  673. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  674. }
  675. raiseWithData(pos, data, errorTemplate, ...params) {
  676. const loc = this.getLocationForPosition(pos);
  677. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  678. return this._raise(Object.assign({
  679. loc,
  680. pos
  681. }, data), message);
  682. }
  683. _raise(errorContext, message) {
  684. const err = new SyntaxError(message);
  685. Object.assign(err, errorContext);
  686. if (this.options.errorRecovery) {
  687. if (!this.isLookahead) this.state.errors.push(err);
  688. return err;
  689. } else {
  690. throw err;
  691. }
  692. }
  693. }
  694. function isSimpleProperty(node) {
  695. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  696. }
  697. var estree = (superClass => class extends superClass {
  698. estreeParseRegExpLiteral({
  699. pattern,
  700. flags
  701. }) {
  702. let regex = null;
  703. try {
  704. regex = new RegExp(pattern, flags);
  705. } catch (e) {}
  706. const node = this.estreeParseLiteral(regex);
  707. node.regex = {
  708. pattern,
  709. flags
  710. };
  711. return node;
  712. }
  713. estreeParseBigIntLiteral(value) {
  714. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  715. const node = this.estreeParseLiteral(bigInt);
  716. node.bigint = String(node.value || value);
  717. return node;
  718. }
  719. estreeParseLiteral(value) {
  720. return this.parseLiteral(value, "Literal");
  721. }
  722. directiveToStmt(directive) {
  723. const directiveLiteral = directive.value;
  724. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  725. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  726. expression.value = directiveLiteral.value;
  727. expression.raw = directiveLiteral.extra.raw;
  728. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  729. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  730. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  731. }
  732. initFunction(node, isAsync) {
  733. super.initFunction(node, isAsync);
  734. node.expression = false;
  735. }
  736. checkDeclaration(node) {
  737. if (isSimpleProperty(node)) {
  738. this.checkDeclaration(node.value);
  739. } else {
  740. super.checkDeclaration(node);
  741. }
  742. }
  743. checkGetterSetterParams(method) {
  744. const prop = method;
  745. const paramCount = prop.kind === "get" ? 0 : 1;
  746. const start = prop.start;
  747. if (prop.value.params.length !== paramCount) {
  748. if (method.kind === "get") {
  749. this.raise(start, Errors.BadGetterArity);
  750. } else {
  751. this.raise(start, Errors.BadSetterArity);
  752. }
  753. } else if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
  754. this.raise(start, Errors.BadSetterRestParameter);
  755. }
  756. }
  757. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding) {
  758. switch (expr.type) {
  759. case "ObjectPattern":
  760. expr.properties.forEach(prop => {
  761. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  762. });
  763. break;
  764. default:
  765. super.checkLVal(expr, bindingType, checkClashes, contextDescription, disallowLetBinding);
  766. }
  767. }
  768. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  769. if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) {
  770. return;
  771. }
  772. const key = prop.key;
  773. const name = key.type === "Identifier" ? key.name : String(key.value);
  774. if (name === "__proto__" && prop.kind === "init") {
  775. if (protoRef.used) {
  776. if (refExpressionErrors && refExpressionErrors.doubleProto === -1) {
  777. refExpressionErrors.doubleProto = key.start;
  778. } else {
  779. this.raise(key.start, Errors.DuplicateProto);
  780. }
  781. }
  782. protoRef.used = true;
  783. }
  784. }
  785. isValidDirective(stmt) {
  786. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized);
  787. }
  788. stmtToDirective(stmt) {
  789. const directive = super.stmtToDirective(stmt);
  790. const value = stmt.expression.value;
  791. directive.value.value = value;
  792. return directive;
  793. }
  794. parseBlockBody(node, allowDirectives, topLevel, end) {
  795. super.parseBlockBody(node, allowDirectives, topLevel, end);
  796. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  797. node.body = directiveStatements.concat(node.body);
  798. delete node.directives;
  799. }
  800. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  801. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  802. if (method.typeParameters) {
  803. method.value.typeParameters = method.typeParameters;
  804. delete method.typeParameters;
  805. }
  806. classBody.body.push(method);
  807. }
  808. parseExprAtom(refExpressionErrors) {
  809. switch (this.state.type) {
  810. case types.num:
  811. case types.string:
  812. return this.estreeParseLiteral(this.state.value);
  813. case types.regexp:
  814. return this.estreeParseRegExpLiteral(this.state.value);
  815. case types.bigint:
  816. return this.estreeParseBigIntLiteral(this.state.value);
  817. case types._null:
  818. return this.estreeParseLiteral(null);
  819. case types._true:
  820. return this.estreeParseLiteral(true);
  821. case types._false:
  822. return this.estreeParseLiteral(false);
  823. default:
  824. return super.parseExprAtom(refExpressionErrors);
  825. }
  826. }
  827. parseLiteral(value, type, startPos, startLoc) {
  828. const node = super.parseLiteral(value, type, startPos, startLoc);
  829. node.raw = node.extra.raw;
  830. delete node.extra;
  831. return node;
  832. }
  833. parseFunctionBody(node, allowExpression, isMethod = false) {
  834. super.parseFunctionBody(node, allowExpression, isMethod);
  835. node.expression = node.body.type !== "BlockStatement";
  836. }
  837. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  838. let funcNode = this.startNode();
  839. funcNode.kind = node.kind;
  840. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  841. funcNode.type = "FunctionExpression";
  842. delete funcNode.kind;
  843. node.value = funcNode;
  844. type = type === "ClassMethod" ? "MethodDefinition" : type;
  845. return this.finishNode(node, type);
  846. }
  847. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  848. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc);
  849. if (node) {
  850. node.type = "Property";
  851. if (node.kind === "method") node.kind = "init";
  852. node.shorthand = false;
  853. }
  854. return node;
  855. }
  856. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  857. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  858. if (node) {
  859. node.kind = "init";
  860. node.type = "Property";
  861. }
  862. return node;
  863. }
  864. toAssignable(node) {
  865. if (isSimpleProperty(node)) {
  866. this.toAssignable(node.value);
  867. return node;
  868. }
  869. return super.toAssignable(node);
  870. }
  871. toAssignableObjectExpressionProp(prop, isLast) {
  872. if (prop.kind === "get" || prop.kind === "set") {
  873. throw this.raise(prop.key.start, Errors.PatternHasAccessor);
  874. } else if (prop.method) {
  875. throw this.raise(prop.key.start, Errors.PatternHasMethod);
  876. } else {
  877. super.toAssignableObjectExpressionProp(prop, isLast);
  878. }
  879. }
  880. finishCallExpression(node, optional) {
  881. super.finishCallExpression(node, optional);
  882. if (node.callee.type === "Import") {
  883. node.type = "ImportExpression";
  884. node.source = node.arguments[0];
  885. delete node.arguments;
  886. delete node.callee;
  887. }
  888. return node;
  889. }
  890. toReferencedListDeep(exprList, isParenthesizedExpr) {
  891. if (!exprList) {
  892. return;
  893. }
  894. super.toReferencedListDeep(exprList, isParenthesizedExpr);
  895. }
  896. parseExport(node) {
  897. super.parseExport(node);
  898. switch (node.type) {
  899. case "ExportAllDeclaration":
  900. node.exported = null;
  901. break;
  902. case "ExportNamedDeclaration":
  903. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  904. node.type = "ExportAllDeclaration";
  905. node.exported = node.specifiers[0].exported;
  906. delete node.specifiers;
  907. }
  908. break;
  909. }
  910. return node;
  911. }
  912. });
  913. class TokContext {
  914. constructor(token, isExpr, preserveSpace, override) {
  915. this.token = token;
  916. this.isExpr = !!isExpr;
  917. this.preserveSpace = !!preserveSpace;
  918. this.override = override;
  919. }
  920. }
  921. const types$1 = {
  922. braceStatement: new TokContext("{", false),
  923. braceExpression: new TokContext("{", true),
  924. templateQuasi: new TokContext("${", false),
  925. parenStatement: new TokContext("(", false),
  926. parenExpression: new TokContext("(", true),
  927. template: new TokContext("`", true, true, p => p.readTmplToken()),
  928. functionExpression: new TokContext("function", true),
  929. functionStatement: new TokContext("function", false)
  930. };
  931. types.parenR.updateContext = types.braceR.updateContext = function () {
  932. if (this.state.context.length === 1) {
  933. this.state.exprAllowed = true;
  934. return;
  935. }
  936. let out = this.state.context.pop();
  937. if (out === types$1.braceStatement && this.curContext().token === "function") {
  938. out = this.state.context.pop();
  939. }
  940. this.state.exprAllowed = !out.isExpr;
  941. };
  942. types.name.updateContext = function (prevType) {
  943. let allowed = false;
  944. if (prevType !== types.dot) {
  945. if (this.state.value === "of" && !this.state.exprAllowed || this.state.value === "yield" && this.prodParam.hasYield) {
  946. allowed = true;
  947. }
  948. }
  949. this.state.exprAllowed = allowed;
  950. if (this.state.isIterator) {
  951. this.state.isIterator = false;
  952. }
  953. };
  954. types.braceL.updateContext = function (prevType) {
  955. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  956. this.state.exprAllowed = true;
  957. };
  958. types.dollarBraceL.updateContext = function () {
  959. this.state.context.push(types$1.templateQuasi);
  960. this.state.exprAllowed = true;
  961. };
  962. types.parenL.updateContext = function (prevType) {
  963. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  964. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  965. this.state.exprAllowed = true;
  966. };
  967. types.incDec.updateContext = function () {};
  968. types._function.updateContext = types._class.updateContext = function (prevType) {
  969. if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
  970. this.state.context.push(types$1.functionExpression);
  971. } else {
  972. this.state.context.push(types$1.functionStatement);
  973. }
  974. this.state.exprAllowed = false;
  975. };
  976. types.backQuote.updateContext = function () {
  977. if (this.curContext() === types$1.template) {
  978. this.state.context.pop();
  979. } else {
  980. this.state.context.push(types$1.template);
  981. }
  982. this.state.exprAllowed = false;
  983. };
  984. 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";
  985. 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";
  986. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  987. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  988. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  989. 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];
  990. 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];
  991. function isInAstralSet(code, set) {
  992. let pos = 0x10000;
  993. for (let i = 0, length = set.length; i < length; i += 2) {
  994. pos += set[i];
  995. if (pos > code) return false;
  996. pos += set[i + 1];
  997. if (pos >= code) return true;
  998. }
  999. return false;
  1000. }
  1001. function isIdentifierStart(code) {
  1002. if (code < 65) return code === 36;
  1003. if (code <= 90) return true;
  1004. if (code < 97) return code === 95;
  1005. if (code <= 122) return true;
  1006. if (code <= 0xffff) {
  1007. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1008. }
  1009. return isInAstralSet(code, astralIdentifierStartCodes);
  1010. }
  1011. function isIdentifierChar(code) {
  1012. if (code < 48) return code === 36;
  1013. if (code < 58) return true;
  1014. if (code < 65) return false;
  1015. if (code <= 90) return true;
  1016. if (code < 97) return code === 95;
  1017. if (code <= 122) return true;
  1018. if (code <= 0xffff) {
  1019. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1020. }
  1021. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1022. }
  1023. const reservedWords = {
  1024. 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"],
  1025. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1026. strictBind: ["eval", "arguments"]
  1027. };
  1028. const keywords$1 = new Set(reservedWords.keyword);
  1029. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1030. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1031. function isReservedWord(word, inModule) {
  1032. return inModule && word === "await" || word === "enum";
  1033. }
  1034. function isStrictReservedWord(word, inModule) {
  1035. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1036. }
  1037. function isStrictBindOnlyReservedWord(word) {
  1038. return reservedWordsStrictBindSet.has(word);
  1039. }
  1040. function isStrictBindReservedWord(word, inModule) {
  1041. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1042. }
  1043. function isKeyword(word) {
  1044. return keywords$1.has(word);
  1045. }
  1046. const keywordRelationalOperator = /^in(stanceof)?$/;
  1047. function isIteratorStart(current, next) {
  1048. return current === 64 && next === 64;
  1049. }
  1050. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1051. const FlowErrors = Object.freeze({
  1052. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1053. 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",
  1054. AssignReservedType: "Cannot overwrite reserved type %0",
  1055. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1056. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1057. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1058. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1059. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1060. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1061. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1062. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1063. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1064. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1065. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1066. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1067. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1068. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1069. 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",
  1070. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1071. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1072. InexactVariance: "Explicit inexact syntax cannot have variance",
  1073. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1074. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1075. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1076. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1077. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1078. SpreadVariance: "Spread properties cannot have variance",
  1079. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1080. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1081. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1082. UnexpectedReservedType: "Unexpected reserved type %0",
  1083. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1084. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1085. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1086. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1087. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1088. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1089. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1090. UnterminatedFlowComment: "Unterminated flow-comment"
  1091. });
  1092. function isEsModuleType(bodyElement) {
  1093. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1094. }
  1095. function hasTypeImportKind(node) {
  1096. return node.importKind === "type" || node.importKind === "typeof";
  1097. }
  1098. function isMaybeDefaultImport(state) {
  1099. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1100. }
  1101. const exportSuggestions = {
  1102. const: "declare export var",
  1103. let: "declare export var",
  1104. type: "export type",
  1105. interface: "export interface"
  1106. };
  1107. function partition(list, test) {
  1108. const list1 = [];
  1109. const list2 = [];
  1110. for (let i = 0; i < list.length; i++) {
  1111. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1112. }
  1113. return [list1, list2];
  1114. }
  1115. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1116. var flow = (superClass => class extends superClass {
  1117. constructor(options, input) {
  1118. super(options, input);
  1119. this.flowPragma = undefined;
  1120. }
  1121. shouldParseTypes() {
  1122. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1123. }
  1124. shouldParseEnums() {
  1125. return !!this.getPluginOption("flow", "enums");
  1126. }
  1127. finishToken(type, val) {
  1128. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1129. if (this.flowPragma === undefined) {
  1130. this.flowPragma = null;
  1131. }
  1132. }
  1133. return super.finishToken(type, val);
  1134. }
  1135. addComment(comment) {
  1136. if (this.flowPragma === undefined) {
  1137. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1138. if (!matches) ; else if (matches[1] === "flow") {
  1139. this.flowPragma = "flow";
  1140. } else if (matches[1] === "noflow") {
  1141. this.flowPragma = "noflow";
  1142. } else {
  1143. throw new Error("Unexpected flow pragma");
  1144. }
  1145. }
  1146. return super.addComment(comment);
  1147. }
  1148. flowParseTypeInitialiser(tok) {
  1149. const oldInType = this.state.inType;
  1150. this.state.inType = true;
  1151. this.expect(tok || types.colon);
  1152. const type = this.flowParseType();
  1153. this.state.inType = oldInType;
  1154. return type;
  1155. }
  1156. flowParsePredicate() {
  1157. const node = this.startNode();
  1158. const moduloLoc = this.state.startLoc;
  1159. const moduloPos = this.state.start;
  1160. this.expect(types.modulo);
  1161. const checksLoc = this.state.startLoc;
  1162. this.expectContextual("checks");
  1163. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1164. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1165. }
  1166. if (this.eat(types.parenL)) {
  1167. node.value = this.parseExpression();
  1168. this.expect(types.parenR);
  1169. return this.finishNode(node, "DeclaredPredicate");
  1170. } else {
  1171. return this.finishNode(node, "InferredPredicate");
  1172. }
  1173. }
  1174. flowParseTypeAndPredicateInitialiser() {
  1175. const oldInType = this.state.inType;
  1176. this.state.inType = true;
  1177. this.expect(types.colon);
  1178. let type = null;
  1179. let predicate = null;
  1180. if (this.match(types.modulo)) {
  1181. this.state.inType = oldInType;
  1182. predicate = this.flowParsePredicate();
  1183. } else {
  1184. type = this.flowParseType();
  1185. this.state.inType = oldInType;
  1186. if (this.match(types.modulo)) {
  1187. predicate = this.flowParsePredicate();
  1188. }
  1189. }
  1190. return [type, predicate];
  1191. }
  1192. flowParseDeclareClass(node) {
  1193. this.next();
  1194. this.flowParseInterfaceish(node, true);
  1195. return this.finishNode(node, "DeclareClass");
  1196. }
  1197. flowParseDeclareFunction(node) {
  1198. this.next();
  1199. const id = node.id = this.parseIdentifier();
  1200. const typeNode = this.startNode();
  1201. const typeContainer = this.startNode();
  1202. if (this.isRelational("<")) {
  1203. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1204. } else {
  1205. typeNode.typeParameters = null;
  1206. }
  1207. this.expect(types.parenL);
  1208. const tmp = this.flowParseFunctionTypeParams();
  1209. typeNode.params = tmp.params;
  1210. typeNode.rest = tmp.rest;
  1211. this.expect(types.parenR);
  1212. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1213. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1214. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1215. this.resetEndLocation(id);
  1216. this.semicolon();
  1217. return this.finishNode(node, "DeclareFunction");
  1218. }
  1219. flowParseDeclare(node, insideModule) {
  1220. if (this.match(types._class)) {
  1221. return this.flowParseDeclareClass(node);
  1222. } else if (this.match(types._function)) {
  1223. return this.flowParseDeclareFunction(node);
  1224. } else if (this.match(types._var)) {
  1225. return this.flowParseDeclareVariable(node);
  1226. } else if (this.eatContextual("module")) {
  1227. if (this.match(types.dot)) {
  1228. return this.flowParseDeclareModuleExports(node);
  1229. } else {
  1230. if (insideModule) {
  1231. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1232. }
  1233. return this.flowParseDeclareModule(node);
  1234. }
  1235. } else if (this.isContextual("type")) {
  1236. return this.flowParseDeclareTypeAlias(node);
  1237. } else if (this.isContextual("opaque")) {
  1238. return this.flowParseDeclareOpaqueType(node);
  1239. } else if (this.isContextual("interface")) {
  1240. return this.flowParseDeclareInterface(node);
  1241. } else if (this.match(types._export)) {
  1242. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1243. } else {
  1244. throw this.unexpected();
  1245. }
  1246. }
  1247. flowParseDeclareVariable(node) {
  1248. this.next();
  1249. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1250. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1251. this.semicolon();
  1252. return this.finishNode(node, "DeclareVariable");
  1253. }
  1254. flowParseDeclareModule(node) {
  1255. this.scope.enter(SCOPE_OTHER);
  1256. if (this.match(types.string)) {
  1257. node.id = this.parseExprAtom();
  1258. } else {
  1259. node.id = this.parseIdentifier();
  1260. }
  1261. const bodyNode = node.body = this.startNode();
  1262. const body = bodyNode.body = [];
  1263. this.expect(types.braceL);
  1264. while (!this.match(types.braceR)) {
  1265. let bodyNode = this.startNode();
  1266. if (this.match(types._import)) {
  1267. this.next();
  1268. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1269. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1270. }
  1271. this.parseImport(bodyNode);
  1272. } else {
  1273. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1274. bodyNode = this.flowParseDeclare(bodyNode, true);
  1275. }
  1276. body.push(bodyNode);
  1277. }
  1278. this.scope.exit();
  1279. this.expect(types.braceR);
  1280. this.finishNode(bodyNode, "BlockStatement");
  1281. let kind = null;
  1282. let hasModuleExport = false;
  1283. body.forEach(bodyElement => {
  1284. if (isEsModuleType(bodyElement)) {
  1285. if (kind === "CommonJS") {
  1286. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1287. }
  1288. kind = "ES";
  1289. } else if (bodyElement.type === "DeclareModuleExports") {
  1290. if (hasModuleExport) {
  1291. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1292. }
  1293. if (kind === "ES") {
  1294. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1295. }
  1296. kind = "CommonJS";
  1297. hasModuleExport = true;
  1298. }
  1299. });
  1300. node.kind = kind || "CommonJS";
  1301. return this.finishNode(node, "DeclareModule");
  1302. }
  1303. flowParseDeclareExportDeclaration(node, insideModule) {
  1304. this.expect(types._export);
  1305. if (this.eat(types._default)) {
  1306. if (this.match(types._function) || this.match(types._class)) {
  1307. node.declaration = this.flowParseDeclare(this.startNode());
  1308. } else {
  1309. node.declaration = this.flowParseType();
  1310. this.semicolon();
  1311. }
  1312. node.default = true;
  1313. return this.finishNode(node, "DeclareExportDeclaration");
  1314. } else {
  1315. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1316. const label = this.state.value;
  1317. const suggestion = exportSuggestions[label];
  1318. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1319. }
  1320. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1321. node.declaration = this.flowParseDeclare(this.startNode());
  1322. node.default = false;
  1323. return this.finishNode(node, "DeclareExportDeclaration");
  1324. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1325. node = this.parseExport(node);
  1326. if (node.type === "ExportNamedDeclaration") {
  1327. node.type = "ExportDeclaration";
  1328. node.default = false;
  1329. delete node.exportKind;
  1330. }
  1331. node.type = "Declare" + node.type;
  1332. return node;
  1333. }
  1334. }
  1335. throw this.unexpected();
  1336. }
  1337. flowParseDeclareModuleExports(node) {
  1338. this.next();
  1339. this.expectContextual("exports");
  1340. node.typeAnnotation = this.flowParseTypeAnnotation();
  1341. this.semicolon();
  1342. return this.finishNode(node, "DeclareModuleExports");
  1343. }
  1344. flowParseDeclareTypeAlias(node) {
  1345. this.next();
  1346. this.flowParseTypeAlias(node);
  1347. node.type = "DeclareTypeAlias";
  1348. return node;
  1349. }
  1350. flowParseDeclareOpaqueType(node) {
  1351. this.next();
  1352. this.flowParseOpaqueType(node, true);
  1353. node.type = "DeclareOpaqueType";
  1354. return node;
  1355. }
  1356. flowParseDeclareInterface(node) {
  1357. this.next();
  1358. this.flowParseInterfaceish(node);
  1359. return this.finishNode(node, "DeclareInterface");
  1360. }
  1361. flowParseInterfaceish(node, isClass = false) {
  1362. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1363. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1364. if (this.isRelational("<")) {
  1365. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1366. } else {
  1367. node.typeParameters = null;
  1368. }
  1369. node.extends = [];
  1370. node.implements = [];
  1371. node.mixins = [];
  1372. if (this.eat(types._extends)) {
  1373. do {
  1374. node.extends.push(this.flowParseInterfaceExtends());
  1375. } while (!isClass && this.eat(types.comma));
  1376. }
  1377. if (this.isContextual("mixins")) {
  1378. this.next();
  1379. do {
  1380. node.mixins.push(this.flowParseInterfaceExtends());
  1381. } while (this.eat(types.comma));
  1382. }
  1383. if (this.isContextual("implements")) {
  1384. this.next();
  1385. do {
  1386. node.implements.push(this.flowParseInterfaceExtends());
  1387. } while (this.eat(types.comma));
  1388. }
  1389. node.body = this.flowParseObjectType({
  1390. allowStatic: isClass,
  1391. allowExact: false,
  1392. allowSpread: false,
  1393. allowProto: isClass,
  1394. allowInexact: false
  1395. });
  1396. }
  1397. flowParseInterfaceExtends() {
  1398. const node = this.startNode();
  1399. node.id = this.flowParseQualifiedTypeIdentifier();
  1400. if (this.isRelational("<")) {
  1401. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1402. } else {
  1403. node.typeParameters = null;
  1404. }
  1405. return this.finishNode(node, "InterfaceExtends");
  1406. }
  1407. flowParseInterface(node) {
  1408. this.flowParseInterfaceish(node);
  1409. return this.finishNode(node, "InterfaceDeclaration");
  1410. }
  1411. checkNotUnderscore(word) {
  1412. if (word === "_") {
  1413. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1414. }
  1415. }
  1416. checkReservedType(word, startLoc, declaration) {
  1417. if (!reservedTypes.has(word)) return;
  1418. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1419. }
  1420. flowParseRestrictedIdentifier(liberal, declaration) {
  1421. this.checkReservedType(this.state.value, this.state.start, declaration);
  1422. return this.parseIdentifier(liberal);
  1423. }
  1424. flowParseTypeAlias(node) {
  1425. node.id = this.flowParseRestrictedIdentifier(false, true);
  1426. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1427. if (this.isRelational("<")) {
  1428. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1429. } else {
  1430. node.typeParameters = null;
  1431. }
  1432. node.right = this.flowParseTypeInitialiser(types.eq);
  1433. this.semicolon();
  1434. return this.finishNode(node, "TypeAlias");
  1435. }
  1436. flowParseOpaqueType(node, declare) {
  1437. this.expectContextual("type");
  1438. node.id = this.flowParseRestrictedIdentifier(true, true);
  1439. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1440. if (this.isRelational("<")) {
  1441. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1442. } else {
  1443. node.typeParameters = null;
  1444. }
  1445. node.supertype = null;
  1446. if (this.match(types.colon)) {
  1447. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1448. }
  1449. node.impltype = null;
  1450. if (!declare) {
  1451. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1452. }
  1453. this.semicolon();
  1454. return this.finishNode(node, "OpaqueType");
  1455. }
  1456. flowParseTypeParameter(requireDefault = false) {
  1457. const nodeStart = this.state.start;
  1458. const node = this.startNode();
  1459. const variance = this.flowParseVariance();
  1460. const ident = this.flowParseTypeAnnotatableIdentifier();
  1461. node.name = ident.name;
  1462. node.variance = variance;
  1463. node.bound = ident.typeAnnotation;
  1464. if (this.match(types.eq)) {
  1465. this.eat(types.eq);
  1466. node.default = this.flowParseType();
  1467. } else {
  1468. if (requireDefault) {
  1469. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1470. }
  1471. }
  1472. return this.finishNode(node, "TypeParameter");
  1473. }
  1474. flowParseTypeParameterDeclaration() {
  1475. const oldInType = this.state.inType;
  1476. const node = this.startNode();
  1477. node.params = [];
  1478. this.state.inType = true;
  1479. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1480. this.next();
  1481. } else {
  1482. this.unexpected();
  1483. }
  1484. let defaultRequired = false;
  1485. do {
  1486. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1487. node.params.push(typeParameter);
  1488. if (typeParameter.default) {
  1489. defaultRequired = true;
  1490. }
  1491. if (!this.isRelational(">")) {
  1492. this.expect(types.comma);
  1493. }
  1494. } while (!this.isRelational(">"));
  1495. this.expectRelational(">");
  1496. this.state.inType = oldInType;
  1497. return this.finishNode(node, "TypeParameterDeclaration");
  1498. }
  1499. flowParseTypeParameterInstantiation() {
  1500. const node = this.startNode();
  1501. const oldInType = this.state.inType;
  1502. node.params = [];
  1503. this.state.inType = true;
  1504. this.expectRelational("<");
  1505. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1506. this.state.noAnonFunctionType = false;
  1507. while (!this.isRelational(">")) {
  1508. node.params.push(this.flowParseType());
  1509. if (!this.isRelational(">")) {
  1510. this.expect(types.comma);
  1511. }
  1512. }
  1513. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1514. this.expectRelational(">");
  1515. this.state.inType = oldInType;
  1516. return this.finishNode(node, "TypeParameterInstantiation");
  1517. }
  1518. flowParseTypeParameterInstantiationCallOrNew() {
  1519. const node = this.startNode();
  1520. const oldInType = this.state.inType;
  1521. node.params = [];
  1522. this.state.inType = true;
  1523. this.expectRelational("<");
  1524. while (!this.isRelational(">")) {
  1525. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1526. if (!this.isRelational(">")) {
  1527. this.expect(types.comma);
  1528. }
  1529. }
  1530. this.expectRelational(">");
  1531. this.state.inType = oldInType;
  1532. return this.finishNode(node, "TypeParameterInstantiation");
  1533. }
  1534. flowParseInterfaceType() {
  1535. const node = this.startNode();
  1536. this.expectContextual("interface");
  1537. node.extends = [];
  1538. if (this.eat(types._extends)) {
  1539. do {
  1540. node.extends.push(this.flowParseInterfaceExtends());
  1541. } while (this.eat(types.comma));
  1542. }
  1543. node.body = this.flowParseObjectType({
  1544. allowStatic: false,
  1545. allowExact: false,
  1546. allowSpread: false,
  1547. allowProto: false,
  1548. allowInexact: false
  1549. });
  1550. return this.finishNode(node, "InterfaceTypeAnnotation");
  1551. }
  1552. flowParseObjectPropertyKey() {
  1553. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1554. }
  1555. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1556. node.static = isStatic;
  1557. if (this.lookahead().type === types.colon) {
  1558. node.id = this.flowParseObjectPropertyKey();
  1559. node.key = this.flowParseTypeInitialiser();
  1560. } else {
  1561. node.id = null;
  1562. node.key = this.flowParseType();
  1563. }
  1564. this.expect(types.bracketR);
  1565. node.value = this.flowParseTypeInitialiser();
  1566. node.variance = variance;
  1567. return this.finishNode(node, "ObjectTypeIndexer");
  1568. }
  1569. flowParseObjectTypeInternalSlot(node, isStatic) {
  1570. node.static = isStatic;
  1571. node.id = this.flowParseObjectPropertyKey();
  1572. this.expect(types.bracketR);
  1573. this.expect(types.bracketR);
  1574. if (this.isRelational("<") || this.match(types.parenL)) {
  1575. node.method = true;
  1576. node.optional = false;
  1577. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1578. } else {
  1579. node.method = false;
  1580. if (this.eat(types.question)) {
  1581. node.optional = true;
  1582. }
  1583. node.value = this.flowParseTypeInitialiser();
  1584. }
  1585. return this.finishNode(node, "ObjectTypeInternalSlot");
  1586. }
  1587. flowParseObjectTypeMethodish(node) {
  1588. node.params = [];
  1589. node.rest = null;
  1590. node.typeParameters = null;
  1591. if (this.isRelational("<")) {
  1592. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1593. }
  1594. this.expect(types.parenL);
  1595. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1596. node.params.push(this.flowParseFunctionTypeParam());
  1597. if (!this.match(types.parenR)) {
  1598. this.expect(types.comma);
  1599. }
  1600. }
  1601. if (this.eat(types.ellipsis)) {
  1602. node.rest = this.flowParseFunctionTypeParam();
  1603. }
  1604. this.expect(types.parenR);
  1605. node.returnType = this.flowParseTypeInitialiser();
  1606. return this.finishNode(node, "FunctionTypeAnnotation");
  1607. }
  1608. flowParseObjectTypeCallProperty(node, isStatic) {
  1609. const valueNode = this.startNode();
  1610. node.static = isStatic;
  1611. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1612. return this.finishNode(node, "ObjectTypeCallProperty");
  1613. }
  1614. flowParseObjectType({
  1615. allowStatic,
  1616. allowExact,
  1617. allowSpread,
  1618. allowProto,
  1619. allowInexact
  1620. }) {
  1621. const oldInType = this.state.inType;
  1622. this.state.inType = true;
  1623. const nodeStart = this.startNode();
  1624. nodeStart.callProperties = [];
  1625. nodeStart.properties = [];
  1626. nodeStart.indexers = [];
  1627. nodeStart.internalSlots = [];
  1628. let endDelim;
  1629. let exact;
  1630. let inexact = false;
  1631. if (allowExact && this.match(types.braceBarL)) {
  1632. this.expect(types.braceBarL);
  1633. endDelim = types.braceBarR;
  1634. exact = true;
  1635. } else {
  1636. this.expect(types.braceL);
  1637. endDelim = types.braceR;
  1638. exact = false;
  1639. }
  1640. nodeStart.exact = exact;
  1641. while (!this.match(endDelim)) {
  1642. let isStatic = false;
  1643. let protoStart = null;
  1644. let inexactStart = null;
  1645. const node = this.startNode();
  1646. if (allowProto && this.isContextual("proto")) {
  1647. const lookahead = this.lookahead();
  1648. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1649. this.next();
  1650. protoStart = this.state.start;
  1651. allowStatic = false;
  1652. }
  1653. }
  1654. if (allowStatic && this.isContextual("static")) {
  1655. const lookahead = this.lookahead();
  1656. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1657. this.next();
  1658. isStatic = true;
  1659. }
  1660. }
  1661. const variance = this.flowParseVariance();
  1662. if (this.eat(types.bracketL)) {
  1663. if (protoStart != null) {
  1664. this.unexpected(protoStart);
  1665. }
  1666. if (this.eat(types.bracketL)) {
  1667. if (variance) {
  1668. this.unexpected(variance.start);
  1669. }
  1670. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1671. } else {
  1672. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1673. }
  1674. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1675. if (protoStart != null) {
  1676. this.unexpected(protoStart);
  1677. }
  1678. if (variance) {
  1679. this.unexpected(variance.start);
  1680. }
  1681. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1682. } else {
  1683. let kind = "init";
  1684. if (this.isContextual("get") || this.isContextual("set")) {
  1685. const lookahead = this.lookahead();
  1686. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1687. kind = this.state.value;
  1688. this.next();
  1689. }
  1690. }
  1691. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1692. if (propOrInexact === null) {
  1693. inexact = true;
  1694. inexactStart = this.state.lastTokStart;
  1695. } else {
  1696. nodeStart.properties.push(propOrInexact);
  1697. }
  1698. }
  1699. this.flowObjectTypeSemicolon();
  1700. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1701. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  1702. }
  1703. }
  1704. this.expect(endDelim);
  1705. if (allowSpread) {
  1706. nodeStart.inexact = inexact;
  1707. }
  1708. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1709. this.state.inType = oldInType;
  1710. return out;
  1711. }
  1712. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1713. if (this.eat(types.ellipsis)) {
  1714. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1715. if (isInexactToken) {
  1716. if (!allowSpread) {
  1717. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  1718. } else if (!allowInexact) {
  1719. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  1720. }
  1721. if (variance) {
  1722. this.raise(variance.start, FlowErrors.InexactVariance);
  1723. }
  1724. return null;
  1725. }
  1726. if (!allowSpread) {
  1727. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  1728. }
  1729. if (protoStart != null) {
  1730. this.unexpected(protoStart);
  1731. }
  1732. if (variance) {
  1733. this.raise(variance.start, FlowErrors.SpreadVariance);
  1734. }
  1735. node.argument = this.flowParseType();
  1736. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1737. } else {
  1738. node.key = this.flowParseObjectPropertyKey();
  1739. node.static = isStatic;
  1740. node.proto = protoStart != null;
  1741. node.kind = kind;
  1742. let optional = false;
  1743. if (this.isRelational("<") || this.match(types.parenL)) {
  1744. node.method = true;
  1745. if (protoStart != null) {
  1746. this.unexpected(protoStart);
  1747. }
  1748. if (variance) {
  1749. this.unexpected(variance.start);
  1750. }
  1751. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1752. if (kind === "get" || kind === "set") {
  1753. this.flowCheckGetterSetterParams(node);
  1754. }
  1755. } else {
  1756. if (kind !== "init") this.unexpected();
  1757. node.method = false;
  1758. if (this.eat(types.question)) {
  1759. optional = true;
  1760. }
  1761. node.value = this.flowParseTypeInitialiser();
  1762. node.variance = variance;
  1763. }
  1764. node.optional = optional;
  1765. return this.finishNode(node, "ObjectTypeProperty");
  1766. }
  1767. }
  1768. flowCheckGetterSetterParams(property) {
  1769. const paramCount = property.kind === "get" ? 0 : 1;
  1770. const start = property.start;
  1771. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1772. if (length !== paramCount) {
  1773. if (property.kind === "get") {
  1774. this.raise(start, Errors.BadGetterArity);
  1775. } else {
  1776. this.raise(start, Errors.BadSetterArity);
  1777. }
  1778. }
  1779. if (property.kind === "set" && property.value.rest) {
  1780. this.raise(start, Errors.BadSetterRestParameter);
  1781. }
  1782. }
  1783. flowObjectTypeSemicolon() {
  1784. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1785. this.unexpected();
  1786. }
  1787. }
  1788. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1789. startPos = startPos || this.state.start;
  1790. startLoc = startLoc || this.state.startLoc;
  1791. let node = id || this.flowParseRestrictedIdentifier(true);
  1792. while (this.eat(types.dot)) {
  1793. const node2 = this.startNodeAt(startPos, startLoc);
  1794. node2.qualification = node;
  1795. node2.id = this.flowParseRestrictedIdentifier(true);
  1796. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1797. }
  1798. return node;
  1799. }
  1800. flowParseGenericType(startPos, startLoc, id) {
  1801. const node = this.startNodeAt(startPos, startLoc);
  1802. node.typeParameters = null;
  1803. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1804. if (this.isRelational("<")) {
  1805. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1806. }
  1807. return this.finishNode(node, "GenericTypeAnnotation");
  1808. }
  1809. flowParseTypeofType() {
  1810. const node = this.startNode();
  1811. this.expect(types._typeof);
  1812. node.argument = this.flowParsePrimaryType();
  1813. return this.finishNode(node, "TypeofTypeAnnotation");
  1814. }
  1815. flowParseTupleType() {
  1816. const node = this.startNode();
  1817. node.types = [];
  1818. this.expect(types.bracketL);
  1819. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1820. node.types.push(this.flowParseType());
  1821. if (this.match(types.bracketR)) break;
  1822. this.expect(types.comma);
  1823. }
  1824. this.expect(types.bracketR);
  1825. return this.finishNode(node, "TupleTypeAnnotation");
  1826. }
  1827. flowParseFunctionTypeParam() {
  1828. let name = null;
  1829. let optional = false;
  1830. let typeAnnotation = null;
  1831. const node = this.startNode();
  1832. const lh = this.lookahead();
  1833. if (lh.type === types.colon || lh.type === types.question) {
  1834. name = this.parseIdentifier();
  1835. if (this.eat(types.question)) {
  1836. optional = true;
  1837. }
  1838. typeAnnotation = this.flowParseTypeInitialiser();
  1839. } else {
  1840. typeAnnotation = this.flowParseType();
  1841. }
  1842. node.name = name;
  1843. node.optional = optional;
  1844. node.typeAnnotation = typeAnnotation;
  1845. return this.finishNode(node, "FunctionTypeParam");
  1846. }
  1847. reinterpretTypeAsFunctionTypeParam(type) {
  1848. const node = this.startNodeAt(type.start, type.loc.start);
  1849. node.name = null;
  1850. node.optional = false;
  1851. node.typeAnnotation = type;
  1852. return this.finishNode(node, "FunctionTypeParam");
  1853. }
  1854. flowParseFunctionTypeParams(params = []) {
  1855. let rest = null;
  1856. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1857. params.push(this.flowParseFunctionTypeParam());
  1858. if (!this.match(types.parenR)) {
  1859. this.expect(types.comma);
  1860. }
  1861. }
  1862. if (this.eat(types.ellipsis)) {
  1863. rest = this.flowParseFunctionTypeParam();
  1864. }
  1865. return {
  1866. params,
  1867. rest
  1868. };
  1869. }
  1870. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1871. switch (id.name) {
  1872. case "any":
  1873. return this.finishNode(node, "AnyTypeAnnotation");
  1874. case "bool":
  1875. case "boolean":
  1876. return this.finishNode(node, "BooleanTypeAnnotation");
  1877. case "mixed":
  1878. return this.finishNode(node, "MixedTypeAnnotation");
  1879. case "empty":
  1880. return this.finishNode(node, "EmptyTypeAnnotation");
  1881. case "number":
  1882. return this.finishNode(node, "NumberTypeAnnotation");
  1883. case "string":
  1884. return this.finishNode(node, "StringTypeAnnotation");
  1885. case "symbol":
  1886. return this.finishNode(node, "SymbolTypeAnnotation");
  1887. default:
  1888. this.checkNotUnderscore(id.name);
  1889. return this.flowParseGenericType(startPos, startLoc, id);
  1890. }
  1891. }
  1892. flowParsePrimaryType() {
  1893. const startPos = this.state.start;
  1894. const startLoc = this.state.startLoc;
  1895. const node = this.startNode();
  1896. let tmp;
  1897. let type;
  1898. let isGroupedType = false;
  1899. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1900. switch (this.state.type) {
  1901. case types.name:
  1902. if (this.isContextual("interface")) {
  1903. return this.flowParseInterfaceType();
  1904. }
  1905. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1906. case types.braceL:
  1907. return this.flowParseObjectType({
  1908. allowStatic: false,
  1909. allowExact: false,
  1910. allowSpread: true,
  1911. allowProto: false,
  1912. allowInexact: true
  1913. });
  1914. case types.braceBarL:
  1915. return this.flowParseObjectType({
  1916. allowStatic: false,
  1917. allowExact: true,
  1918. allowSpread: true,
  1919. allowProto: false,
  1920. allowInexact: false
  1921. });
  1922. case types.bracketL:
  1923. this.state.noAnonFunctionType = false;
  1924. type = this.flowParseTupleType();
  1925. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1926. return type;
  1927. case types.relational:
  1928. if (this.state.value === "<") {
  1929. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1930. this.expect(types.parenL);
  1931. tmp = this.flowParseFunctionTypeParams();
  1932. node.params = tmp.params;
  1933. node.rest = tmp.rest;
  1934. this.expect(types.parenR);
  1935. this.expect(types.arrow);
  1936. node.returnType = this.flowParseType();
  1937. return this.finishNode(node, "FunctionTypeAnnotation");
  1938. }
  1939. break;
  1940. case types.parenL:
  1941. this.next();
  1942. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1943. if (this.match(types.name)) {
  1944. const token = this.lookahead().type;
  1945. isGroupedType = token !== types.question && token !== types.colon;
  1946. } else {
  1947. isGroupedType = true;
  1948. }
  1949. }
  1950. if (isGroupedType) {
  1951. this.state.noAnonFunctionType = false;
  1952. type = this.flowParseType();
  1953. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1954. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  1955. this.expect(types.parenR);
  1956. return type;
  1957. } else {
  1958. this.eat(types.comma);
  1959. }
  1960. }
  1961. if (type) {
  1962. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  1963. } else {
  1964. tmp = this.flowParseFunctionTypeParams();
  1965. }
  1966. node.params = tmp.params;
  1967. node.rest = tmp.rest;
  1968. this.expect(types.parenR);
  1969. this.expect(types.arrow);
  1970. node.returnType = this.flowParseType();
  1971. node.typeParameters = null;
  1972. return this.finishNode(node, "FunctionTypeAnnotation");
  1973. case types.string:
  1974. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  1975. case types._true:
  1976. case types._false:
  1977. node.value = this.match(types._true);
  1978. this.next();
  1979. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  1980. case types.plusMin:
  1981. if (this.state.value === "-") {
  1982. this.next();
  1983. if (this.match(types.num)) {
  1984. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  1985. }
  1986. if (this.match(types.bigint)) {
  1987. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  1988. }
  1989. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  1990. }
  1991. throw this.unexpected();
  1992. case types.num:
  1993. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  1994. case types.bigint:
  1995. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  1996. case types._void:
  1997. this.next();
  1998. return this.finishNode(node, "VoidTypeAnnotation");
  1999. case types._null:
  2000. this.next();
  2001. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2002. case types._this:
  2003. this.next();
  2004. return this.finishNode(node, "ThisTypeAnnotation");
  2005. case types.star:
  2006. this.next();
  2007. return this.finishNode(node, "ExistsTypeAnnotation");
  2008. default:
  2009. if (this.state.type.keyword === "typeof") {
  2010. return this.flowParseTypeofType();
  2011. } else if (this.state.type.keyword) {
  2012. const label = this.state.type.label;
  2013. this.next();
  2014. return super.createIdentifier(node, label);
  2015. }
  2016. }
  2017. throw this.unexpected();
  2018. }
  2019. flowParsePostfixType() {
  2020. const startPos = this.state.start,
  2021. startLoc = this.state.startLoc;
  2022. let type = this.flowParsePrimaryType();
  2023. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2024. const node = this.startNodeAt(startPos, startLoc);
  2025. node.elementType = type;
  2026. this.expect(types.bracketL);
  2027. this.expect(types.bracketR);
  2028. type = this.finishNode(node, "ArrayTypeAnnotation");
  2029. }
  2030. return type;
  2031. }
  2032. flowParsePrefixType() {
  2033. const node = this.startNode();
  2034. if (this.eat(types.question)) {
  2035. node.typeAnnotation = this.flowParsePrefixType();
  2036. return this.finishNode(node, "NullableTypeAnnotation");
  2037. } else {
  2038. return this.flowParsePostfixType();
  2039. }
  2040. }
  2041. flowParseAnonFunctionWithoutParens() {
  2042. const param = this.flowParsePrefixType();
  2043. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2044. const node = this.startNodeAt(param.start, param.loc.start);
  2045. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2046. node.rest = null;
  2047. node.returnType = this.flowParseType();
  2048. node.typeParameters = null;
  2049. return this.finishNode(node, "FunctionTypeAnnotation");
  2050. }
  2051. return param;
  2052. }
  2053. flowParseIntersectionType() {
  2054. const node = this.startNode();
  2055. this.eat(types.bitwiseAND);
  2056. const type = this.flowParseAnonFunctionWithoutParens();
  2057. node.types = [type];
  2058. while (this.eat(types.bitwiseAND)) {
  2059. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2060. }
  2061. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2062. }
  2063. flowParseUnionType() {
  2064. const node = this.startNode();
  2065. this.eat(types.bitwiseOR);
  2066. const type = this.flowParseIntersectionType();
  2067. node.types = [type];
  2068. while (this.eat(types.bitwiseOR)) {
  2069. node.types.push(this.flowParseIntersectionType());
  2070. }
  2071. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2072. }
  2073. flowParseType() {
  2074. const oldInType = this.state.inType;
  2075. this.state.inType = true;
  2076. const type = this.flowParseUnionType();
  2077. this.state.inType = oldInType;
  2078. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2079. return type;
  2080. }
  2081. flowParseTypeOrImplicitInstantiation() {
  2082. if (this.state.type === types.name && this.state.value === "_") {
  2083. const startPos = this.state.start;
  2084. const startLoc = this.state.startLoc;
  2085. const node = this.parseIdentifier();
  2086. return this.flowParseGenericType(startPos, startLoc, node);
  2087. } else {
  2088. return this.flowParseType();
  2089. }
  2090. }
  2091. flowParseTypeAnnotation() {
  2092. const node = this.startNode();
  2093. node.typeAnnotation = this.flowParseTypeInitialiser();
  2094. return this.finishNode(node, "TypeAnnotation");
  2095. }
  2096. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2097. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2098. if (this.match(types.colon)) {
  2099. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2100. this.resetEndLocation(ident);
  2101. }
  2102. return ident;
  2103. }
  2104. typeCastToParameter(node) {
  2105. node.expression.typeAnnotation = node.typeAnnotation;
  2106. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2107. return node.expression;
  2108. }
  2109. flowParseVariance() {
  2110. let variance = null;
  2111. if (this.match(types.plusMin)) {
  2112. variance = this.startNode();
  2113. if (this.state.value === "+") {
  2114. variance.kind = "plus";
  2115. } else {
  2116. variance.kind = "minus";
  2117. }
  2118. this.next();
  2119. this.finishNode(variance, "Variance");
  2120. }
  2121. return variance;
  2122. }
  2123. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2124. if (allowExpressionBody) {
  2125. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2126. }
  2127. return super.parseFunctionBody(node, false, isMethod);
  2128. }
  2129. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2130. if (this.match(types.colon)) {
  2131. const typeNode = this.startNode();
  2132. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2133. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2134. }
  2135. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2136. }
  2137. parseStatement(context, topLevel) {
  2138. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2139. const node = this.startNode();
  2140. this.next();
  2141. return this.flowParseInterface(node);
  2142. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2143. const node = this.startNode();
  2144. this.next();
  2145. return this.flowParseEnumDeclaration(node);
  2146. } else {
  2147. const stmt = super.parseStatement(context, topLevel);
  2148. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2149. this.flowPragma = null;
  2150. }
  2151. return stmt;
  2152. }
  2153. }
  2154. parseExpressionStatement(node, expr) {
  2155. if (expr.type === "Identifier") {
  2156. if (expr.name === "declare") {
  2157. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2158. return this.flowParseDeclare(node);
  2159. }
  2160. } else if (this.match(types.name)) {
  2161. if (expr.name === "interface") {
  2162. return this.flowParseInterface(node);
  2163. } else if (expr.name === "type") {
  2164. return this.flowParseTypeAlias(node);
  2165. } else if (expr.name === "opaque") {
  2166. return this.flowParseOpaqueType(node, false);
  2167. }
  2168. }
  2169. }
  2170. return super.parseExpressionStatement(node, expr);
  2171. }
  2172. shouldParseExportDeclaration() {
  2173. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2174. }
  2175. isExportDefaultSpecifier() {
  2176. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2177. return false;
  2178. }
  2179. return super.isExportDefaultSpecifier();
  2180. }
  2181. parseExportDefaultExpression() {
  2182. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2183. const node = this.startNode();
  2184. this.next();
  2185. return this.flowParseEnumDeclaration(node);
  2186. }
  2187. return super.parseExportDefaultExpression();
  2188. }
  2189. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  2190. if (!this.match(types.question)) return expr;
  2191. if (refNeedsArrowPos) {
  2192. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  2193. if (!result.node) {
  2194. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2195. return expr;
  2196. }
  2197. if (result.error) this.state = result.failState;
  2198. return result.node;
  2199. }
  2200. this.expect(types.question);
  2201. const state = this.state.clone();
  2202. const originalNoArrowAt = this.state.noArrowAt;
  2203. const node = this.startNodeAt(startPos, startLoc);
  2204. let {
  2205. consequent,
  2206. failed
  2207. } = this.tryParseConditionalConsequent();
  2208. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2209. if (failed || invalid.length > 0) {
  2210. const noArrowAt = [...originalNoArrowAt];
  2211. if (invalid.length > 0) {
  2212. this.state = state;
  2213. this.state.noArrowAt = noArrowAt;
  2214. for (let i = 0; i < invalid.length; i++) {
  2215. noArrowAt.push(invalid[i].start);
  2216. }
  2217. ({
  2218. consequent,
  2219. failed
  2220. } = this.tryParseConditionalConsequent());
  2221. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2222. }
  2223. if (failed && valid.length > 1) {
  2224. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2225. }
  2226. if (failed && valid.length === 1) {
  2227. this.state = state;
  2228. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2229. ({
  2230. consequent,
  2231. failed
  2232. } = this.tryParseConditionalConsequent());
  2233. }
  2234. }
  2235. this.getArrowLikeExpressions(consequent, true);
  2236. this.state.noArrowAt = originalNoArrowAt;
  2237. this.expect(types.colon);
  2238. node.test = expr;
  2239. node.consequent = consequent;
  2240. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(noIn, undefined, undefined, undefined));
  2241. return this.finishNode(node, "ConditionalExpression");
  2242. }
  2243. tryParseConditionalConsequent() {
  2244. this.state.noArrowParamsConversionAt.push(this.state.start);
  2245. const consequent = this.parseMaybeAssign();
  2246. const failed = !this.match(types.colon);
  2247. this.state.noArrowParamsConversionAt.pop();
  2248. return {
  2249. consequent,
  2250. failed
  2251. };
  2252. }
  2253. getArrowLikeExpressions(node, disallowInvalid) {
  2254. const stack = [node];
  2255. const arrows = [];
  2256. while (stack.length !== 0) {
  2257. const node = stack.pop();
  2258. if (node.type === "ArrowFunctionExpression") {
  2259. if (node.typeParameters || !node.returnType) {
  2260. this.finishArrowValidation(node);
  2261. } else {
  2262. arrows.push(node);
  2263. }
  2264. stack.push(node.body);
  2265. } else if (node.type === "ConditionalExpression") {
  2266. stack.push(node.consequent);
  2267. stack.push(node.alternate);
  2268. }
  2269. }
  2270. if (disallowInvalid) {
  2271. arrows.forEach(node => this.finishArrowValidation(node));
  2272. return [arrows, []];
  2273. }
  2274. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2275. }
  2276. finishArrowValidation(node) {
  2277. var _node$extra;
  2278. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma);
  2279. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2280. super.checkParams(node, false, true);
  2281. this.scope.exit();
  2282. }
  2283. forwardNoArrowParamsConversionAt(node, parse) {
  2284. let result;
  2285. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2286. this.state.noArrowParamsConversionAt.push(this.state.start);
  2287. result = parse();
  2288. this.state.noArrowParamsConversionAt.pop();
  2289. } else {
  2290. result = parse();
  2291. }
  2292. return result;
  2293. }
  2294. parseParenItem(node, startPos, startLoc) {
  2295. node = super.parseParenItem(node, startPos, startLoc);
  2296. if (this.eat(types.question)) {
  2297. node.optional = true;
  2298. this.resetEndLocation(node);
  2299. }
  2300. if (this.match(types.colon)) {
  2301. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2302. typeCastNode.expression = node;
  2303. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2304. return this.finishNode(typeCastNode, "TypeCastExpression");
  2305. }
  2306. return node;
  2307. }
  2308. assertModuleNodeAllowed(node) {
  2309. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2310. return;
  2311. }
  2312. super.assertModuleNodeAllowed(node);
  2313. }
  2314. parseExport(node) {
  2315. const decl = super.parseExport(node);
  2316. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2317. decl.exportKind = decl.exportKind || "value";
  2318. }
  2319. return decl;
  2320. }
  2321. parseExportDeclaration(node) {
  2322. if (this.isContextual("type")) {
  2323. node.exportKind = "type";
  2324. const declarationNode = this.startNode();
  2325. this.next();
  2326. if (this.match(types.braceL)) {
  2327. node.specifiers = this.parseExportSpecifiers();
  2328. this.parseExportFrom(node);
  2329. return null;
  2330. } else {
  2331. return this.flowParseTypeAlias(declarationNode);
  2332. }
  2333. } else if (this.isContextual("opaque")) {
  2334. node.exportKind = "type";
  2335. const declarationNode = this.startNode();
  2336. this.next();
  2337. return this.flowParseOpaqueType(declarationNode, false);
  2338. } else if (this.isContextual("interface")) {
  2339. node.exportKind = "type";
  2340. const declarationNode = this.startNode();
  2341. this.next();
  2342. return this.flowParseInterface(declarationNode);
  2343. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2344. node.exportKind = "value";
  2345. const declarationNode = this.startNode();
  2346. this.next();
  2347. return this.flowParseEnumDeclaration(declarationNode);
  2348. } else {
  2349. return super.parseExportDeclaration(node);
  2350. }
  2351. }
  2352. eatExportStar(node) {
  2353. if (super.eatExportStar(...arguments)) return true;
  2354. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2355. node.exportKind = "type";
  2356. this.next();
  2357. this.next();
  2358. return true;
  2359. }
  2360. return false;
  2361. }
  2362. maybeParseExportNamespaceSpecifier(node) {
  2363. const pos = this.state.start;
  2364. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2365. if (hasNamespace && node.exportKind === "type") {
  2366. this.unexpected(pos);
  2367. }
  2368. return hasNamespace;
  2369. }
  2370. parseClassId(node, isStatement, optionalId) {
  2371. super.parseClassId(node, isStatement, optionalId);
  2372. if (this.isRelational("<")) {
  2373. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2374. }
  2375. }
  2376. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  2377. const pos = this.state.start;
  2378. if (this.isContextual("declare")) {
  2379. if (this.parseClassMemberFromModifier(classBody, member)) {
  2380. return;
  2381. }
  2382. member.declare = true;
  2383. }
  2384. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  2385. if (member.declare) {
  2386. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  2387. this.raise(pos, FlowErrors.DeclareClassElement);
  2388. } else if (member.value) {
  2389. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2390. }
  2391. }
  2392. }
  2393. getTokenFromCode(code) {
  2394. const next = this.input.charCodeAt(this.state.pos + 1);
  2395. if (code === 123 && next === 124) {
  2396. return this.finishOp(types.braceBarL, 2);
  2397. } else if (this.state.inType && (code === 62 || code === 60)) {
  2398. return this.finishOp(types.relational, 1);
  2399. } else if (isIteratorStart(code, next)) {
  2400. this.state.isIterator = true;
  2401. return super.readWord();
  2402. } else {
  2403. return super.getTokenFromCode(code);
  2404. }
  2405. }
  2406. isAssignable(node, isBinding) {
  2407. switch (node.type) {
  2408. case "Identifier":
  2409. case "ObjectPattern":
  2410. case "ArrayPattern":
  2411. case "AssignmentPattern":
  2412. return true;
  2413. case "ObjectExpression":
  2414. {
  2415. const last = node.properties.length - 1;
  2416. return node.properties.every((prop, i) => {
  2417. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2418. });
  2419. }
  2420. case "ObjectProperty":
  2421. return this.isAssignable(node.value);
  2422. case "SpreadElement":
  2423. return this.isAssignable(node.argument);
  2424. case "ArrayExpression":
  2425. return node.elements.every(element => this.isAssignable(element));
  2426. case "AssignmentExpression":
  2427. return node.operator === "=";
  2428. case "ParenthesizedExpression":
  2429. case "TypeCastExpression":
  2430. return this.isAssignable(node.expression);
  2431. case "MemberExpression":
  2432. case "OptionalMemberExpression":
  2433. return !isBinding;
  2434. default:
  2435. return false;
  2436. }
  2437. }
  2438. toAssignable(node) {
  2439. if (node.type === "TypeCastExpression") {
  2440. return super.toAssignable(this.typeCastToParameter(node));
  2441. } else {
  2442. return super.toAssignable(node);
  2443. }
  2444. }
  2445. toAssignableList(exprList, trailingCommaPos) {
  2446. for (let i = 0; i < exprList.length; i++) {
  2447. const expr = exprList[i];
  2448. if (expr && expr.type === "TypeCastExpression") {
  2449. exprList[i] = this.typeCastToParameter(expr);
  2450. }
  2451. }
  2452. return super.toAssignableList(exprList, trailingCommaPos);
  2453. }
  2454. toReferencedList(exprList, isParenthesizedExpr) {
  2455. for (let i = 0; i < exprList.length; i++) {
  2456. const expr = exprList[i];
  2457. if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2458. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2459. }
  2460. }
  2461. return exprList;
  2462. }
  2463. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  2464. if (expr.type !== "TypeCastExpression") {
  2465. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  2466. }
  2467. }
  2468. parseClassProperty(node) {
  2469. if (this.match(types.colon)) {
  2470. node.typeAnnotation = this.flowParseTypeAnnotation();
  2471. }
  2472. return super.parseClassProperty(node);
  2473. }
  2474. parseClassPrivateProperty(node) {
  2475. if (this.match(types.colon)) {
  2476. node.typeAnnotation = this.flowParseTypeAnnotation();
  2477. }
  2478. return super.parseClassPrivateProperty(node);
  2479. }
  2480. isClassMethod() {
  2481. return this.isRelational("<") || super.isClassMethod();
  2482. }
  2483. isClassProperty() {
  2484. return this.match(types.colon) || super.isClassProperty();
  2485. }
  2486. isNonstaticConstructor(method) {
  2487. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2488. }
  2489. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2490. if (method.variance) {
  2491. this.unexpected(method.variance.start);
  2492. }
  2493. delete method.variance;
  2494. if (this.isRelational("<")) {
  2495. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2496. }
  2497. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2498. }
  2499. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2500. if (method.variance) {
  2501. this.unexpected(method.variance.start);
  2502. }
  2503. delete method.variance;
  2504. if (this.isRelational("<")) {
  2505. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2506. }
  2507. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2508. }
  2509. parseClassSuper(node) {
  2510. super.parseClassSuper(node);
  2511. if (node.superClass && this.isRelational("<")) {
  2512. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2513. }
  2514. if (this.isContextual("implements")) {
  2515. this.next();
  2516. const implemented = node.implements = [];
  2517. do {
  2518. const node = this.startNode();
  2519. node.id = this.flowParseRestrictedIdentifier(true);
  2520. if (this.isRelational("<")) {
  2521. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2522. } else {
  2523. node.typeParameters = null;
  2524. }
  2525. implemented.push(this.finishNode(node, "ClassImplements"));
  2526. } while (this.eat(types.comma));
  2527. }
  2528. }
  2529. parsePropertyName(node, isPrivateNameAllowed) {
  2530. const variance = this.flowParseVariance();
  2531. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2532. node.variance = variance;
  2533. return key;
  2534. }
  2535. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  2536. if (prop.variance) {
  2537. this.unexpected(prop.variance.start);
  2538. }
  2539. delete prop.variance;
  2540. let typeParameters;
  2541. if (this.isRelational("<")) {
  2542. typeParameters = this.flowParseTypeParameterDeclaration();
  2543. if (!this.match(types.parenL)) this.unexpected();
  2544. }
  2545. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  2546. if (typeParameters) {
  2547. (prop.value || prop).typeParameters = typeParameters;
  2548. }
  2549. }
  2550. parseAssignableListItemTypes(param) {
  2551. if (this.eat(types.question)) {
  2552. if (param.type !== "Identifier") {
  2553. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  2554. }
  2555. param.optional = true;
  2556. }
  2557. if (this.match(types.colon)) {
  2558. param.typeAnnotation = this.flowParseTypeAnnotation();
  2559. }
  2560. this.resetEndLocation(param);
  2561. return param;
  2562. }
  2563. parseMaybeDefault(startPos, startLoc, left) {
  2564. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2565. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2566. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  2567. }
  2568. return node;
  2569. }
  2570. shouldParseDefaultImport(node) {
  2571. if (!hasTypeImportKind(node)) {
  2572. return super.shouldParseDefaultImport(node);
  2573. }
  2574. return isMaybeDefaultImport(this.state);
  2575. }
  2576. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2577. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2578. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  2579. node.specifiers.push(this.finishNode(specifier, type));
  2580. }
  2581. maybeParseDefaultImportSpecifier(node) {
  2582. node.importKind = "value";
  2583. let kind = null;
  2584. if (this.match(types._typeof)) {
  2585. kind = "typeof";
  2586. } else if (this.isContextual("type")) {
  2587. kind = "type";
  2588. }
  2589. if (kind) {
  2590. const lh = this.lookahead();
  2591. if (kind === "type" && lh.type === types.star) {
  2592. this.unexpected(lh.start);
  2593. }
  2594. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2595. this.next();
  2596. node.importKind = kind;
  2597. }
  2598. }
  2599. return super.maybeParseDefaultImportSpecifier(node);
  2600. }
  2601. parseImportSpecifier(node) {
  2602. const specifier = this.startNode();
  2603. const firstIdentLoc = this.state.start;
  2604. const firstIdent = this.parseIdentifier(true);
  2605. let specifierTypeKind = null;
  2606. if (firstIdent.name === "type") {
  2607. specifierTypeKind = "type";
  2608. } else if (firstIdent.name === "typeof") {
  2609. specifierTypeKind = "typeof";
  2610. }
  2611. let isBinding = false;
  2612. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2613. const as_ident = this.parseIdentifier(true);
  2614. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2615. specifier.imported = as_ident;
  2616. specifier.importKind = specifierTypeKind;
  2617. specifier.local = as_ident.__clone();
  2618. } else {
  2619. specifier.imported = firstIdent;
  2620. specifier.importKind = null;
  2621. specifier.local = this.parseIdentifier();
  2622. }
  2623. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2624. specifier.imported = this.parseIdentifier(true);
  2625. specifier.importKind = specifierTypeKind;
  2626. if (this.eatContextual("as")) {
  2627. specifier.local = this.parseIdentifier();
  2628. } else {
  2629. isBinding = true;
  2630. specifier.local = specifier.imported.__clone();
  2631. }
  2632. } else {
  2633. isBinding = true;
  2634. specifier.imported = firstIdent;
  2635. specifier.importKind = null;
  2636. specifier.local = specifier.imported.__clone();
  2637. }
  2638. const nodeIsTypeImport = hasTypeImportKind(node);
  2639. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2640. if (nodeIsTypeImport && specifierIsTypeImport) {
  2641. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  2642. }
  2643. if (nodeIsTypeImport || specifierIsTypeImport) {
  2644. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2645. }
  2646. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2647. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2648. }
  2649. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2650. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2651. }
  2652. parseFunctionParams(node, allowModifiers) {
  2653. const kind = node.kind;
  2654. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2655. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2656. }
  2657. super.parseFunctionParams(node, allowModifiers);
  2658. }
  2659. parseVarId(decl, kind) {
  2660. super.parseVarId(decl, kind);
  2661. if (this.match(types.colon)) {
  2662. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2663. this.resetEndLocation(decl.id);
  2664. }
  2665. }
  2666. parseAsyncArrowFromCallExpression(node, call) {
  2667. if (this.match(types.colon)) {
  2668. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2669. this.state.noAnonFunctionType = true;
  2670. node.returnType = this.flowParseTypeAnnotation();
  2671. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2672. }
  2673. return super.parseAsyncArrowFromCallExpression(node, call);
  2674. }
  2675. shouldParseAsyncArrow() {
  2676. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2677. }
  2678. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  2679. let state = null;
  2680. let jsx;
  2681. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2682. state = this.state.clone();
  2683. jsx = this.tryParse(() => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  2684. if (!jsx.error) return jsx.node;
  2685. const {
  2686. context
  2687. } = this.state;
  2688. if (context[context.length - 1] === types$1.j_oTag) {
  2689. context.length -= 2;
  2690. } else if (context[context.length - 1] === types$1.j_expr) {
  2691. context.length -= 1;
  2692. }
  2693. }
  2694. if (jsx && jsx.error || this.isRelational("<")) {
  2695. state = state || this.state.clone();
  2696. let typeParameters;
  2697. const arrow = this.tryParse(() => {
  2698. typeParameters = this.flowParseTypeParameterDeclaration();
  2699. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  2700. arrowExpression.typeParameters = typeParameters;
  2701. this.resetStartLocationFromNode(arrowExpression, typeParameters);
  2702. return arrowExpression;
  2703. }, state);
  2704. const arrowExpression = arrow.node && arrow.node.type === "ArrowFunctionExpression" ? arrow.node : null;
  2705. if (!arrow.error && arrowExpression) return arrowExpression;
  2706. if (jsx && jsx.node) {
  2707. this.state = jsx.failState;
  2708. return jsx.node;
  2709. }
  2710. if (arrowExpression) {
  2711. this.state = arrow.failState;
  2712. return arrowExpression;
  2713. }
  2714. if (jsx && jsx.thrown) throw jsx.error;
  2715. if (arrow.thrown) throw arrow.error;
  2716. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  2717. }
  2718. return super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2719. }
  2720. parseArrow(node) {
  2721. if (this.match(types.colon)) {
  2722. const result = this.tryParse(() => {
  2723. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2724. this.state.noAnonFunctionType = true;
  2725. const typeNode = this.startNode();
  2726. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2727. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2728. if (this.canInsertSemicolon()) this.unexpected();
  2729. if (!this.match(types.arrow)) this.unexpected();
  2730. return typeNode;
  2731. });
  2732. if (result.thrown) return null;
  2733. if (result.error) this.state = result.failState;
  2734. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2735. }
  2736. return super.parseArrow(node);
  2737. }
  2738. shouldParseArrow() {
  2739. return this.match(types.colon) || super.shouldParseArrow();
  2740. }
  2741. setArrowFunctionParameters(node, params) {
  2742. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2743. node.params = params;
  2744. } else {
  2745. super.setArrowFunctionParameters(node, params);
  2746. }
  2747. }
  2748. checkParams(node, allowDuplicates, isArrowFunction) {
  2749. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2750. return;
  2751. }
  2752. return super.checkParams(...arguments);
  2753. }
  2754. parseParenAndDistinguishExpression(canBeArrow) {
  2755. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2756. }
  2757. parseSubscripts(base, startPos, startLoc, noCalls) {
  2758. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2759. this.next();
  2760. const node = this.startNodeAt(startPos, startLoc);
  2761. node.callee = base;
  2762. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2763. base = this.finishNode(node, "CallExpression");
  2764. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2765. const state = this.state.clone();
  2766. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2767. if (!arrow.error && !arrow.aborted) return arrow.node;
  2768. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2769. if (result.node && !result.error) return result.node;
  2770. if (arrow.node) {
  2771. this.state = arrow.failState;
  2772. return arrow.node;
  2773. }
  2774. if (result.node) {
  2775. this.state = result.failState;
  2776. return result.node;
  2777. }
  2778. throw arrow.error || result.error;
  2779. }
  2780. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2781. }
  2782. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2783. if (this.match(types.questionDot) && this.isLookaheadRelational("<")) {
  2784. subscriptState.optionalChainMember = true;
  2785. if (noCalls) {
  2786. subscriptState.stop = true;
  2787. return base;
  2788. }
  2789. this.next();
  2790. const node = this.startNodeAt(startPos, startLoc);
  2791. node.callee = base;
  2792. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2793. this.expect(types.parenL);
  2794. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2795. node.optional = true;
  2796. return this.finishCallExpression(node, true);
  2797. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2798. const node = this.startNodeAt(startPos, startLoc);
  2799. node.callee = base;
  2800. const result = this.tryParse(() => {
  2801. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2802. this.expect(types.parenL);
  2803. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2804. if (subscriptState.optionalChainMember) node.optional = false;
  2805. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2806. });
  2807. if (result.node) {
  2808. if (result.error) this.state = result.failState;
  2809. return result.node;
  2810. }
  2811. }
  2812. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2813. }
  2814. parseNewArguments(node) {
  2815. let targs = null;
  2816. if (this.shouldParseTypes() && this.isRelational("<")) {
  2817. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2818. }
  2819. node.typeArguments = targs;
  2820. super.parseNewArguments(node);
  2821. }
  2822. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2823. const node = this.startNodeAt(startPos, startLoc);
  2824. this.parseFunctionParams(node);
  2825. if (!this.parseArrow(node)) return;
  2826. return this.parseArrowExpression(node, undefined, true);
  2827. }
  2828. readToken_mult_modulo(code) {
  2829. const next = this.input.charCodeAt(this.state.pos + 1);
  2830. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2831. this.state.hasFlowComment = false;
  2832. this.state.pos += 2;
  2833. this.nextToken();
  2834. return;
  2835. }
  2836. super.readToken_mult_modulo(code);
  2837. }
  2838. readToken_pipe_amp(code) {
  2839. const next = this.input.charCodeAt(this.state.pos + 1);
  2840. if (code === 124 && next === 125) {
  2841. this.finishOp(types.braceBarR, 2);
  2842. return;
  2843. }
  2844. super.readToken_pipe_amp(code);
  2845. }
  2846. parseTopLevel(file, program) {
  2847. const fileNode = super.parseTopLevel(file, program);
  2848. if (this.state.hasFlowComment) {
  2849. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  2850. }
  2851. return fileNode;
  2852. }
  2853. skipBlockComment() {
  2854. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2855. if (this.state.hasFlowComment) {
  2856. this.unexpected(null, FlowErrors.NestedFlowComment);
  2857. }
  2858. this.hasFlowCommentCompletion();
  2859. this.state.pos += this.skipFlowComment();
  2860. this.state.hasFlowComment = true;
  2861. return;
  2862. }
  2863. if (this.state.hasFlowComment) {
  2864. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2865. if (end === -1) {
  2866. throw this.raise(this.state.pos - 2, Errors.UnterminatedComment);
  2867. }
  2868. this.state.pos = end + 3;
  2869. return;
  2870. }
  2871. super.skipBlockComment();
  2872. }
  2873. skipFlowComment() {
  2874. const {
  2875. pos
  2876. } = this.state;
  2877. let shiftToFirstNonWhiteSpace = 2;
  2878. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2879. shiftToFirstNonWhiteSpace++;
  2880. }
  2881. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2882. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2883. if (ch2 === 58 && ch3 === 58) {
  2884. return shiftToFirstNonWhiteSpace + 2;
  2885. }
  2886. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2887. return shiftToFirstNonWhiteSpace + 12;
  2888. }
  2889. if (ch2 === 58 && ch3 !== 58) {
  2890. return shiftToFirstNonWhiteSpace;
  2891. }
  2892. return false;
  2893. }
  2894. hasFlowCommentCompletion() {
  2895. const end = this.input.indexOf("*/", this.state.pos);
  2896. if (end === -1) {
  2897. throw this.raise(this.state.pos, Errors.UnterminatedComment);
  2898. }
  2899. }
  2900. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2901. enumName,
  2902. memberName
  2903. }) {
  2904. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  2905. }
  2906. flowEnumErrorInvalidMemberName(pos, {
  2907. enumName,
  2908. memberName
  2909. }) {
  2910. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  2911. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  2912. }
  2913. flowEnumErrorDuplicateMemberName(pos, {
  2914. enumName,
  2915. memberName
  2916. }) {
  2917. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  2918. }
  2919. flowEnumErrorInconsistentMemberValues(pos, {
  2920. enumName
  2921. }) {
  2922. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  2923. }
  2924. flowEnumErrorInvalidExplicitType(pos, {
  2925. enumName,
  2926. suppliedType
  2927. }) {
  2928. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  2929. }
  2930. flowEnumErrorInvalidMemberInitializer(pos, {
  2931. enumName,
  2932. explicitType,
  2933. memberName
  2934. }) {
  2935. let message = null;
  2936. switch (explicitType) {
  2937. case "boolean":
  2938. case "number":
  2939. case "string":
  2940. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  2941. break;
  2942. case "symbol":
  2943. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  2944. break;
  2945. default:
  2946. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  2947. }
  2948. return this.raise(pos, message, enumName, memberName, explicitType);
  2949. }
  2950. flowEnumErrorNumberMemberNotInitialized(pos, {
  2951. enumName,
  2952. memberName
  2953. }) {
  2954. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  2955. }
  2956. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  2957. enumName
  2958. }) {
  2959. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  2960. }
  2961. flowEnumMemberInit() {
  2962. const startPos = this.state.start;
  2963. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  2964. switch (this.state.type) {
  2965. case types.num:
  2966. {
  2967. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  2968. if (endOfInit()) {
  2969. return {
  2970. type: "number",
  2971. pos: literal.start,
  2972. value: literal
  2973. };
  2974. }
  2975. return {
  2976. type: "invalid",
  2977. pos: startPos
  2978. };
  2979. }
  2980. case types.string:
  2981. {
  2982. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  2983. if (endOfInit()) {
  2984. return {
  2985. type: "string",
  2986. pos: literal.start,
  2987. value: literal
  2988. };
  2989. }
  2990. return {
  2991. type: "invalid",
  2992. pos: startPos
  2993. };
  2994. }
  2995. case types._true:
  2996. case types._false:
  2997. {
  2998. const literal = this.parseBooleanLiteral();
  2999. if (endOfInit()) {
  3000. return {
  3001. type: "boolean",
  3002. pos: literal.start,
  3003. value: literal
  3004. };
  3005. }
  3006. return {
  3007. type: "invalid",
  3008. pos: startPos
  3009. };
  3010. }
  3011. default:
  3012. return {
  3013. type: "invalid",
  3014. pos: startPos
  3015. };
  3016. }
  3017. }
  3018. flowEnumMemberRaw() {
  3019. const pos = this.state.start;
  3020. const id = this.parseIdentifier(true);
  3021. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3022. type: "none",
  3023. pos
  3024. };
  3025. return {
  3026. id,
  3027. init
  3028. };
  3029. }
  3030. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3031. const {
  3032. explicitType
  3033. } = context;
  3034. if (explicitType === null) {
  3035. return;
  3036. }
  3037. if (explicitType !== expectedType) {
  3038. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3039. }
  3040. }
  3041. flowEnumMembers({
  3042. enumName,
  3043. explicitType
  3044. }) {
  3045. const seenNames = new Set();
  3046. const members = {
  3047. booleanMembers: [],
  3048. numberMembers: [],
  3049. stringMembers: [],
  3050. defaultedMembers: []
  3051. };
  3052. while (!this.match(types.braceR)) {
  3053. const memberNode = this.startNode();
  3054. const {
  3055. id,
  3056. init
  3057. } = this.flowEnumMemberRaw();
  3058. const memberName = id.name;
  3059. if (memberName === "") {
  3060. continue;
  3061. }
  3062. if (/^[a-z]/.test(memberName)) {
  3063. this.flowEnumErrorInvalidMemberName(id.start, {
  3064. enumName,
  3065. memberName
  3066. });
  3067. }
  3068. if (seenNames.has(memberName)) {
  3069. this.flowEnumErrorDuplicateMemberName(id.start, {
  3070. enumName,
  3071. memberName
  3072. });
  3073. }
  3074. seenNames.add(memberName);
  3075. const context = {
  3076. enumName,
  3077. explicitType,
  3078. memberName
  3079. };
  3080. memberNode.id = id;
  3081. switch (init.type) {
  3082. case "boolean":
  3083. {
  3084. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3085. memberNode.init = init.value;
  3086. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3087. break;
  3088. }
  3089. case "number":
  3090. {
  3091. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3092. memberNode.init = init.value;
  3093. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3094. break;
  3095. }
  3096. case "string":
  3097. {
  3098. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3099. memberNode.init = init.value;
  3100. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3101. break;
  3102. }
  3103. case "invalid":
  3104. {
  3105. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3106. }
  3107. case "none":
  3108. {
  3109. switch (explicitType) {
  3110. case "boolean":
  3111. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3112. break;
  3113. case "number":
  3114. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3115. break;
  3116. default:
  3117. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3118. }
  3119. }
  3120. }
  3121. if (!this.match(types.braceR)) {
  3122. this.expect(types.comma);
  3123. }
  3124. }
  3125. return members;
  3126. }
  3127. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3128. enumName
  3129. }) {
  3130. if (initializedMembers.length === 0) {
  3131. return defaultedMembers;
  3132. } else if (defaultedMembers.length === 0) {
  3133. return initializedMembers;
  3134. } else if (defaultedMembers.length > initializedMembers.length) {
  3135. for (let _i = 0; _i < initializedMembers.length; _i++) {
  3136. const member = initializedMembers[_i];
  3137. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3138. enumName
  3139. });
  3140. }
  3141. return defaultedMembers;
  3142. } else {
  3143. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  3144. const member = defaultedMembers[_i2];
  3145. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3146. enumName
  3147. });
  3148. }
  3149. return initializedMembers;
  3150. }
  3151. }
  3152. flowEnumParseExplicitType({
  3153. enumName
  3154. }) {
  3155. if (this.eatContextual("of")) {
  3156. if (!this.match(types.name)) {
  3157. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3158. enumName,
  3159. suppliedType: null
  3160. });
  3161. }
  3162. const {
  3163. value
  3164. } = this.state;
  3165. this.next();
  3166. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3167. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3168. enumName,
  3169. suppliedType: value
  3170. });
  3171. }
  3172. return value;
  3173. }
  3174. return null;
  3175. }
  3176. flowEnumBody(node, {
  3177. enumName,
  3178. nameLoc
  3179. }) {
  3180. const explicitType = this.flowEnumParseExplicitType({
  3181. enumName
  3182. });
  3183. this.expect(types.braceL);
  3184. const members = this.flowEnumMembers({
  3185. enumName,
  3186. explicitType
  3187. });
  3188. switch (explicitType) {
  3189. case "boolean":
  3190. node.explicitType = true;
  3191. node.members = members.booleanMembers;
  3192. this.expect(types.braceR);
  3193. return this.finishNode(node, "EnumBooleanBody");
  3194. case "number":
  3195. node.explicitType = true;
  3196. node.members = members.numberMembers;
  3197. this.expect(types.braceR);
  3198. return this.finishNode(node, "EnumNumberBody");
  3199. case "string":
  3200. node.explicitType = true;
  3201. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3202. enumName
  3203. });
  3204. this.expect(types.braceR);
  3205. return this.finishNode(node, "EnumStringBody");
  3206. case "symbol":
  3207. node.members = members.defaultedMembers;
  3208. this.expect(types.braceR);
  3209. return this.finishNode(node, "EnumSymbolBody");
  3210. default:
  3211. {
  3212. const empty = () => {
  3213. node.members = [];
  3214. this.expect(types.braceR);
  3215. return this.finishNode(node, "EnumStringBody");
  3216. };
  3217. node.explicitType = false;
  3218. const boolsLen = members.booleanMembers.length;
  3219. const numsLen = members.numberMembers.length;
  3220. const strsLen = members.stringMembers.length;
  3221. const defaultedLen = members.defaultedMembers.length;
  3222. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3223. return empty();
  3224. } else if (!boolsLen && !numsLen) {
  3225. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3226. enumName
  3227. });
  3228. this.expect(types.braceR);
  3229. return this.finishNode(node, "EnumStringBody");
  3230. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3231. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  3232. const member = _members$defaultedMem[_i3];
  3233. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3234. enumName,
  3235. memberName: member.id.name
  3236. });
  3237. }
  3238. node.members = members.booleanMembers;
  3239. this.expect(types.braceR);
  3240. return this.finishNode(node, "EnumBooleanBody");
  3241. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3242. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  3243. const member = _members$defaultedMem2[_i4];
  3244. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3245. enumName,
  3246. memberName: member.id.name
  3247. });
  3248. }
  3249. node.members = members.numberMembers;
  3250. this.expect(types.braceR);
  3251. return this.finishNode(node, "EnumNumberBody");
  3252. } else {
  3253. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3254. enumName
  3255. });
  3256. return empty();
  3257. }
  3258. }
  3259. }
  3260. }
  3261. flowParseEnumDeclaration(node) {
  3262. const id = this.parseIdentifier();
  3263. node.id = id;
  3264. node.body = this.flowEnumBody(this.startNode(), {
  3265. enumName: id.name,
  3266. nameLoc: id.start
  3267. });
  3268. return this.finishNode(node, "EnumDeclaration");
  3269. }
  3270. });
  3271. const entities = {
  3272. quot: "\u0022",
  3273. amp: "&",
  3274. apos: "\u0027",
  3275. lt: "<",
  3276. gt: ">",
  3277. nbsp: "\u00A0",
  3278. iexcl: "\u00A1",
  3279. cent: "\u00A2",
  3280. pound: "\u00A3",
  3281. curren: "\u00A4",
  3282. yen: "\u00A5",
  3283. brvbar: "\u00A6",
  3284. sect: "\u00A7",
  3285. uml: "\u00A8",
  3286. copy: "\u00A9",
  3287. ordf: "\u00AA",
  3288. laquo: "\u00AB",
  3289. not: "\u00AC",
  3290. shy: "\u00AD",
  3291. reg: "\u00AE",
  3292. macr: "\u00AF",
  3293. deg: "\u00B0",
  3294. plusmn: "\u00B1",
  3295. sup2: "\u00B2",
  3296. sup3: "\u00B3",
  3297. acute: "\u00B4",
  3298. micro: "\u00B5",
  3299. para: "\u00B6",
  3300. middot: "\u00B7",
  3301. cedil: "\u00B8",
  3302. sup1: "\u00B9",
  3303. ordm: "\u00BA",
  3304. raquo: "\u00BB",
  3305. frac14: "\u00BC",
  3306. frac12: "\u00BD",
  3307. frac34: "\u00BE",
  3308. iquest: "\u00BF",
  3309. Agrave: "\u00C0",
  3310. Aacute: "\u00C1",
  3311. Acirc: "\u00C2",
  3312. Atilde: "\u00C3",
  3313. Auml: "\u00C4",
  3314. Aring: "\u00C5",
  3315. AElig: "\u00C6",
  3316. Ccedil: "\u00C7",
  3317. Egrave: "\u00C8",
  3318. Eacute: "\u00C9",
  3319. Ecirc: "\u00CA",
  3320. Euml: "\u00CB",
  3321. Igrave: "\u00CC",
  3322. Iacute: "\u00CD",
  3323. Icirc: "\u00CE",
  3324. Iuml: "\u00CF",
  3325. ETH: "\u00D0",
  3326. Ntilde: "\u00D1",
  3327. Ograve: "\u00D2",
  3328. Oacute: "\u00D3",
  3329. Ocirc: "\u00D4",
  3330. Otilde: "\u00D5",
  3331. Ouml: "\u00D6",
  3332. times: "\u00D7",
  3333. Oslash: "\u00D8",
  3334. Ugrave: "\u00D9",
  3335. Uacute: "\u00DA",
  3336. Ucirc: "\u00DB",
  3337. Uuml: "\u00DC",
  3338. Yacute: "\u00DD",
  3339. THORN: "\u00DE",
  3340. szlig: "\u00DF",
  3341. agrave: "\u00E0",
  3342. aacute: "\u00E1",
  3343. acirc: "\u00E2",
  3344. atilde: "\u00E3",
  3345. auml: "\u00E4",
  3346. aring: "\u00E5",
  3347. aelig: "\u00E6",
  3348. ccedil: "\u00E7",
  3349. egrave: "\u00E8",
  3350. eacute: "\u00E9",
  3351. ecirc: "\u00EA",
  3352. euml: "\u00EB",
  3353. igrave: "\u00EC",
  3354. iacute: "\u00ED",
  3355. icirc: "\u00EE",
  3356. iuml: "\u00EF",
  3357. eth: "\u00F0",
  3358. ntilde: "\u00F1",
  3359. ograve: "\u00F2",
  3360. oacute: "\u00F3",
  3361. ocirc: "\u00F4",
  3362. otilde: "\u00F5",
  3363. ouml: "\u00F6",
  3364. divide: "\u00F7",
  3365. oslash: "\u00F8",
  3366. ugrave: "\u00F9",
  3367. uacute: "\u00FA",
  3368. ucirc: "\u00FB",
  3369. uuml: "\u00FC",
  3370. yacute: "\u00FD",
  3371. thorn: "\u00FE",
  3372. yuml: "\u00FF",
  3373. OElig: "\u0152",
  3374. oelig: "\u0153",
  3375. Scaron: "\u0160",
  3376. scaron: "\u0161",
  3377. Yuml: "\u0178",
  3378. fnof: "\u0192",
  3379. circ: "\u02C6",
  3380. tilde: "\u02DC",
  3381. Alpha: "\u0391",
  3382. Beta: "\u0392",
  3383. Gamma: "\u0393",
  3384. Delta: "\u0394",
  3385. Epsilon: "\u0395",
  3386. Zeta: "\u0396",
  3387. Eta: "\u0397",
  3388. Theta: "\u0398",
  3389. Iota: "\u0399",
  3390. Kappa: "\u039A",
  3391. Lambda: "\u039B",
  3392. Mu: "\u039C",
  3393. Nu: "\u039D",
  3394. Xi: "\u039E",
  3395. Omicron: "\u039F",
  3396. Pi: "\u03A0",
  3397. Rho: "\u03A1",
  3398. Sigma: "\u03A3",
  3399. Tau: "\u03A4",
  3400. Upsilon: "\u03A5",
  3401. Phi: "\u03A6",
  3402. Chi: "\u03A7",
  3403. Psi: "\u03A8",
  3404. Omega: "\u03A9",
  3405. alpha: "\u03B1",
  3406. beta: "\u03B2",
  3407. gamma: "\u03B3",
  3408. delta: "\u03B4",
  3409. epsilon: "\u03B5",
  3410. zeta: "\u03B6",
  3411. eta: "\u03B7",
  3412. theta: "\u03B8",
  3413. iota: "\u03B9",
  3414. kappa: "\u03BA",
  3415. lambda: "\u03BB",
  3416. mu: "\u03BC",
  3417. nu: "\u03BD",
  3418. xi: "\u03BE",
  3419. omicron: "\u03BF",
  3420. pi: "\u03C0",
  3421. rho: "\u03C1",
  3422. sigmaf: "\u03C2",
  3423. sigma: "\u03C3",
  3424. tau: "\u03C4",
  3425. upsilon: "\u03C5",
  3426. phi: "\u03C6",
  3427. chi: "\u03C7",
  3428. psi: "\u03C8",
  3429. omega: "\u03C9",
  3430. thetasym: "\u03D1",
  3431. upsih: "\u03D2",
  3432. piv: "\u03D6",
  3433. ensp: "\u2002",
  3434. emsp: "\u2003",
  3435. thinsp: "\u2009",
  3436. zwnj: "\u200C",
  3437. zwj: "\u200D",
  3438. lrm: "\u200E",
  3439. rlm: "\u200F",
  3440. ndash: "\u2013",
  3441. mdash: "\u2014",
  3442. lsquo: "\u2018",
  3443. rsquo: "\u2019",
  3444. sbquo: "\u201A",
  3445. ldquo: "\u201C",
  3446. rdquo: "\u201D",
  3447. bdquo: "\u201E",
  3448. dagger: "\u2020",
  3449. Dagger: "\u2021",
  3450. bull: "\u2022",
  3451. hellip: "\u2026",
  3452. permil: "\u2030",
  3453. prime: "\u2032",
  3454. Prime: "\u2033",
  3455. lsaquo: "\u2039",
  3456. rsaquo: "\u203A",
  3457. oline: "\u203E",
  3458. frasl: "\u2044",
  3459. euro: "\u20AC",
  3460. image: "\u2111",
  3461. weierp: "\u2118",
  3462. real: "\u211C",
  3463. trade: "\u2122",
  3464. alefsym: "\u2135",
  3465. larr: "\u2190",
  3466. uarr: "\u2191",
  3467. rarr: "\u2192",
  3468. darr: "\u2193",
  3469. harr: "\u2194",
  3470. crarr: "\u21B5",
  3471. lArr: "\u21D0",
  3472. uArr: "\u21D1",
  3473. rArr: "\u21D2",
  3474. dArr: "\u21D3",
  3475. hArr: "\u21D4",
  3476. forall: "\u2200",
  3477. part: "\u2202",
  3478. exist: "\u2203",
  3479. empty: "\u2205",
  3480. nabla: "\u2207",
  3481. isin: "\u2208",
  3482. notin: "\u2209",
  3483. ni: "\u220B",
  3484. prod: "\u220F",
  3485. sum: "\u2211",
  3486. minus: "\u2212",
  3487. lowast: "\u2217",
  3488. radic: "\u221A",
  3489. prop: "\u221D",
  3490. infin: "\u221E",
  3491. ang: "\u2220",
  3492. and: "\u2227",
  3493. or: "\u2228",
  3494. cap: "\u2229",
  3495. cup: "\u222A",
  3496. int: "\u222B",
  3497. there4: "\u2234",
  3498. sim: "\u223C",
  3499. cong: "\u2245",
  3500. asymp: "\u2248",
  3501. ne: "\u2260",
  3502. equiv: "\u2261",
  3503. le: "\u2264",
  3504. ge: "\u2265",
  3505. sub: "\u2282",
  3506. sup: "\u2283",
  3507. nsub: "\u2284",
  3508. sube: "\u2286",
  3509. supe: "\u2287",
  3510. oplus: "\u2295",
  3511. otimes: "\u2297",
  3512. perp: "\u22A5",
  3513. sdot: "\u22C5",
  3514. lceil: "\u2308",
  3515. rceil: "\u2309",
  3516. lfloor: "\u230A",
  3517. rfloor: "\u230B",
  3518. lang: "\u2329",
  3519. rang: "\u232A",
  3520. loz: "\u25CA",
  3521. spades: "\u2660",
  3522. clubs: "\u2663",
  3523. hearts: "\u2665",
  3524. diams: "\u2666"
  3525. };
  3526. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3527. const DECIMAL_NUMBER = /^\d+$/;
  3528. const JsxErrors = Object.freeze({
  3529. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3530. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3531. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3532. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3533. UnterminatedJsxContent: "Unterminated JSX contents",
  3534. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3535. });
  3536. types$1.j_oTag = new TokContext("<tag", false);
  3537. types$1.j_cTag = new TokContext("</tag", false);
  3538. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3539. types.jsxName = new TokenType("jsxName");
  3540. types.jsxText = new TokenType("jsxText", {
  3541. beforeExpr: true
  3542. });
  3543. types.jsxTagStart = new TokenType("jsxTagStart", {
  3544. startsExpr: true
  3545. });
  3546. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3547. types.jsxTagStart.updateContext = function () {
  3548. this.state.context.push(types$1.j_expr);
  3549. this.state.context.push(types$1.j_oTag);
  3550. this.state.exprAllowed = false;
  3551. };
  3552. types.jsxTagEnd.updateContext = function (prevType) {
  3553. const out = this.state.context.pop();
  3554. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3555. this.state.context.pop();
  3556. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3557. } else {
  3558. this.state.exprAllowed = true;
  3559. }
  3560. };
  3561. function isFragment(object) {
  3562. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3563. }
  3564. function getQualifiedJSXName(object) {
  3565. if (object.type === "JSXIdentifier") {
  3566. return object.name;
  3567. }
  3568. if (object.type === "JSXNamespacedName") {
  3569. return object.namespace.name + ":" + object.name.name;
  3570. }
  3571. if (object.type === "JSXMemberExpression") {
  3572. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3573. }
  3574. throw new Error("Node had unexpected type: " + object.type);
  3575. }
  3576. var jsx = (superClass => class extends superClass {
  3577. jsxReadToken() {
  3578. let out = "";
  3579. let chunkStart = this.state.pos;
  3580. for (;;) {
  3581. if (this.state.pos >= this.length) {
  3582. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  3583. }
  3584. const ch = this.input.charCodeAt(this.state.pos);
  3585. switch (ch) {
  3586. case 60:
  3587. case 123:
  3588. if (this.state.pos === this.state.start) {
  3589. if (ch === 60 && this.state.exprAllowed) {
  3590. ++this.state.pos;
  3591. return this.finishToken(types.jsxTagStart);
  3592. }
  3593. return super.getTokenFromCode(ch);
  3594. }
  3595. out += this.input.slice(chunkStart, this.state.pos);
  3596. return this.finishToken(types.jsxText, out);
  3597. case 38:
  3598. out += this.input.slice(chunkStart, this.state.pos);
  3599. out += this.jsxReadEntity();
  3600. chunkStart = this.state.pos;
  3601. break;
  3602. default:
  3603. if (isNewLine(ch)) {
  3604. out += this.input.slice(chunkStart, this.state.pos);
  3605. out += this.jsxReadNewLine(true);
  3606. chunkStart = this.state.pos;
  3607. } else {
  3608. ++this.state.pos;
  3609. }
  3610. }
  3611. }
  3612. }
  3613. jsxReadNewLine(normalizeCRLF) {
  3614. const ch = this.input.charCodeAt(this.state.pos);
  3615. let out;
  3616. ++this.state.pos;
  3617. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3618. ++this.state.pos;
  3619. out = normalizeCRLF ? "\n" : "\r\n";
  3620. } else {
  3621. out = String.fromCharCode(ch);
  3622. }
  3623. ++this.state.curLine;
  3624. this.state.lineStart = this.state.pos;
  3625. return out;
  3626. }
  3627. jsxReadString(quote) {
  3628. let out = "";
  3629. let chunkStart = ++this.state.pos;
  3630. for (;;) {
  3631. if (this.state.pos >= this.length) {
  3632. throw this.raise(this.state.start, Errors.UnterminatedString);
  3633. }
  3634. const ch = this.input.charCodeAt(this.state.pos);
  3635. if (ch === quote) break;
  3636. if (ch === 38) {
  3637. out += this.input.slice(chunkStart, this.state.pos);
  3638. out += this.jsxReadEntity();
  3639. chunkStart = this.state.pos;
  3640. } else if (isNewLine(ch)) {
  3641. out += this.input.slice(chunkStart, this.state.pos);
  3642. out += this.jsxReadNewLine(false);
  3643. chunkStart = this.state.pos;
  3644. } else {
  3645. ++this.state.pos;
  3646. }
  3647. }
  3648. out += this.input.slice(chunkStart, this.state.pos++);
  3649. return this.finishToken(types.string, out);
  3650. }
  3651. jsxReadEntity() {
  3652. let str = "";
  3653. let count = 0;
  3654. let entity;
  3655. let ch = this.input[this.state.pos];
  3656. const startPos = ++this.state.pos;
  3657. while (this.state.pos < this.length && count++ < 10) {
  3658. ch = this.input[this.state.pos++];
  3659. if (ch === ";") {
  3660. if (str[0] === "#") {
  3661. if (str[1] === "x") {
  3662. str = str.substr(2);
  3663. if (HEX_NUMBER.test(str)) {
  3664. entity = String.fromCodePoint(parseInt(str, 16));
  3665. }
  3666. } else {
  3667. str = str.substr(1);
  3668. if (DECIMAL_NUMBER.test(str)) {
  3669. entity = String.fromCodePoint(parseInt(str, 10));
  3670. }
  3671. }
  3672. } else {
  3673. entity = entities[str];
  3674. }
  3675. break;
  3676. }
  3677. str += ch;
  3678. }
  3679. if (!entity) {
  3680. this.state.pos = startPos;
  3681. return "&";
  3682. }
  3683. return entity;
  3684. }
  3685. jsxReadWord() {
  3686. let ch;
  3687. const start = this.state.pos;
  3688. do {
  3689. ch = this.input.charCodeAt(++this.state.pos);
  3690. } while (isIdentifierChar(ch) || ch === 45);
  3691. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3692. }
  3693. jsxParseIdentifier() {
  3694. const node = this.startNode();
  3695. if (this.match(types.jsxName)) {
  3696. node.name = this.state.value;
  3697. } else if (this.state.type.keyword) {
  3698. node.name = this.state.type.keyword;
  3699. } else {
  3700. this.unexpected();
  3701. }
  3702. this.next();
  3703. return this.finishNode(node, "JSXIdentifier");
  3704. }
  3705. jsxParseNamespacedName() {
  3706. const startPos = this.state.start;
  3707. const startLoc = this.state.startLoc;
  3708. const name = this.jsxParseIdentifier();
  3709. if (!this.eat(types.colon)) return name;
  3710. const node = this.startNodeAt(startPos, startLoc);
  3711. node.namespace = name;
  3712. node.name = this.jsxParseIdentifier();
  3713. return this.finishNode(node, "JSXNamespacedName");
  3714. }
  3715. jsxParseElementName() {
  3716. const startPos = this.state.start;
  3717. const startLoc = this.state.startLoc;
  3718. let node = this.jsxParseNamespacedName();
  3719. if (node.type === "JSXNamespacedName") {
  3720. return node;
  3721. }
  3722. while (this.eat(types.dot)) {
  3723. const newNode = this.startNodeAt(startPos, startLoc);
  3724. newNode.object = node;
  3725. newNode.property = this.jsxParseIdentifier();
  3726. node = this.finishNode(newNode, "JSXMemberExpression");
  3727. }
  3728. return node;
  3729. }
  3730. jsxParseAttributeValue() {
  3731. let node;
  3732. switch (this.state.type) {
  3733. case types.braceL:
  3734. node = this.startNode();
  3735. this.next();
  3736. node = this.jsxParseExpressionContainer(node);
  3737. if (node.expression.type === "JSXEmptyExpression") {
  3738. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  3739. }
  3740. return node;
  3741. case types.jsxTagStart:
  3742. case types.string:
  3743. return this.parseExprAtom();
  3744. default:
  3745. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  3746. }
  3747. }
  3748. jsxParseEmptyExpression() {
  3749. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3750. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3751. }
  3752. jsxParseSpreadChild(node) {
  3753. this.next();
  3754. node.expression = this.parseExpression();
  3755. this.expect(types.braceR);
  3756. return this.finishNode(node, "JSXSpreadChild");
  3757. }
  3758. jsxParseExpressionContainer(node) {
  3759. if (this.match(types.braceR)) {
  3760. node.expression = this.jsxParseEmptyExpression();
  3761. } else {
  3762. node.expression = this.parseExpression();
  3763. }
  3764. this.expect(types.braceR);
  3765. return this.finishNode(node, "JSXExpressionContainer");
  3766. }
  3767. jsxParseAttribute() {
  3768. const node = this.startNode();
  3769. if (this.eat(types.braceL)) {
  3770. this.expect(types.ellipsis);
  3771. node.argument = this.parseMaybeAssign();
  3772. this.expect(types.braceR);
  3773. return this.finishNode(node, "JSXSpreadAttribute");
  3774. }
  3775. node.name = this.jsxParseNamespacedName();
  3776. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3777. return this.finishNode(node, "JSXAttribute");
  3778. }
  3779. jsxParseOpeningElementAt(startPos, startLoc) {
  3780. const node = this.startNodeAt(startPos, startLoc);
  3781. if (this.match(types.jsxTagEnd)) {
  3782. this.expect(types.jsxTagEnd);
  3783. return this.finishNode(node, "JSXOpeningFragment");
  3784. }
  3785. node.name = this.jsxParseElementName();
  3786. return this.jsxParseOpeningElementAfterName(node);
  3787. }
  3788. jsxParseOpeningElementAfterName(node) {
  3789. const attributes = [];
  3790. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3791. attributes.push(this.jsxParseAttribute());
  3792. }
  3793. node.attributes = attributes;
  3794. node.selfClosing = this.eat(types.slash);
  3795. this.expect(types.jsxTagEnd);
  3796. return this.finishNode(node, "JSXOpeningElement");
  3797. }
  3798. jsxParseClosingElementAt(startPos, startLoc) {
  3799. const node = this.startNodeAt(startPos, startLoc);
  3800. if (this.match(types.jsxTagEnd)) {
  3801. this.expect(types.jsxTagEnd);
  3802. return this.finishNode(node, "JSXClosingFragment");
  3803. }
  3804. node.name = this.jsxParseElementName();
  3805. this.expect(types.jsxTagEnd);
  3806. return this.finishNode(node, "JSXClosingElement");
  3807. }
  3808. jsxParseElementAt(startPos, startLoc) {
  3809. const node = this.startNodeAt(startPos, startLoc);
  3810. const children = [];
  3811. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3812. let closingElement = null;
  3813. if (!openingElement.selfClosing) {
  3814. contents: for (;;) {
  3815. switch (this.state.type) {
  3816. case types.jsxTagStart:
  3817. startPos = this.state.start;
  3818. startLoc = this.state.startLoc;
  3819. this.next();
  3820. if (this.eat(types.slash)) {
  3821. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3822. break contents;
  3823. }
  3824. children.push(this.jsxParseElementAt(startPos, startLoc));
  3825. break;
  3826. case types.jsxText:
  3827. children.push(this.parseExprAtom());
  3828. break;
  3829. case types.braceL:
  3830. {
  3831. const node = this.startNode();
  3832. this.next();
  3833. if (this.match(types.ellipsis)) {
  3834. children.push(this.jsxParseSpreadChild(node));
  3835. } else {
  3836. children.push(this.jsxParseExpressionContainer(node));
  3837. }
  3838. break;
  3839. }
  3840. default:
  3841. throw this.unexpected();
  3842. }
  3843. }
  3844. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3845. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  3846. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3847. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3848. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3849. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3850. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3851. }
  3852. }
  3853. }
  3854. if (isFragment(openingElement)) {
  3855. node.openingFragment = openingElement;
  3856. node.closingFragment = closingElement;
  3857. } else {
  3858. node.openingElement = openingElement;
  3859. node.closingElement = closingElement;
  3860. }
  3861. node.children = children;
  3862. if (this.isRelational("<")) {
  3863. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  3864. }
  3865. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3866. }
  3867. jsxParseElement() {
  3868. const startPos = this.state.start;
  3869. const startLoc = this.state.startLoc;
  3870. this.next();
  3871. return this.jsxParseElementAt(startPos, startLoc);
  3872. }
  3873. parseExprAtom(refExpressionErrors) {
  3874. if (this.match(types.jsxText)) {
  3875. return this.parseLiteral(this.state.value, "JSXText");
  3876. } else if (this.match(types.jsxTagStart)) {
  3877. return this.jsxParseElement();
  3878. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3879. this.finishToken(types.jsxTagStart);
  3880. return this.jsxParseElement();
  3881. } else {
  3882. return super.parseExprAtom(refExpressionErrors);
  3883. }
  3884. }
  3885. getTokenFromCode(code) {
  3886. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  3887. const context = this.curContext();
  3888. if (context === types$1.j_expr) {
  3889. return this.jsxReadToken();
  3890. }
  3891. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  3892. if (isIdentifierStart(code)) {
  3893. return this.jsxReadWord();
  3894. }
  3895. if (code === 62) {
  3896. ++this.state.pos;
  3897. return this.finishToken(types.jsxTagEnd);
  3898. }
  3899. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  3900. return this.jsxReadString(code);
  3901. }
  3902. }
  3903. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  3904. ++this.state.pos;
  3905. return this.finishToken(types.jsxTagStart);
  3906. }
  3907. return super.getTokenFromCode(code);
  3908. }
  3909. updateContext(prevType) {
  3910. if (this.match(types.braceL)) {
  3911. const curContext = this.curContext();
  3912. if (curContext === types$1.j_oTag) {
  3913. this.state.context.push(types$1.braceExpression);
  3914. } else if (curContext === types$1.j_expr) {
  3915. this.state.context.push(types$1.templateQuasi);
  3916. } else {
  3917. super.updateContext(prevType);
  3918. }
  3919. this.state.exprAllowed = true;
  3920. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  3921. this.state.context.length -= 2;
  3922. this.state.context.push(types$1.j_cTag);
  3923. this.state.exprAllowed = false;
  3924. } else {
  3925. return super.updateContext(prevType);
  3926. }
  3927. }
  3928. });
  3929. class Scope {
  3930. constructor(flags) {
  3931. this.var = [];
  3932. this.lexical = [];
  3933. this.functions = [];
  3934. this.flags = flags;
  3935. }
  3936. }
  3937. class ScopeHandler {
  3938. constructor(raise, inModule) {
  3939. this.scopeStack = [];
  3940. this.undefinedExports = new Map();
  3941. this.undefinedPrivateNames = new Map();
  3942. this.raise = raise;
  3943. this.inModule = inModule;
  3944. }
  3945. get inFunction() {
  3946. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  3947. }
  3948. get allowSuper() {
  3949. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  3950. }
  3951. get allowDirectSuper() {
  3952. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  3953. }
  3954. get inClass() {
  3955. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  3956. }
  3957. get inNonArrowFunction() {
  3958. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  3959. }
  3960. get treatFunctionsAsVar() {
  3961. return this.treatFunctionsAsVarInScope(this.currentScope());
  3962. }
  3963. createScope(flags) {
  3964. return new Scope(flags);
  3965. }
  3966. enter(flags) {
  3967. this.scopeStack.push(this.createScope(flags));
  3968. }
  3969. exit() {
  3970. this.scopeStack.pop();
  3971. }
  3972. treatFunctionsAsVarInScope(scope) {
  3973. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  3974. }
  3975. declareName(name, bindingType, pos) {
  3976. let scope = this.currentScope();
  3977. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  3978. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3979. if (bindingType & BIND_SCOPE_FUNCTION) {
  3980. scope.functions.push(name);
  3981. } else {
  3982. scope.lexical.push(name);
  3983. }
  3984. if (bindingType & BIND_SCOPE_LEXICAL) {
  3985. this.maybeExportDefined(scope, name);
  3986. }
  3987. } else if (bindingType & BIND_SCOPE_VAR) {
  3988. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  3989. scope = this.scopeStack[i];
  3990. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3991. scope.var.push(name);
  3992. this.maybeExportDefined(scope, name);
  3993. if (scope.flags & SCOPE_VAR) break;
  3994. }
  3995. }
  3996. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  3997. this.undefinedExports.delete(name);
  3998. }
  3999. }
  4000. maybeExportDefined(scope, name) {
  4001. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4002. this.undefinedExports.delete(name);
  4003. }
  4004. }
  4005. checkRedeclarationInScope(scope, name, bindingType, pos) {
  4006. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  4007. this.raise(pos, Errors.VarRedeclaration, name);
  4008. }
  4009. }
  4010. isRedeclaredInScope(scope, name, bindingType) {
  4011. if (!(bindingType & BIND_KIND_VALUE)) return false;
  4012. if (bindingType & BIND_SCOPE_LEXICAL) {
  4013. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  4014. }
  4015. if (bindingType & BIND_SCOPE_FUNCTION) {
  4016. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  4017. }
  4018. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  4019. }
  4020. checkLocalExport(id) {
  4021. 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) {
  4022. this.undefinedExports.set(id.name, id.start);
  4023. }
  4024. }
  4025. currentScope() {
  4026. return this.scopeStack[this.scopeStack.length - 1];
  4027. }
  4028. currentVarScope() {
  4029. for (let i = this.scopeStack.length - 1;; i--) {
  4030. const scope = this.scopeStack[i];
  4031. if (scope.flags & SCOPE_VAR) {
  4032. return scope;
  4033. }
  4034. }
  4035. }
  4036. currentThisScope() {
  4037. for (let i = this.scopeStack.length - 1;; i--) {
  4038. const scope = this.scopeStack[i];
  4039. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  4040. return scope;
  4041. }
  4042. }
  4043. }
  4044. }
  4045. class TypeScriptScope extends Scope {
  4046. constructor(...args) {
  4047. super(...args);
  4048. this.types = [];
  4049. this.enums = [];
  4050. this.constEnums = [];
  4051. this.classes = [];
  4052. this.exportOnlyBindings = [];
  4053. }
  4054. }
  4055. class TypeScriptScopeHandler extends ScopeHandler {
  4056. createScope(flags) {
  4057. return new TypeScriptScope(flags);
  4058. }
  4059. declareName(name, bindingType, pos) {
  4060. const scope = this.currentScope();
  4061. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4062. this.maybeExportDefined(scope, name);
  4063. scope.exportOnlyBindings.push(name);
  4064. return;
  4065. }
  4066. super.declareName(...arguments);
  4067. if (bindingType & BIND_KIND_TYPE) {
  4068. if (!(bindingType & BIND_KIND_VALUE)) {
  4069. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4070. this.maybeExportDefined(scope, name);
  4071. }
  4072. scope.types.push(name);
  4073. }
  4074. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4075. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4076. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4077. }
  4078. isRedeclaredInScope(scope, name, bindingType) {
  4079. if (scope.enums.indexOf(name) > -1) {
  4080. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4081. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4082. const wasConst = scope.constEnums.indexOf(name) > -1;
  4083. return isConst !== wasConst;
  4084. }
  4085. return true;
  4086. }
  4087. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4088. if (scope.lexical.indexOf(name) > -1) {
  4089. return !!(bindingType & BIND_KIND_VALUE);
  4090. } else {
  4091. return false;
  4092. }
  4093. }
  4094. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4095. return true;
  4096. }
  4097. return super.isRedeclaredInScope(...arguments);
  4098. }
  4099. checkLocalExport(id) {
  4100. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4101. super.checkLocalExport(id);
  4102. }
  4103. }
  4104. }
  4105. const PARAM = 0b000,
  4106. PARAM_YIELD = 0b001,
  4107. PARAM_AWAIT = 0b010,
  4108. PARAM_RETURN = 0b100;
  4109. class ProductionParameterHandler {
  4110. constructor() {
  4111. this.stacks = [];
  4112. }
  4113. enter(flags) {
  4114. this.stacks.push(flags);
  4115. }
  4116. exit() {
  4117. this.stacks.pop();
  4118. }
  4119. currentFlags() {
  4120. return this.stacks[this.stacks.length - 1];
  4121. }
  4122. get hasAwait() {
  4123. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4124. }
  4125. get hasYield() {
  4126. return (this.currentFlags() & PARAM_YIELD) > 0;
  4127. }
  4128. get hasReturn() {
  4129. return (this.currentFlags() & PARAM_RETURN) > 0;
  4130. }
  4131. }
  4132. function functionFlags(isAsync, isGenerator) {
  4133. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4134. }
  4135. function nonNull(x) {
  4136. if (x == null) {
  4137. throw new Error(`Unexpected ${x} value.`);
  4138. }
  4139. return x;
  4140. }
  4141. function assert(x) {
  4142. if (!x) {
  4143. throw new Error("Assert fail");
  4144. }
  4145. }
  4146. const TSErrors = Object.freeze({
  4147. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4148. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4149. DeclareClassFieldHasInitializer: "'declare' class fields cannot have an initializer",
  4150. DuplicateModifier: "Duplicate modifier: '%0'",
  4151. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4152. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4153. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4154. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4155. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4156. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4157. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4158. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4159. TemplateTypeHasSubstitution: "Template literal types cannot have any substitution",
  4160. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4161. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4162. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4163. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4164. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4165. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4166. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4167. });
  4168. function keywordTypeFromName(value) {
  4169. switch (value) {
  4170. case "any":
  4171. return "TSAnyKeyword";
  4172. case "boolean":
  4173. return "TSBooleanKeyword";
  4174. case "bigint":
  4175. return "TSBigIntKeyword";
  4176. case "never":
  4177. return "TSNeverKeyword";
  4178. case "number":
  4179. return "TSNumberKeyword";
  4180. case "object":
  4181. return "TSObjectKeyword";
  4182. case "string":
  4183. return "TSStringKeyword";
  4184. case "symbol":
  4185. return "TSSymbolKeyword";
  4186. case "undefined":
  4187. return "TSUndefinedKeyword";
  4188. case "unknown":
  4189. return "TSUnknownKeyword";
  4190. default:
  4191. return undefined;
  4192. }
  4193. }
  4194. var typescript = (superClass => class extends superClass {
  4195. getScopeHandler() {
  4196. return TypeScriptScopeHandler;
  4197. }
  4198. tsIsIdentifier() {
  4199. return this.match(types.name);
  4200. }
  4201. tsNextTokenCanFollowModifier() {
  4202. this.next();
  4203. 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);
  4204. }
  4205. tsParseModifier(allowedModifiers) {
  4206. if (!this.match(types.name)) {
  4207. return undefined;
  4208. }
  4209. const modifier = this.state.value;
  4210. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4211. return modifier;
  4212. }
  4213. return undefined;
  4214. }
  4215. tsParseModifiers(modified, allowedModifiers) {
  4216. for (;;) {
  4217. const startPos = this.state.start;
  4218. const modifier = this.tsParseModifier(allowedModifiers);
  4219. if (!modifier) break;
  4220. if (Object.hasOwnProperty.call(modified, modifier)) {
  4221. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4222. }
  4223. modified[modifier] = true;
  4224. }
  4225. }
  4226. tsIsListTerminator(kind) {
  4227. switch (kind) {
  4228. case "EnumMembers":
  4229. case "TypeMembers":
  4230. return this.match(types.braceR);
  4231. case "HeritageClauseElement":
  4232. return this.match(types.braceL);
  4233. case "TupleElementTypes":
  4234. return this.match(types.bracketR);
  4235. case "TypeParametersOrArguments":
  4236. return this.isRelational(">");
  4237. }
  4238. throw new Error("Unreachable");
  4239. }
  4240. tsParseList(kind, parseElement) {
  4241. const result = [];
  4242. while (!this.tsIsListTerminator(kind)) {
  4243. result.push(parseElement());
  4244. }
  4245. return result;
  4246. }
  4247. tsParseDelimitedList(kind, parseElement) {
  4248. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4249. }
  4250. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4251. const result = [];
  4252. for (;;) {
  4253. if (this.tsIsListTerminator(kind)) {
  4254. break;
  4255. }
  4256. const element = parseElement();
  4257. if (element == null) {
  4258. return undefined;
  4259. }
  4260. result.push(element);
  4261. if (this.eat(types.comma)) {
  4262. continue;
  4263. }
  4264. if (this.tsIsListTerminator(kind)) {
  4265. break;
  4266. }
  4267. if (expectSuccess) {
  4268. this.expect(types.comma);
  4269. }
  4270. return undefined;
  4271. }
  4272. return result;
  4273. }
  4274. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4275. if (!skipFirstToken) {
  4276. if (bracket) {
  4277. this.expect(types.bracketL);
  4278. } else {
  4279. this.expectRelational("<");
  4280. }
  4281. }
  4282. const result = this.tsParseDelimitedList(kind, parseElement);
  4283. if (bracket) {
  4284. this.expect(types.bracketR);
  4285. } else {
  4286. this.expectRelational(">");
  4287. }
  4288. return result;
  4289. }
  4290. tsParseImportType() {
  4291. const node = this.startNode();
  4292. this.expect(types._import);
  4293. this.expect(types.parenL);
  4294. if (!this.match(types.string)) {
  4295. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4296. }
  4297. node.argument = this.parseExprAtom();
  4298. this.expect(types.parenR);
  4299. if (this.eat(types.dot)) {
  4300. node.qualifier = this.tsParseEntityName(true);
  4301. }
  4302. if (this.isRelational("<")) {
  4303. node.typeParameters = this.tsParseTypeArguments();
  4304. }
  4305. return this.finishNode(node, "TSImportType");
  4306. }
  4307. tsParseEntityName(allowReservedWords) {
  4308. let entity = this.parseIdentifier();
  4309. while (this.eat(types.dot)) {
  4310. const node = this.startNodeAtNode(entity);
  4311. node.left = entity;
  4312. node.right = this.parseIdentifier(allowReservedWords);
  4313. entity = this.finishNode(node, "TSQualifiedName");
  4314. }
  4315. return entity;
  4316. }
  4317. tsParseTypeReference() {
  4318. const node = this.startNode();
  4319. node.typeName = this.tsParseEntityName(false);
  4320. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4321. node.typeParameters = this.tsParseTypeArguments();
  4322. }
  4323. return this.finishNode(node, "TSTypeReference");
  4324. }
  4325. tsParseThisTypePredicate(lhs) {
  4326. this.next();
  4327. const node = this.startNodeAtNode(lhs);
  4328. node.parameterName = lhs;
  4329. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4330. return this.finishNode(node, "TSTypePredicate");
  4331. }
  4332. tsParseThisTypeNode() {
  4333. const node = this.startNode();
  4334. this.next();
  4335. return this.finishNode(node, "TSThisType");
  4336. }
  4337. tsParseTypeQuery() {
  4338. const node = this.startNode();
  4339. this.expect(types._typeof);
  4340. if (this.match(types._import)) {
  4341. node.exprName = this.tsParseImportType();
  4342. } else {
  4343. node.exprName = this.tsParseEntityName(true);
  4344. }
  4345. return this.finishNode(node, "TSTypeQuery");
  4346. }
  4347. tsParseTypeParameter() {
  4348. const node = this.startNode();
  4349. node.name = this.parseIdentifierName(node.start);
  4350. node.constraint = this.tsEatThenParseType(types._extends);
  4351. node.default = this.tsEatThenParseType(types.eq);
  4352. return this.finishNode(node, "TSTypeParameter");
  4353. }
  4354. tsTryParseTypeParameters() {
  4355. if (this.isRelational("<")) {
  4356. return this.tsParseTypeParameters();
  4357. }
  4358. }
  4359. tsParseTypeParameters() {
  4360. const node = this.startNode();
  4361. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4362. this.next();
  4363. } else {
  4364. this.unexpected();
  4365. }
  4366. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4367. return this.finishNode(node, "TSTypeParameterDeclaration");
  4368. }
  4369. tsTryNextParseConstantContext() {
  4370. if (this.lookahead().type === types._const) {
  4371. this.next();
  4372. return this.tsParseTypeReference();
  4373. }
  4374. return null;
  4375. }
  4376. tsFillSignature(returnToken, signature) {
  4377. const returnTokenRequired = returnToken === types.arrow;
  4378. signature.typeParameters = this.tsTryParseTypeParameters();
  4379. this.expect(types.parenL);
  4380. signature.parameters = this.tsParseBindingListForSignature();
  4381. if (returnTokenRequired) {
  4382. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4383. } else if (this.match(returnToken)) {
  4384. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4385. }
  4386. }
  4387. tsParseBindingListForSignature() {
  4388. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4389. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4390. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4391. }
  4392. return pattern;
  4393. });
  4394. }
  4395. tsParseTypeMemberSemicolon() {
  4396. if (!this.eat(types.comma)) {
  4397. this.semicolon();
  4398. }
  4399. }
  4400. tsParseSignatureMember(kind, node) {
  4401. this.tsFillSignature(types.colon, node);
  4402. this.tsParseTypeMemberSemicolon();
  4403. return this.finishNode(node, kind);
  4404. }
  4405. tsIsUnambiguouslyIndexSignature() {
  4406. this.next();
  4407. return this.eat(types.name) && this.match(types.colon);
  4408. }
  4409. tsTryParseIndexSignature(node) {
  4410. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4411. return undefined;
  4412. }
  4413. this.expect(types.bracketL);
  4414. const id = this.parseIdentifier();
  4415. id.typeAnnotation = this.tsParseTypeAnnotation();
  4416. this.resetEndLocation(id);
  4417. this.expect(types.bracketR);
  4418. node.parameters = [id];
  4419. const type = this.tsTryParseTypeAnnotation();
  4420. if (type) node.typeAnnotation = type;
  4421. this.tsParseTypeMemberSemicolon();
  4422. return this.finishNode(node, "TSIndexSignature");
  4423. }
  4424. tsParsePropertyOrMethodSignature(node, readonly) {
  4425. if (this.eat(types.question)) node.optional = true;
  4426. const nodeAny = node;
  4427. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  4428. const method = nodeAny;
  4429. this.tsFillSignature(types.colon, method);
  4430. this.tsParseTypeMemberSemicolon();
  4431. return this.finishNode(method, "TSMethodSignature");
  4432. } else {
  4433. const property = nodeAny;
  4434. if (readonly) property.readonly = true;
  4435. const type = this.tsTryParseTypeAnnotation();
  4436. if (type) property.typeAnnotation = type;
  4437. this.tsParseTypeMemberSemicolon();
  4438. return this.finishNode(property, "TSPropertySignature");
  4439. }
  4440. }
  4441. tsParseTypeMember() {
  4442. const node = this.startNode();
  4443. if (this.match(types.parenL) || this.isRelational("<")) {
  4444. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4445. }
  4446. if (this.match(types._new)) {
  4447. const id = this.startNode();
  4448. this.next();
  4449. if (this.match(types.parenL) || this.isRelational("<")) {
  4450. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4451. } else {
  4452. node.key = this.createIdentifier(id, "new");
  4453. return this.tsParsePropertyOrMethodSignature(node, false);
  4454. }
  4455. }
  4456. const readonly = !!this.tsParseModifier(["readonly"]);
  4457. const idx = this.tsTryParseIndexSignature(node);
  4458. if (idx) {
  4459. if (readonly) node.readonly = true;
  4460. return idx;
  4461. }
  4462. this.parsePropertyName(node, false);
  4463. return this.tsParsePropertyOrMethodSignature(node, readonly);
  4464. }
  4465. tsParseTypeLiteral() {
  4466. const node = this.startNode();
  4467. node.members = this.tsParseObjectTypeMembers();
  4468. return this.finishNode(node, "TSTypeLiteral");
  4469. }
  4470. tsParseObjectTypeMembers() {
  4471. this.expect(types.braceL);
  4472. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4473. this.expect(types.braceR);
  4474. return members;
  4475. }
  4476. tsIsStartOfMappedType() {
  4477. this.next();
  4478. if (this.eat(types.plusMin)) {
  4479. return this.isContextual("readonly");
  4480. }
  4481. if (this.isContextual("readonly")) {
  4482. this.next();
  4483. }
  4484. if (!this.match(types.bracketL)) {
  4485. return false;
  4486. }
  4487. this.next();
  4488. if (!this.tsIsIdentifier()) {
  4489. return false;
  4490. }
  4491. this.next();
  4492. return this.match(types._in);
  4493. }
  4494. tsParseMappedTypeParameter() {
  4495. const node = this.startNode();
  4496. node.name = this.parseIdentifierName(node.start);
  4497. node.constraint = this.tsExpectThenParseType(types._in);
  4498. return this.finishNode(node, "TSTypeParameter");
  4499. }
  4500. tsParseMappedType() {
  4501. const node = this.startNode();
  4502. this.expect(types.braceL);
  4503. if (this.match(types.plusMin)) {
  4504. node.readonly = this.state.value;
  4505. this.next();
  4506. this.expectContextual("readonly");
  4507. } else if (this.eatContextual("readonly")) {
  4508. node.readonly = true;
  4509. }
  4510. this.expect(types.bracketL);
  4511. node.typeParameter = this.tsParseMappedTypeParameter();
  4512. this.expect(types.bracketR);
  4513. if (this.match(types.plusMin)) {
  4514. node.optional = this.state.value;
  4515. this.next();
  4516. this.expect(types.question);
  4517. } else if (this.eat(types.question)) {
  4518. node.optional = true;
  4519. }
  4520. node.typeAnnotation = this.tsTryParseType();
  4521. this.semicolon();
  4522. this.expect(types.braceR);
  4523. return this.finishNode(node, "TSMappedType");
  4524. }
  4525. tsParseTupleType() {
  4526. const node = this.startNode();
  4527. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4528. let seenOptionalElement = false;
  4529. node.elementTypes.forEach(elementNode => {
  4530. if (elementNode.type === "TSOptionalType") {
  4531. seenOptionalElement = true;
  4532. } else if (seenOptionalElement && elementNode.type !== "TSRestType") {
  4533. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4534. }
  4535. });
  4536. return this.finishNode(node, "TSTupleType");
  4537. }
  4538. tsParseTupleElementType() {
  4539. if (this.match(types.ellipsis)) {
  4540. const restNode = this.startNode();
  4541. this.next();
  4542. restNode.typeAnnotation = this.tsParseType();
  4543. if (this.match(types.comma) && this.lookaheadCharCode() !== 93) {
  4544. this.raiseRestNotLast(this.state.start);
  4545. }
  4546. return this.finishNode(restNode, "TSRestType");
  4547. }
  4548. const type = this.tsParseType();
  4549. if (this.eat(types.question)) {
  4550. const optionalTypeNode = this.startNodeAtNode(type);
  4551. optionalTypeNode.typeAnnotation = type;
  4552. return this.finishNode(optionalTypeNode, "TSOptionalType");
  4553. }
  4554. return type;
  4555. }
  4556. tsParseParenthesizedType() {
  4557. const node = this.startNode();
  4558. this.expect(types.parenL);
  4559. node.typeAnnotation = this.tsParseType();
  4560. this.expect(types.parenR);
  4561. return this.finishNode(node, "TSParenthesizedType");
  4562. }
  4563. tsParseFunctionOrConstructorType(type) {
  4564. const node = this.startNode();
  4565. if (type === "TSConstructorType") {
  4566. this.expect(types._new);
  4567. }
  4568. this.tsFillSignature(types.arrow, node);
  4569. return this.finishNode(node, type);
  4570. }
  4571. tsParseLiteralTypeNode() {
  4572. const node = this.startNode();
  4573. node.literal = (() => {
  4574. switch (this.state.type) {
  4575. case types.num:
  4576. case types.string:
  4577. case types._true:
  4578. case types._false:
  4579. return this.parseExprAtom();
  4580. default:
  4581. throw this.unexpected();
  4582. }
  4583. })();
  4584. return this.finishNode(node, "TSLiteralType");
  4585. }
  4586. tsParseTemplateLiteralType() {
  4587. const node = this.startNode();
  4588. const templateNode = this.parseTemplate(false);
  4589. if (templateNode.expressions.length > 0) {
  4590. this.raise(templateNode.expressions[0].start, TSErrors.TemplateTypeHasSubstitution);
  4591. }
  4592. node.literal = templateNode;
  4593. return this.finishNode(node, "TSLiteralType");
  4594. }
  4595. tsParseThisTypeOrThisTypePredicate() {
  4596. const thisKeyword = this.tsParseThisTypeNode();
  4597. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4598. return this.tsParseThisTypePredicate(thisKeyword);
  4599. } else {
  4600. return thisKeyword;
  4601. }
  4602. }
  4603. tsParseNonArrayType() {
  4604. switch (this.state.type) {
  4605. case types.name:
  4606. case types._void:
  4607. case types._null:
  4608. {
  4609. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4610. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4611. const node = this.startNode();
  4612. this.next();
  4613. return this.finishNode(node, type);
  4614. }
  4615. return this.tsParseTypeReference();
  4616. }
  4617. case types.string:
  4618. case types.num:
  4619. case types._true:
  4620. case types._false:
  4621. return this.tsParseLiteralTypeNode();
  4622. case types.plusMin:
  4623. if (this.state.value === "-") {
  4624. const node = this.startNode();
  4625. if (this.lookahead().type !== types.num) {
  4626. throw this.unexpected();
  4627. }
  4628. node.literal = this.parseMaybeUnary();
  4629. return this.finishNode(node, "TSLiteralType");
  4630. }
  4631. break;
  4632. case types._this:
  4633. return this.tsParseThisTypeOrThisTypePredicate();
  4634. case types._typeof:
  4635. return this.tsParseTypeQuery();
  4636. case types._import:
  4637. return this.tsParseImportType();
  4638. case types.braceL:
  4639. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4640. case types.bracketL:
  4641. return this.tsParseTupleType();
  4642. case types.parenL:
  4643. return this.tsParseParenthesizedType();
  4644. case types.backQuote:
  4645. return this.tsParseTemplateLiteralType();
  4646. }
  4647. throw this.unexpected();
  4648. }
  4649. tsParseArrayTypeOrHigher() {
  4650. let type = this.tsParseNonArrayType();
  4651. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4652. if (this.match(types.bracketR)) {
  4653. const node = this.startNodeAtNode(type);
  4654. node.elementType = type;
  4655. this.expect(types.bracketR);
  4656. type = this.finishNode(node, "TSArrayType");
  4657. } else {
  4658. const node = this.startNodeAtNode(type);
  4659. node.objectType = type;
  4660. node.indexType = this.tsParseType();
  4661. this.expect(types.bracketR);
  4662. type = this.finishNode(node, "TSIndexedAccessType");
  4663. }
  4664. }
  4665. return type;
  4666. }
  4667. tsParseTypeOperator(operator) {
  4668. const node = this.startNode();
  4669. this.expectContextual(operator);
  4670. node.operator = operator;
  4671. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4672. if (operator === "readonly") {
  4673. this.tsCheckTypeAnnotationForReadOnly(node);
  4674. }
  4675. return this.finishNode(node, "TSTypeOperator");
  4676. }
  4677. tsCheckTypeAnnotationForReadOnly(node) {
  4678. switch (node.typeAnnotation.type) {
  4679. case "TSTupleType":
  4680. case "TSArrayType":
  4681. return;
  4682. default:
  4683. this.raise(node.start, TSErrors.UnexpectedReadonly);
  4684. }
  4685. }
  4686. tsParseInferType() {
  4687. const node = this.startNode();
  4688. this.expectContextual("infer");
  4689. const typeParameter = this.startNode();
  4690. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4691. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4692. return this.finishNode(node, "TSInferType");
  4693. }
  4694. tsParseTypeOperatorOrHigher() {
  4695. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4696. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4697. }
  4698. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4699. this.eat(operator);
  4700. let type = parseConstituentType();
  4701. if (this.match(operator)) {
  4702. const types = [type];
  4703. while (this.eat(operator)) {
  4704. types.push(parseConstituentType());
  4705. }
  4706. const node = this.startNodeAtNode(type);
  4707. node.types = types;
  4708. type = this.finishNode(node, kind);
  4709. }
  4710. return type;
  4711. }
  4712. tsParseIntersectionTypeOrHigher() {
  4713. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4714. }
  4715. tsParseUnionTypeOrHigher() {
  4716. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4717. }
  4718. tsIsStartOfFunctionType() {
  4719. if (this.isRelational("<")) {
  4720. return true;
  4721. }
  4722. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4723. }
  4724. tsSkipParameterStart() {
  4725. if (this.match(types.name) || this.match(types._this)) {
  4726. this.next();
  4727. return true;
  4728. }
  4729. if (this.match(types.braceL)) {
  4730. let braceStackCounter = 1;
  4731. this.next();
  4732. while (braceStackCounter > 0) {
  4733. if (this.match(types.braceL)) {
  4734. ++braceStackCounter;
  4735. } else if (this.match(types.braceR)) {
  4736. --braceStackCounter;
  4737. }
  4738. this.next();
  4739. }
  4740. return true;
  4741. }
  4742. if (this.match(types.bracketL)) {
  4743. let braceStackCounter = 1;
  4744. this.next();
  4745. while (braceStackCounter > 0) {
  4746. if (this.match(types.bracketL)) {
  4747. ++braceStackCounter;
  4748. } else if (this.match(types.bracketR)) {
  4749. --braceStackCounter;
  4750. }
  4751. this.next();
  4752. }
  4753. return true;
  4754. }
  4755. return false;
  4756. }
  4757. tsIsUnambiguouslyStartOfFunctionType() {
  4758. this.next();
  4759. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4760. return true;
  4761. }
  4762. if (this.tsSkipParameterStart()) {
  4763. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4764. return true;
  4765. }
  4766. if (this.match(types.parenR)) {
  4767. this.next();
  4768. if (this.match(types.arrow)) {
  4769. return true;
  4770. }
  4771. }
  4772. }
  4773. return false;
  4774. }
  4775. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4776. return this.tsInType(() => {
  4777. const t = this.startNode();
  4778. this.expect(returnToken);
  4779. const asserts = this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4780. if (asserts && this.match(types._this)) {
  4781. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4782. if (thisTypePredicate.type === "TSThisType") {
  4783. const node = this.startNodeAtNode(t);
  4784. node.parameterName = thisTypePredicate;
  4785. node.asserts = true;
  4786. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4787. } else {
  4788. thisTypePredicate.asserts = true;
  4789. }
  4790. t.typeAnnotation = thisTypePredicate;
  4791. return this.finishNode(t, "TSTypeAnnotation");
  4792. }
  4793. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4794. if (!typePredicateVariable) {
  4795. if (!asserts) {
  4796. return this.tsParseTypeAnnotation(false, t);
  4797. }
  4798. const node = this.startNodeAtNode(t);
  4799. node.parameterName = this.parseIdentifier();
  4800. node.asserts = asserts;
  4801. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4802. return this.finishNode(t, "TSTypeAnnotation");
  4803. }
  4804. const type = this.tsParseTypeAnnotation(false);
  4805. const node = this.startNodeAtNode(t);
  4806. node.parameterName = typePredicateVariable;
  4807. node.typeAnnotation = type;
  4808. node.asserts = asserts;
  4809. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4810. return this.finishNode(t, "TSTypeAnnotation");
  4811. });
  4812. }
  4813. tsTryParseTypeOrTypePredicateAnnotation() {
  4814. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4815. }
  4816. tsTryParseTypeAnnotation() {
  4817. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4818. }
  4819. tsTryParseType() {
  4820. return this.tsEatThenParseType(types.colon);
  4821. }
  4822. tsParseTypePredicatePrefix() {
  4823. const id = this.parseIdentifier();
  4824. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4825. this.next();
  4826. return id;
  4827. }
  4828. }
  4829. tsParseTypePredicateAsserts() {
  4830. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4831. return false;
  4832. }
  4833. const containsEsc = this.state.containsEsc;
  4834. this.next();
  4835. if (!this.match(types.name) && !this.match(types._this)) {
  4836. return false;
  4837. }
  4838. if (containsEsc) {
  4839. this.raise(this.state.lastTokStart, Errors.InvalidEscapedReservedWord, "asserts");
  4840. }
  4841. return true;
  4842. }
  4843. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  4844. this.tsInType(() => {
  4845. if (eatColon) this.expect(types.colon);
  4846. t.typeAnnotation = this.tsParseType();
  4847. });
  4848. return this.finishNode(t, "TSTypeAnnotation");
  4849. }
  4850. tsParseType() {
  4851. assert(this.state.inType);
  4852. const type = this.tsParseNonConditionalType();
  4853. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  4854. return type;
  4855. }
  4856. const node = this.startNodeAtNode(type);
  4857. node.checkType = type;
  4858. node.extendsType = this.tsParseNonConditionalType();
  4859. this.expect(types.question);
  4860. node.trueType = this.tsParseType();
  4861. this.expect(types.colon);
  4862. node.falseType = this.tsParseType();
  4863. return this.finishNode(node, "TSConditionalType");
  4864. }
  4865. tsParseNonConditionalType() {
  4866. if (this.tsIsStartOfFunctionType()) {
  4867. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  4868. }
  4869. if (this.match(types._new)) {
  4870. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  4871. }
  4872. return this.tsParseUnionTypeOrHigher();
  4873. }
  4874. tsParseTypeAssertion() {
  4875. const node = this.startNode();
  4876. const _const = this.tsTryNextParseConstantContext();
  4877. node.typeAnnotation = _const || this.tsNextThenParseType();
  4878. this.expectRelational(">");
  4879. node.expression = this.parseMaybeUnary();
  4880. return this.finishNode(node, "TSTypeAssertion");
  4881. }
  4882. tsParseHeritageClause(descriptor) {
  4883. const originalStart = this.state.start;
  4884. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  4885. if (!delimitedList.length) {
  4886. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  4887. }
  4888. return delimitedList;
  4889. }
  4890. tsParseExpressionWithTypeArguments() {
  4891. const node = this.startNode();
  4892. node.expression = this.tsParseEntityName(false);
  4893. if (this.isRelational("<")) {
  4894. node.typeParameters = this.tsParseTypeArguments();
  4895. }
  4896. return this.finishNode(node, "TSExpressionWithTypeArguments");
  4897. }
  4898. tsParseInterfaceDeclaration(node) {
  4899. node.id = this.parseIdentifier();
  4900. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  4901. node.typeParameters = this.tsTryParseTypeParameters();
  4902. if (this.eat(types._extends)) {
  4903. node.extends = this.tsParseHeritageClause("extends");
  4904. }
  4905. const body = this.startNode();
  4906. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  4907. node.body = this.finishNode(body, "TSInterfaceBody");
  4908. return this.finishNode(node, "TSInterfaceDeclaration");
  4909. }
  4910. tsParseTypeAliasDeclaration(node) {
  4911. node.id = this.parseIdentifier();
  4912. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  4913. node.typeParameters = this.tsTryParseTypeParameters();
  4914. node.typeAnnotation = this.tsExpectThenParseType(types.eq);
  4915. this.semicolon();
  4916. return this.finishNode(node, "TSTypeAliasDeclaration");
  4917. }
  4918. tsInNoContext(cb) {
  4919. const oldContext = this.state.context;
  4920. this.state.context = [oldContext[0]];
  4921. try {
  4922. return cb();
  4923. } finally {
  4924. this.state.context = oldContext;
  4925. }
  4926. }
  4927. tsInType(cb) {
  4928. const oldInType = this.state.inType;
  4929. this.state.inType = true;
  4930. try {
  4931. return cb();
  4932. } finally {
  4933. this.state.inType = oldInType;
  4934. }
  4935. }
  4936. tsEatThenParseType(token) {
  4937. return !this.match(token) ? undefined : this.tsNextThenParseType();
  4938. }
  4939. tsExpectThenParseType(token) {
  4940. return this.tsDoThenParseType(() => this.expect(token));
  4941. }
  4942. tsNextThenParseType() {
  4943. return this.tsDoThenParseType(() => this.next());
  4944. }
  4945. tsDoThenParseType(cb) {
  4946. return this.tsInType(() => {
  4947. cb();
  4948. return this.tsParseType();
  4949. });
  4950. }
  4951. tsParseEnumMember() {
  4952. const node = this.startNode();
  4953. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  4954. if (this.eat(types.eq)) {
  4955. node.initializer = this.parseMaybeAssign();
  4956. }
  4957. return this.finishNode(node, "TSEnumMember");
  4958. }
  4959. tsParseEnumDeclaration(node, isConst) {
  4960. if (isConst) node.const = true;
  4961. node.id = this.parseIdentifier();
  4962. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  4963. this.expect(types.braceL);
  4964. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  4965. this.expect(types.braceR);
  4966. return this.finishNode(node, "TSEnumDeclaration");
  4967. }
  4968. tsParseModuleBlock() {
  4969. const node = this.startNode();
  4970. this.scope.enter(SCOPE_OTHER);
  4971. this.expect(types.braceL);
  4972. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  4973. this.scope.exit();
  4974. return this.finishNode(node, "TSModuleBlock");
  4975. }
  4976. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  4977. node.id = this.parseIdentifier();
  4978. if (!nested) {
  4979. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  4980. }
  4981. if (this.eat(types.dot)) {
  4982. const inner = this.startNode();
  4983. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  4984. node.body = inner;
  4985. } else {
  4986. this.scope.enter(SCOPE_TS_MODULE);
  4987. this.prodParam.enter(PARAM);
  4988. node.body = this.tsParseModuleBlock();
  4989. this.prodParam.exit();
  4990. this.scope.exit();
  4991. }
  4992. return this.finishNode(node, "TSModuleDeclaration");
  4993. }
  4994. tsParseAmbientExternalModuleDeclaration(node) {
  4995. if (this.isContextual("global")) {
  4996. node.global = true;
  4997. node.id = this.parseIdentifier();
  4998. } else if (this.match(types.string)) {
  4999. node.id = this.parseExprAtom();
  5000. } else {
  5001. this.unexpected();
  5002. }
  5003. if (this.match(types.braceL)) {
  5004. this.scope.enter(SCOPE_TS_MODULE);
  5005. this.prodParam.enter(PARAM);
  5006. node.body = this.tsParseModuleBlock();
  5007. this.prodParam.exit();
  5008. this.scope.exit();
  5009. } else {
  5010. this.semicolon();
  5011. }
  5012. return this.finishNode(node, "TSModuleDeclaration");
  5013. }
  5014. tsParseImportEqualsDeclaration(node, isExport) {
  5015. node.isExport = isExport || false;
  5016. node.id = this.parseIdentifier();
  5017. this.checkLVal(node.id, BIND_LEXICAL, undefined, "import equals declaration");
  5018. this.expect(types.eq);
  5019. node.moduleReference = this.tsParseModuleReference();
  5020. this.semicolon();
  5021. return this.finishNode(node, "TSImportEqualsDeclaration");
  5022. }
  5023. tsIsExternalModuleReference() {
  5024. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5025. }
  5026. tsParseModuleReference() {
  5027. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5028. }
  5029. tsParseExternalModuleReference() {
  5030. const node = this.startNode();
  5031. this.expectContextual("require");
  5032. this.expect(types.parenL);
  5033. if (!this.match(types.string)) {
  5034. throw this.unexpected();
  5035. }
  5036. node.expression = this.parseExprAtom();
  5037. this.expect(types.parenR);
  5038. return this.finishNode(node, "TSExternalModuleReference");
  5039. }
  5040. tsLookAhead(f) {
  5041. const state = this.state.clone();
  5042. const res = f();
  5043. this.state = state;
  5044. return res;
  5045. }
  5046. tsTryParseAndCatch(f) {
  5047. const result = this.tryParse(abort => f() || abort());
  5048. if (result.aborted || !result.node) return undefined;
  5049. if (result.error) this.state = result.failState;
  5050. return result.node;
  5051. }
  5052. tsTryParse(f) {
  5053. const state = this.state.clone();
  5054. const result = f();
  5055. if (result !== undefined && result !== false) {
  5056. return result;
  5057. } else {
  5058. this.state = state;
  5059. return undefined;
  5060. }
  5061. }
  5062. tsTryParseDeclare(nany) {
  5063. if (this.isLineTerminator()) {
  5064. return;
  5065. }
  5066. let starttype = this.state.type;
  5067. let kind;
  5068. if (this.isContextual("let")) {
  5069. starttype = types._var;
  5070. kind = "let";
  5071. }
  5072. switch (starttype) {
  5073. case types._function:
  5074. return this.parseFunctionStatement(nany, false, true);
  5075. case types._class:
  5076. nany.declare = true;
  5077. return this.parseClass(nany, true, false);
  5078. case types._const:
  5079. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5080. this.expect(types._const);
  5081. this.expectContextual("enum");
  5082. return this.tsParseEnumDeclaration(nany, true);
  5083. }
  5084. case types._var:
  5085. kind = kind || this.state.value;
  5086. return this.parseVarStatement(nany, kind);
  5087. case types.name:
  5088. {
  5089. const value = this.state.value;
  5090. if (value === "global") {
  5091. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5092. } else {
  5093. return this.tsParseDeclaration(nany, value, true);
  5094. }
  5095. }
  5096. }
  5097. }
  5098. tsTryParseExportDeclaration() {
  5099. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5100. }
  5101. tsParseExpressionStatement(node, expr) {
  5102. switch (expr.name) {
  5103. case "declare":
  5104. {
  5105. const declaration = this.tsTryParseDeclare(node);
  5106. if (declaration) {
  5107. declaration.declare = true;
  5108. return declaration;
  5109. }
  5110. break;
  5111. }
  5112. case "global":
  5113. if (this.match(types.braceL)) {
  5114. this.scope.enter(SCOPE_TS_MODULE);
  5115. this.prodParam.enter(PARAM);
  5116. const mod = node;
  5117. mod.global = true;
  5118. mod.id = expr;
  5119. mod.body = this.tsParseModuleBlock();
  5120. this.scope.exit();
  5121. this.prodParam.exit();
  5122. return this.finishNode(mod, "TSModuleDeclaration");
  5123. }
  5124. break;
  5125. default:
  5126. return this.tsParseDeclaration(node, expr.name, false);
  5127. }
  5128. }
  5129. tsParseDeclaration(node, value, next) {
  5130. switch (value) {
  5131. case "abstract":
  5132. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  5133. const cls = node;
  5134. cls.abstract = true;
  5135. if (next) {
  5136. this.next();
  5137. if (!this.match(types._class)) {
  5138. this.unexpected(null, types._class);
  5139. }
  5140. }
  5141. return this.parseClass(cls, true, false);
  5142. }
  5143. break;
  5144. case "enum":
  5145. if (next || this.match(types.name)) {
  5146. if (next) this.next();
  5147. return this.tsParseEnumDeclaration(node, false);
  5148. }
  5149. break;
  5150. case "interface":
  5151. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5152. if (next) this.next();
  5153. return this.tsParseInterfaceDeclaration(node);
  5154. }
  5155. break;
  5156. case "module":
  5157. if (next) this.next();
  5158. if (this.match(types.string)) {
  5159. return this.tsParseAmbientExternalModuleDeclaration(node);
  5160. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5161. return this.tsParseModuleOrNamespaceDeclaration(node);
  5162. }
  5163. break;
  5164. case "namespace":
  5165. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5166. if (next) this.next();
  5167. return this.tsParseModuleOrNamespaceDeclaration(node);
  5168. }
  5169. break;
  5170. case "type":
  5171. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5172. if (next) this.next();
  5173. return this.tsParseTypeAliasDeclaration(node);
  5174. }
  5175. break;
  5176. }
  5177. }
  5178. tsCheckLineTerminatorAndMatch(tokenType, next) {
  5179. return (next || this.match(tokenType)) && !this.isLineTerminator();
  5180. }
  5181. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5182. if (!this.isRelational("<")) {
  5183. return undefined;
  5184. }
  5185. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5186. const oldYieldPos = this.state.yieldPos;
  5187. const oldAwaitPos = this.state.awaitPos;
  5188. this.state.maybeInArrowParameters = true;
  5189. this.state.yieldPos = -1;
  5190. this.state.awaitPos = -1;
  5191. const res = this.tsTryParseAndCatch(() => {
  5192. const node = this.startNodeAt(startPos, startLoc);
  5193. node.typeParameters = this.tsParseTypeParameters();
  5194. super.parseFunctionParams(node);
  5195. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5196. this.expect(types.arrow);
  5197. return node;
  5198. });
  5199. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5200. this.state.yieldPos = oldYieldPos;
  5201. this.state.awaitPos = oldAwaitPos;
  5202. if (!res) {
  5203. return undefined;
  5204. }
  5205. return this.parseArrowExpression(res, null, true);
  5206. }
  5207. tsParseTypeArguments() {
  5208. const node = this.startNode();
  5209. node.params = this.tsInType(() => this.tsInNoContext(() => {
  5210. this.expectRelational("<");
  5211. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  5212. }));
  5213. this.state.exprAllowed = false;
  5214. this.expectRelational(">");
  5215. return this.finishNode(node, "TSTypeParameterInstantiation");
  5216. }
  5217. tsIsDeclarationStart() {
  5218. if (this.match(types.name)) {
  5219. switch (this.state.value) {
  5220. case "abstract":
  5221. case "declare":
  5222. case "enum":
  5223. case "interface":
  5224. case "module":
  5225. case "namespace":
  5226. case "type":
  5227. return true;
  5228. }
  5229. }
  5230. return false;
  5231. }
  5232. isExportDefaultSpecifier() {
  5233. if (this.tsIsDeclarationStart()) return false;
  5234. return super.isExportDefaultSpecifier();
  5235. }
  5236. parseAssignableListItem(allowModifiers, decorators) {
  5237. const startPos = this.state.start;
  5238. const startLoc = this.state.startLoc;
  5239. let accessibility;
  5240. let readonly = false;
  5241. if (allowModifiers) {
  5242. accessibility = this.parseAccessModifier();
  5243. readonly = !!this.tsParseModifier(["readonly"]);
  5244. }
  5245. const left = this.parseMaybeDefault();
  5246. this.parseAssignableListItemTypes(left);
  5247. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  5248. if (accessibility || readonly) {
  5249. const pp = this.startNodeAt(startPos, startLoc);
  5250. if (decorators.length) {
  5251. pp.decorators = decorators;
  5252. }
  5253. if (accessibility) pp.accessibility = accessibility;
  5254. if (readonly) pp.readonly = readonly;
  5255. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  5256. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  5257. }
  5258. pp.parameter = elt;
  5259. return this.finishNode(pp, "TSParameterProperty");
  5260. }
  5261. if (decorators.length) {
  5262. left.decorators = decorators;
  5263. }
  5264. return elt;
  5265. }
  5266. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5267. if (this.match(types.colon)) {
  5268. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5269. }
  5270. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  5271. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  5272. this.finishNode(node, bodilessType);
  5273. return;
  5274. }
  5275. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5276. }
  5277. registerFunctionStatementId(node) {
  5278. if (!node.body && node.id) {
  5279. this.checkLVal(node.id, BIND_TS_AMBIENT, null, "function name");
  5280. } else {
  5281. super.registerFunctionStatementId(...arguments);
  5282. }
  5283. }
  5284. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5285. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5286. this.state.exprAllowed = false;
  5287. this.next();
  5288. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5289. nonNullExpression.expression = base;
  5290. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5291. }
  5292. if (this.isRelational("<")) {
  5293. const result = this.tsTryParseAndCatch(() => {
  5294. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5295. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5296. if (asyncArrowFn) {
  5297. return asyncArrowFn;
  5298. }
  5299. }
  5300. const node = this.startNodeAt(startPos, startLoc);
  5301. node.callee = base;
  5302. const typeArguments = this.tsParseTypeArguments();
  5303. if (typeArguments) {
  5304. if (!noCalls && this.eat(types.parenL)) {
  5305. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5306. node.typeParameters = typeArguments;
  5307. return this.finishCallExpression(node, state.optionalChainMember);
  5308. } else if (this.match(types.backQuote)) {
  5309. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments);
  5310. }
  5311. }
  5312. this.unexpected();
  5313. });
  5314. if (result) return result;
  5315. }
  5316. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5317. }
  5318. parseNewArguments(node) {
  5319. if (this.isRelational("<")) {
  5320. const typeParameters = this.tsTryParseAndCatch(() => {
  5321. const args = this.tsParseTypeArguments();
  5322. if (!this.match(types.parenL)) this.unexpected();
  5323. return args;
  5324. });
  5325. if (typeParameters) {
  5326. node.typeParameters = typeParameters;
  5327. }
  5328. }
  5329. super.parseNewArguments(node);
  5330. }
  5331. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  5332. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5333. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5334. node.expression = left;
  5335. const _const = this.tsTryNextParseConstantContext();
  5336. if (_const) {
  5337. node.typeAnnotation = _const;
  5338. } else {
  5339. node.typeAnnotation = this.tsNextThenParseType();
  5340. }
  5341. this.finishNode(node, "TSAsExpression");
  5342. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  5343. }
  5344. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn);
  5345. }
  5346. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5347. checkDuplicateExports() {}
  5348. parseImport(node) {
  5349. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5350. const ahead = this.lookahead();
  5351. if (this.match(types.name) && ahead.type === types.eq) {
  5352. return this.tsParseImportEqualsDeclaration(node);
  5353. }
  5354. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  5355. node.importKind = "type";
  5356. this.next();
  5357. } else {
  5358. node.importKind = "value";
  5359. }
  5360. }
  5361. const importNode = super.parseImport(node);
  5362. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5363. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5364. }
  5365. return importNode;
  5366. }
  5367. parseExport(node) {
  5368. if (this.match(types._import)) {
  5369. this.expect(types._import);
  5370. return this.tsParseImportEqualsDeclaration(node, true);
  5371. } else if (this.eat(types.eq)) {
  5372. const assign = node;
  5373. assign.expression = this.parseExpression();
  5374. this.semicolon();
  5375. return this.finishNode(assign, "TSExportAssignment");
  5376. } else if (this.eatContextual("as")) {
  5377. const decl = node;
  5378. this.expectContextual("namespace");
  5379. decl.id = this.parseIdentifier();
  5380. this.semicolon();
  5381. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5382. } else {
  5383. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5384. this.next();
  5385. node.exportKind = "type";
  5386. } else {
  5387. node.exportKind = "value";
  5388. }
  5389. return super.parseExport(node);
  5390. }
  5391. }
  5392. isAbstractClass() {
  5393. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5394. }
  5395. parseExportDefaultExpression() {
  5396. if (this.isAbstractClass()) {
  5397. const cls = this.startNode();
  5398. this.next();
  5399. this.parseClass(cls, true, true);
  5400. cls.abstract = true;
  5401. return cls;
  5402. }
  5403. if (this.state.value === "interface") {
  5404. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5405. if (result) return result;
  5406. }
  5407. return super.parseExportDefaultExpression();
  5408. }
  5409. parseStatementContent(context, topLevel) {
  5410. if (this.state.type === types._const) {
  5411. const ahead = this.lookahead();
  5412. if (ahead.type === types.name && ahead.value === "enum") {
  5413. const node = this.startNode();
  5414. this.expect(types._const);
  5415. this.expectContextual("enum");
  5416. return this.tsParseEnumDeclaration(node, true);
  5417. }
  5418. }
  5419. return super.parseStatementContent(context, topLevel);
  5420. }
  5421. parseAccessModifier() {
  5422. return this.tsParseModifier(["public", "protected", "private"]);
  5423. }
  5424. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  5425. this.tsParseModifiers(member, ["declare"]);
  5426. const accessibility = this.parseAccessModifier();
  5427. if (accessibility) member.accessibility = accessibility;
  5428. this.tsParseModifiers(member, ["declare"]);
  5429. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  5430. }
  5431. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  5432. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5433. const idx = this.tsTryParseIndexSignature(member);
  5434. if (idx) {
  5435. classBody.body.push(idx);
  5436. if (member.abstract) {
  5437. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5438. }
  5439. if (isStatic) {
  5440. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5441. }
  5442. if (member.accessibility) {
  5443. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5444. }
  5445. return;
  5446. }
  5447. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  5448. }
  5449. parsePostMemberNameModifiers(methodOrProp) {
  5450. const optional = this.eat(types.question);
  5451. if (optional) methodOrProp.optional = true;
  5452. if (methodOrProp.readonly && this.match(types.parenL)) {
  5453. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5454. }
  5455. if (methodOrProp.declare && this.match(types.parenL)) {
  5456. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5457. }
  5458. }
  5459. parseExpressionStatement(node, expr) {
  5460. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5461. return decl || super.parseExpressionStatement(node, expr);
  5462. }
  5463. shouldParseExportDeclaration() {
  5464. if (this.tsIsDeclarationStart()) return true;
  5465. return super.shouldParseExportDeclaration();
  5466. }
  5467. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  5468. if (!refNeedsArrowPos || !this.match(types.question)) {
  5469. return super.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  5470. }
  5471. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  5472. if (!result.node) {
  5473. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5474. return expr;
  5475. }
  5476. if (result.error) this.state = result.failState;
  5477. return result.node;
  5478. }
  5479. parseParenItem(node, startPos, startLoc) {
  5480. node = super.parseParenItem(node, startPos, startLoc);
  5481. if (this.eat(types.question)) {
  5482. node.optional = true;
  5483. this.resetEndLocation(node);
  5484. }
  5485. if (this.match(types.colon)) {
  5486. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5487. typeCastNode.expression = node;
  5488. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5489. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5490. }
  5491. return node;
  5492. }
  5493. parseExportDeclaration(node) {
  5494. const startPos = this.state.start;
  5495. const startLoc = this.state.startLoc;
  5496. const isDeclare = this.eatContextual("declare");
  5497. let declaration;
  5498. if (this.match(types.name)) {
  5499. declaration = this.tsTryParseExportDeclaration();
  5500. }
  5501. if (!declaration) {
  5502. declaration = super.parseExportDeclaration(node);
  5503. }
  5504. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5505. node.exportKind = "type";
  5506. }
  5507. if (declaration && isDeclare) {
  5508. this.resetStartLocation(declaration, startPos, startLoc);
  5509. declaration.declare = true;
  5510. }
  5511. return declaration;
  5512. }
  5513. parseClassId(node, isStatement, optionalId) {
  5514. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5515. return;
  5516. }
  5517. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5518. const typeParameters = this.tsTryParseTypeParameters();
  5519. if (typeParameters) node.typeParameters = typeParameters;
  5520. }
  5521. parseClassPropertyAnnotation(node) {
  5522. if (!node.optional && this.eat(types.bang)) {
  5523. node.definite = true;
  5524. }
  5525. const type = this.tsTryParseTypeAnnotation();
  5526. if (type) node.typeAnnotation = type;
  5527. }
  5528. parseClassProperty(node) {
  5529. this.parseClassPropertyAnnotation(node);
  5530. if (node.declare && this.match(types.equal)) {
  5531. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5532. }
  5533. return super.parseClassProperty(node);
  5534. }
  5535. parseClassPrivateProperty(node) {
  5536. if (node.abstract) {
  5537. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  5538. }
  5539. if (node.accessibility) {
  5540. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  5541. }
  5542. this.parseClassPropertyAnnotation(node);
  5543. return super.parseClassPrivateProperty(node);
  5544. }
  5545. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5546. const typeParameters = this.tsTryParseTypeParameters();
  5547. if (typeParameters) method.typeParameters = typeParameters;
  5548. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5549. }
  5550. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5551. const typeParameters = this.tsTryParseTypeParameters();
  5552. if (typeParameters) method.typeParameters = typeParameters;
  5553. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5554. }
  5555. parseClassSuper(node) {
  5556. super.parseClassSuper(node);
  5557. if (node.superClass && this.isRelational("<")) {
  5558. node.superTypeParameters = this.tsParseTypeArguments();
  5559. }
  5560. if (this.eatContextual("implements")) {
  5561. node.implements = this.tsParseHeritageClause("implements");
  5562. }
  5563. }
  5564. parseObjPropValue(prop, ...args) {
  5565. const typeParameters = this.tsTryParseTypeParameters();
  5566. if (typeParameters) prop.typeParameters = typeParameters;
  5567. super.parseObjPropValue(prop, ...args);
  5568. }
  5569. parseFunctionParams(node, allowModifiers) {
  5570. const typeParameters = this.tsTryParseTypeParameters();
  5571. if (typeParameters) node.typeParameters = typeParameters;
  5572. super.parseFunctionParams(node, allowModifiers);
  5573. }
  5574. parseVarId(decl, kind) {
  5575. super.parseVarId(decl, kind);
  5576. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5577. decl.definite = true;
  5578. }
  5579. const type = this.tsTryParseTypeAnnotation();
  5580. if (type) {
  5581. decl.id.typeAnnotation = type;
  5582. this.resetEndLocation(decl.id);
  5583. }
  5584. }
  5585. parseAsyncArrowFromCallExpression(node, call) {
  5586. if (this.match(types.colon)) {
  5587. node.returnType = this.tsParseTypeAnnotation();
  5588. }
  5589. return super.parseAsyncArrowFromCallExpression(node, call);
  5590. }
  5591. parseMaybeAssign(...args) {
  5592. let state;
  5593. let jsx;
  5594. let typeCast;
  5595. if (this.match(types.jsxTagStart)) {
  5596. state = this.state.clone();
  5597. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5598. if (!jsx.error) return jsx.node;
  5599. const {
  5600. context
  5601. } = this.state;
  5602. if (context[context.length - 1] === types$1.j_oTag) {
  5603. context.length -= 2;
  5604. } else if (context[context.length - 1] === types$1.j_expr) {
  5605. context.length -= 1;
  5606. }
  5607. }
  5608. if (!(jsx && jsx.error) && !this.isRelational("<")) {
  5609. return super.parseMaybeAssign(...args);
  5610. }
  5611. let typeParameters;
  5612. state = state || this.state.clone();
  5613. const arrow = this.tryParse(abort => {
  5614. typeParameters = this.tsParseTypeParameters();
  5615. const expr = super.parseMaybeAssign(...args);
  5616. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5617. abort();
  5618. }
  5619. if (typeParameters && typeParameters.params.length !== 0) {
  5620. this.resetStartLocationFromNode(expr, typeParameters);
  5621. }
  5622. expr.typeParameters = typeParameters;
  5623. return expr;
  5624. }, state);
  5625. if (!arrow.error && !arrow.aborted) return arrow.node;
  5626. if (!jsx) {
  5627. assert(!this.hasPlugin("jsx"));
  5628. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5629. if (!typeCast.error) return typeCast.node;
  5630. }
  5631. if (jsx && jsx.node) {
  5632. this.state = jsx.failState;
  5633. return jsx.node;
  5634. }
  5635. if (arrow.node) {
  5636. this.state = arrow.failState;
  5637. return arrow.node;
  5638. }
  5639. if (typeCast && typeCast.node) {
  5640. this.state = typeCast.failState;
  5641. return typeCast.node;
  5642. }
  5643. if (jsx && jsx.thrown) throw jsx.error;
  5644. if (arrow.thrown) throw arrow.error;
  5645. if (typeCast && typeCast.thrown) throw typeCast.error;
  5646. throw jsx && jsx.error || arrow.error || typeCast && typeCast.error;
  5647. }
  5648. parseMaybeUnary(refExpressionErrors) {
  5649. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5650. return this.tsParseTypeAssertion();
  5651. } else {
  5652. return super.parseMaybeUnary(refExpressionErrors);
  5653. }
  5654. }
  5655. parseArrow(node) {
  5656. if (this.match(types.colon)) {
  5657. const result = this.tryParse(abort => {
  5658. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5659. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5660. return returnType;
  5661. });
  5662. if (result.aborted) return;
  5663. if (!result.thrown) {
  5664. if (result.error) this.state = result.failState;
  5665. node.returnType = result.node;
  5666. }
  5667. }
  5668. return super.parseArrow(node);
  5669. }
  5670. parseAssignableListItemTypes(param) {
  5671. if (this.eat(types.question)) {
  5672. if (param.type !== "Identifier") {
  5673. this.raise(param.start, TSErrors.PatternIsOptional);
  5674. }
  5675. param.optional = true;
  5676. }
  5677. const type = this.tsTryParseTypeAnnotation();
  5678. if (type) param.typeAnnotation = type;
  5679. this.resetEndLocation(param);
  5680. return param;
  5681. }
  5682. toAssignable(node) {
  5683. switch (node.type) {
  5684. case "TSTypeCastExpression":
  5685. return super.toAssignable(this.typeCastToParameter(node));
  5686. case "TSParameterProperty":
  5687. return super.toAssignable(node);
  5688. case "TSAsExpression":
  5689. case "TSNonNullExpression":
  5690. case "TSTypeAssertion":
  5691. node.expression = this.toAssignable(node.expression);
  5692. return node;
  5693. default:
  5694. return super.toAssignable(node);
  5695. }
  5696. }
  5697. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  5698. switch (expr.type) {
  5699. case "TSTypeCastExpression":
  5700. return;
  5701. case "TSParameterProperty":
  5702. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  5703. return;
  5704. case "TSAsExpression":
  5705. case "TSNonNullExpression":
  5706. case "TSTypeAssertion":
  5707. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  5708. return;
  5709. default:
  5710. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  5711. return;
  5712. }
  5713. }
  5714. parseBindingAtom() {
  5715. switch (this.state.type) {
  5716. case types._this:
  5717. return this.parseIdentifier(true);
  5718. default:
  5719. return super.parseBindingAtom();
  5720. }
  5721. }
  5722. parseMaybeDecoratorArguments(expr) {
  5723. if (this.isRelational("<")) {
  5724. const typeArguments = this.tsParseTypeArguments();
  5725. if (this.match(types.parenL)) {
  5726. const call = super.parseMaybeDecoratorArguments(expr);
  5727. call.typeParameters = typeArguments;
  5728. return call;
  5729. }
  5730. this.unexpected(this.state.start, types.parenL);
  5731. }
  5732. return super.parseMaybeDecoratorArguments(expr);
  5733. }
  5734. isClassMethod() {
  5735. return this.isRelational("<") || super.isClassMethod();
  5736. }
  5737. isClassProperty() {
  5738. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5739. }
  5740. parseMaybeDefault(...args) {
  5741. const node = super.parseMaybeDefault(...args);
  5742. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5743. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  5744. }
  5745. return node;
  5746. }
  5747. getTokenFromCode(code) {
  5748. if (this.state.inType && (code === 62 || code === 60)) {
  5749. return this.finishOp(types.relational, 1);
  5750. } else {
  5751. return super.getTokenFromCode(code);
  5752. }
  5753. }
  5754. toAssignableList(exprList) {
  5755. for (let i = 0; i < exprList.length; i++) {
  5756. const expr = exprList[i];
  5757. if (!expr) continue;
  5758. switch (expr.type) {
  5759. case "TSTypeCastExpression":
  5760. exprList[i] = this.typeCastToParameter(expr);
  5761. break;
  5762. case "TSAsExpression":
  5763. case "TSTypeAssertion":
  5764. if (!this.state.maybeInArrowParameters) {
  5765. exprList[i] = this.typeCastToParameter(expr);
  5766. } else {
  5767. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  5768. }
  5769. break;
  5770. }
  5771. }
  5772. return super.toAssignableList(...arguments);
  5773. }
  5774. typeCastToParameter(node) {
  5775. node.expression.typeAnnotation = node.typeAnnotation;
  5776. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5777. return node.expression;
  5778. }
  5779. toReferencedList(exprList, isInParens) {
  5780. for (let i = 0; i < exprList.length; i++) {
  5781. const expr = exprList[i];
  5782. if (expr && expr.type === "TSTypeCastExpression") {
  5783. this.raise(expr.start, TSErrors.UnexpectedTypeAnnotation);
  5784. }
  5785. }
  5786. return exprList;
  5787. }
  5788. shouldParseArrow() {
  5789. return this.match(types.colon) || super.shouldParseArrow();
  5790. }
  5791. shouldParseAsyncArrow() {
  5792. return this.match(types.colon) || super.shouldParseAsyncArrow();
  5793. }
  5794. canHaveLeadingDecorator() {
  5795. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  5796. }
  5797. jsxParseOpeningElementAfterName(node) {
  5798. if (this.isRelational("<")) {
  5799. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  5800. if (typeArguments) node.typeParameters = typeArguments;
  5801. }
  5802. return super.jsxParseOpeningElementAfterName(node);
  5803. }
  5804. getGetterSetterExpectedParamCount(method) {
  5805. const baseCount = super.getGetterSetterExpectedParamCount(method);
  5806. const firstParam = method.params[0];
  5807. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  5808. return hasContextParam ? baseCount + 1 : baseCount;
  5809. }
  5810. });
  5811. types.placeholder = new TokenType("%%", {
  5812. startsExpr: true
  5813. });
  5814. var placeholders = (superClass => class extends superClass {
  5815. parsePlaceholder(expectedNode) {
  5816. if (this.match(types.placeholder)) {
  5817. const node = this.startNode();
  5818. this.next();
  5819. this.assertNoSpace("Unexpected space in placeholder.");
  5820. node.name = super.parseIdentifier(true);
  5821. this.assertNoSpace("Unexpected space in placeholder.");
  5822. this.expect(types.placeholder);
  5823. return this.finishPlaceholder(node, expectedNode);
  5824. }
  5825. }
  5826. finishPlaceholder(node, expectedNode) {
  5827. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  5828. node.expectedNode = expectedNode;
  5829. return isFinished ? node : this.finishNode(node, "Placeholder");
  5830. }
  5831. getTokenFromCode(code) {
  5832. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  5833. return this.finishOp(types.placeholder, 2);
  5834. }
  5835. return super.getTokenFromCode(...arguments);
  5836. }
  5837. parseExprAtom() {
  5838. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  5839. }
  5840. parseIdentifier() {
  5841. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  5842. }
  5843. checkReservedWord(word) {
  5844. if (word !== undefined) super.checkReservedWord(...arguments);
  5845. }
  5846. parseBindingAtom() {
  5847. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  5848. }
  5849. checkLVal(expr) {
  5850. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  5851. }
  5852. toAssignable(node) {
  5853. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  5854. node.expectedNode = "Pattern";
  5855. return node;
  5856. }
  5857. return super.toAssignable(...arguments);
  5858. }
  5859. verifyBreakContinue(node) {
  5860. if (node.label && node.label.type === "Placeholder") return;
  5861. super.verifyBreakContinue(...arguments);
  5862. }
  5863. parseExpressionStatement(node, expr) {
  5864. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  5865. return super.parseExpressionStatement(...arguments);
  5866. }
  5867. if (this.match(types.colon)) {
  5868. const stmt = node;
  5869. stmt.label = this.finishPlaceholder(expr, "Identifier");
  5870. this.next();
  5871. stmt.body = this.parseStatement("label");
  5872. return this.finishNode(stmt, "LabeledStatement");
  5873. }
  5874. this.semicolon();
  5875. node.name = expr.name;
  5876. return this.finishPlaceholder(node, "Statement");
  5877. }
  5878. parseBlock() {
  5879. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  5880. }
  5881. parseFunctionId() {
  5882. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  5883. }
  5884. parseClass(node, isStatement, optionalId) {
  5885. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  5886. this.next();
  5887. this.takeDecorators(node);
  5888. const placeholder = this.parsePlaceholder("Identifier");
  5889. if (placeholder) {
  5890. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  5891. node.id = placeholder;
  5892. } else if (optionalId || !isStatement) {
  5893. node.id = null;
  5894. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  5895. return this.finishNode(node, type);
  5896. } else {
  5897. this.unexpected(null, "A class name is required");
  5898. }
  5899. } else {
  5900. this.parseClassId(node, isStatement, optionalId);
  5901. }
  5902. this.parseClassSuper(node);
  5903. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass);
  5904. return this.finishNode(node, type);
  5905. }
  5906. parseExport(node) {
  5907. const placeholder = this.parsePlaceholder("Identifier");
  5908. if (!placeholder) return super.parseExport(...arguments);
  5909. if (!this.isContextual("from") && !this.match(types.comma)) {
  5910. node.specifiers = [];
  5911. node.source = null;
  5912. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  5913. return this.finishNode(node, "ExportNamedDeclaration");
  5914. }
  5915. this.expectPlugin("exportDefaultFrom");
  5916. const specifier = this.startNode();
  5917. specifier.exported = placeholder;
  5918. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  5919. return super.parseExport(node);
  5920. }
  5921. maybeParseExportDefaultSpecifier(node) {
  5922. if (node.specifiers && node.specifiers.length > 0) {
  5923. return true;
  5924. }
  5925. return super.maybeParseExportDefaultSpecifier(...arguments);
  5926. }
  5927. checkExport(node) {
  5928. const {
  5929. specifiers
  5930. } = node;
  5931. if (specifiers && specifiers.length) {
  5932. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  5933. }
  5934. super.checkExport(node);
  5935. node.specifiers = specifiers;
  5936. }
  5937. parseImport(node) {
  5938. const placeholder = this.parsePlaceholder("Identifier");
  5939. if (!placeholder) return super.parseImport(...arguments);
  5940. node.specifiers = [];
  5941. if (!this.isContextual("from") && !this.match(types.comma)) {
  5942. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  5943. this.semicolon();
  5944. return this.finishNode(node, "ImportDeclaration");
  5945. }
  5946. const specifier = this.startNodeAtNode(placeholder);
  5947. specifier.local = placeholder;
  5948. this.finishNode(specifier, "ImportDefaultSpecifier");
  5949. node.specifiers.push(specifier);
  5950. if (this.eat(types.comma)) {
  5951. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  5952. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  5953. }
  5954. this.expectContextual("from");
  5955. node.source = this.parseImportSource();
  5956. this.semicolon();
  5957. return this.finishNode(node, "ImportDeclaration");
  5958. }
  5959. parseImportSource() {
  5960. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  5961. }
  5962. });
  5963. var v8intrinsic = (superClass => class extends superClass {
  5964. parseV8Intrinsic() {
  5965. if (this.match(types.modulo)) {
  5966. const v8IntrinsicStart = this.state.start;
  5967. const node = this.startNode();
  5968. this.eat(types.modulo);
  5969. if (this.match(types.name)) {
  5970. const name = this.parseIdentifierName(this.state.start);
  5971. const identifier = this.createIdentifier(node, name);
  5972. identifier.type = "V8IntrinsicIdentifier";
  5973. if (this.match(types.parenL)) {
  5974. return identifier;
  5975. }
  5976. }
  5977. this.unexpected(v8IntrinsicStart);
  5978. }
  5979. }
  5980. parseExprAtom() {
  5981. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  5982. }
  5983. });
  5984. function hasPlugin(plugins, name) {
  5985. return plugins.some(plugin => {
  5986. if (Array.isArray(plugin)) {
  5987. return plugin[0] === name;
  5988. } else {
  5989. return plugin === name;
  5990. }
  5991. });
  5992. }
  5993. function getPluginOption(plugins, name, option) {
  5994. const plugin = plugins.find(plugin => {
  5995. if (Array.isArray(plugin)) {
  5996. return plugin[0] === name;
  5997. } else {
  5998. return plugin === name;
  5999. }
  6000. });
  6001. if (plugin && Array.isArray(plugin)) {
  6002. return plugin[1][option];
  6003. }
  6004. return null;
  6005. }
  6006. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6007. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6008. function validatePlugins(plugins) {
  6009. if (hasPlugin(plugins, "decorators")) {
  6010. if (hasPlugin(plugins, "decorators-legacy")) {
  6011. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6012. }
  6013. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6014. if (decoratorsBeforeExport == null) {
  6015. 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'.");
  6016. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6017. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6018. }
  6019. }
  6020. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6021. throw new Error("Cannot combine flow and typescript plugins.");
  6022. }
  6023. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6024. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6025. }
  6026. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6027. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6028. }
  6029. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6030. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6031. }
  6032. }
  6033. const mixinPlugins = {
  6034. estree,
  6035. jsx,
  6036. flow,
  6037. typescript,
  6038. v8intrinsic,
  6039. placeholders
  6040. };
  6041. const mixinPluginNames = Object.keys(mixinPlugins);
  6042. const defaultOptions = {
  6043. sourceType: "script",
  6044. sourceFilename: undefined,
  6045. startLine: 1,
  6046. allowAwaitOutsideFunction: false,
  6047. allowReturnOutsideFunction: false,
  6048. allowImportExportEverywhere: false,
  6049. allowSuperOutsideMethod: false,
  6050. allowUndeclaredExports: false,
  6051. plugins: [],
  6052. strictMode: null,
  6053. ranges: false,
  6054. tokens: false,
  6055. createParenthesizedExpressions: false,
  6056. errorRecovery: false
  6057. };
  6058. function getOptions(opts) {
  6059. const options = {};
  6060. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  6061. const key = _Object$keys[_i];
  6062. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6063. }
  6064. return options;
  6065. }
  6066. class State {
  6067. constructor() {
  6068. this.errors = [];
  6069. this.potentialArrowAt = -1;
  6070. this.noArrowAt = [];
  6071. this.noArrowParamsConversionAt = [];
  6072. this.inParameters = false;
  6073. this.maybeInArrowParameters = false;
  6074. this.maybeInAsyncArrowHead = false;
  6075. this.inPipeline = false;
  6076. this.inType = false;
  6077. this.noAnonFunctionType = false;
  6078. this.inPropertyName = false;
  6079. this.hasFlowComment = false;
  6080. this.isIterator = false;
  6081. this.topicContext = {
  6082. maxNumOfResolvableTopics: 0,
  6083. maxTopicIndex: null
  6084. };
  6085. this.soloAwait = false;
  6086. this.inFSharpPipelineDirectBody = false;
  6087. this.labels = [];
  6088. this.decoratorStack = [[]];
  6089. this.yieldPos = -1;
  6090. this.awaitPos = -1;
  6091. this.comments = [];
  6092. this.trailingComments = [];
  6093. this.leadingComments = [];
  6094. this.commentStack = [];
  6095. this.commentPreviousNode = null;
  6096. this.pos = 0;
  6097. this.lineStart = 0;
  6098. this.type = types.eof;
  6099. this.value = null;
  6100. this.start = 0;
  6101. this.end = 0;
  6102. this.lastTokEndLoc = null;
  6103. this.lastTokStartLoc = null;
  6104. this.lastTokStart = 0;
  6105. this.lastTokEnd = 0;
  6106. this.context = [types$1.braceStatement];
  6107. this.exprAllowed = true;
  6108. this.containsEsc = false;
  6109. this.octalPositions = [];
  6110. this.exportedIdentifiers = [];
  6111. this.tokensLength = 0;
  6112. }
  6113. init(options) {
  6114. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6115. this.curLine = options.startLine;
  6116. this.startLoc = this.endLoc = this.curPosition();
  6117. }
  6118. curPosition() {
  6119. return new Position(this.curLine, this.pos - this.lineStart);
  6120. }
  6121. clone(skipArrays) {
  6122. const state = new State();
  6123. const keys = Object.keys(this);
  6124. for (let i = 0, length = keys.length; i < length; i++) {
  6125. const key = keys[i];
  6126. let val = this[key];
  6127. if (!skipArrays && Array.isArray(val)) {
  6128. val = val.slice();
  6129. }
  6130. state[key] = val;
  6131. }
  6132. return state;
  6133. }
  6134. }
  6135. var _isDigit = function isDigit(code) {
  6136. return code >= 48 && code <= 57;
  6137. };
  6138. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6139. const forbiddenNumericSeparatorSiblings = {
  6140. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6141. hex: [46, 88, 95, 120]
  6142. };
  6143. const allowedNumericSeparatorSiblings = {};
  6144. allowedNumericSeparatorSiblings.bin = [48, 49];
  6145. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6146. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6147. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6148. class Token {
  6149. constructor(state) {
  6150. this.type = state.type;
  6151. this.value = state.value;
  6152. this.start = state.start;
  6153. this.end = state.end;
  6154. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  6155. }
  6156. }
  6157. class Tokenizer extends LocationParser {
  6158. constructor(options, input) {
  6159. super();
  6160. this.tokens = [];
  6161. this.state = new State();
  6162. this.state.init(options);
  6163. this.input = input;
  6164. this.length = input.length;
  6165. this.isLookahead = false;
  6166. }
  6167. pushToken(token) {
  6168. this.tokens.length = this.state.tokensLength;
  6169. this.tokens.push(token);
  6170. ++this.state.tokensLength;
  6171. }
  6172. next() {
  6173. if (!this.isLookahead) {
  6174. this.checkKeywordEscapes();
  6175. if (this.options.tokens) {
  6176. this.pushToken(new Token(this.state));
  6177. }
  6178. }
  6179. this.state.lastTokEnd = this.state.end;
  6180. this.state.lastTokStart = this.state.start;
  6181. this.state.lastTokEndLoc = this.state.endLoc;
  6182. this.state.lastTokStartLoc = this.state.startLoc;
  6183. this.nextToken();
  6184. }
  6185. eat(type) {
  6186. if (this.match(type)) {
  6187. this.next();
  6188. return true;
  6189. } else {
  6190. return false;
  6191. }
  6192. }
  6193. match(type) {
  6194. return this.state.type === type;
  6195. }
  6196. lookahead() {
  6197. const old = this.state;
  6198. this.state = old.clone(true);
  6199. this.isLookahead = true;
  6200. this.next();
  6201. this.isLookahead = false;
  6202. const curr = this.state;
  6203. this.state = old;
  6204. return curr;
  6205. }
  6206. nextTokenStart() {
  6207. const thisTokEnd = this.state.pos;
  6208. skipWhiteSpace.lastIndex = thisTokEnd;
  6209. const skip = skipWhiteSpace.exec(this.input);
  6210. return thisTokEnd + skip[0].length;
  6211. }
  6212. lookaheadCharCode() {
  6213. return this.input.charCodeAt(this.nextTokenStart());
  6214. }
  6215. setStrict(strict) {
  6216. this.state.strict = strict;
  6217. if (!this.match(types.num) && !this.match(types.string)) return;
  6218. this.state.pos = this.state.start;
  6219. while (this.state.pos < this.state.lineStart) {
  6220. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  6221. --this.state.curLine;
  6222. }
  6223. this.nextToken();
  6224. }
  6225. curContext() {
  6226. return this.state.context[this.state.context.length - 1];
  6227. }
  6228. nextToken() {
  6229. const curContext = this.curContext();
  6230. if (!curContext || !curContext.preserveSpace) this.skipSpace();
  6231. this.state.octalPositions = [];
  6232. this.state.start = this.state.pos;
  6233. this.state.startLoc = this.state.curPosition();
  6234. if (this.state.pos >= this.length) {
  6235. this.finishToken(types.eof);
  6236. return;
  6237. }
  6238. const override = curContext == null ? void 0 : curContext.override;
  6239. if (override) {
  6240. override(this);
  6241. } else {
  6242. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6243. }
  6244. }
  6245. pushComment(block, text, start, end, startLoc, endLoc) {
  6246. const comment = {
  6247. type: block ? "CommentBlock" : "CommentLine",
  6248. value: text,
  6249. start: start,
  6250. end: end,
  6251. loc: new SourceLocation(startLoc, endLoc)
  6252. };
  6253. if (this.options.tokens) this.pushToken(comment);
  6254. this.state.comments.push(comment);
  6255. this.addComment(comment);
  6256. }
  6257. skipBlockComment() {
  6258. const startLoc = this.state.curPosition();
  6259. const start = this.state.pos;
  6260. const end = this.input.indexOf("*/", this.state.pos + 2);
  6261. if (end === -1) throw this.raise(start, Errors.UnterminatedComment);
  6262. this.state.pos = end + 2;
  6263. lineBreakG.lastIndex = start;
  6264. let match;
  6265. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6266. ++this.state.curLine;
  6267. this.state.lineStart = match.index + match[0].length;
  6268. }
  6269. if (this.isLookahead) return;
  6270. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6271. }
  6272. skipLineComment(startSkip) {
  6273. const start = this.state.pos;
  6274. const startLoc = this.state.curPosition();
  6275. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6276. if (this.state.pos < this.length) {
  6277. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6278. ch = this.input.charCodeAt(this.state.pos);
  6279. }
  6280. }
  6281. if (this.isLookahead) return;
  6282. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6283. }
  6284. skipSpace() {
  6285. loop: while (this.state.pos < this.length) {
  6286. const ch = this.input.charCodeAt(this.state.pos);
  6287. switch (ch) {
  6288. case 32:
  6289. case 160:
  6290. case 9:
  6291. ++this.state.pos;
  6292. break;
  6293. case 13:
  6294. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6295. ++this.state.pos;
  6296. }
  6297. case 10:
  6298. case 8232:
  6299. case 8233:
  6300. ++this.state.pos;
  6301. ++this.state.curLine;
  6302. this.state.lineStart = this.state.pos;
  6303. break;
  6304. case 47:
  6305. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6306. case 42:
  6307. this.skipBlockComment();
  6308. break;
  6309. case 47:
  6310. this.skipLineComment(2);
  6311. break;
  6312. default:
  6313. break loop;
  6314. }
  6315. break;
  6316. default:
  6317. if (isWhitespace(ch)) {
  6318. ++this.state.pos;
  6319. } else {
  6320. break loop;
  6321. }
  6322. }
  6323. }
  6324. }
  6325. finishToken(type, val) {
  6326. this.state.end = this.state.pos;
  6327. this.state.endLoc = this.state.curPosition();
  6328. const prevType = this.state.type;
  6329. this.state.type = type;
  6330. this.state.value = val;
  6331. if (!this.isLookahead) this.updateContext(prevType);
  6332. }
  6333. readToken_numberSign() {
  6334. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6335. return;
  6336. }
  6337. const nextPos = this.state.pos + 1;
  6338. const next = this.input.charCodeAt(nextPos);
  6339. if (next >= 48 && next <= 57) {
  6340. throw this.raise(this.state.pos, Errors.UnexpectedDigitAfterHash);
  6341. }
  6342. if (this.hasPlugin("recordAndTuple") && (next === 123 || next === 91)) {
  6343. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6344. throw this.raise(this.state.pos, next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType);
  6345. }
  6346. if (next === 123) {
  6347. this.finishToken(types.braceHashL);
  6348. } else {
  6349. this.finishToken(types.bracketHashL);
  6350. }
  6351. this.state.pos += 2;
  6352. } else if (this.hasPlugin("classPrivateProperties") || this.hasPlugin("classPrivateMethods") || this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  6353. this.finishOp(types.hash, 1);
  6354. } else {
  6355. throw this.raise(this.state.pos, Errors.InvalidOrUnexpectedToken, "#");
  6356. }
  6357. }
  6358. readToken_dot() {
  6359. const next = this.input.charCodeAt(this.state.pos + 1);
  6360. if (next >= 48 && next <= 57) {
  6361. this.readNumber(true);
  6362. return;
  6363. }
  6364. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6365. this.state.pos += 3;
  6366. this.finishToken(types.ellipsis);
  6367. } else {
  6368. ++this.state.pos;
  6369. this.finishToken(types.dot);
  6370. }
  6371. }
  6372. readToken_slash() {
  6373. if (this.state.exprAllowed && !this.state.inType) {
  6374. ++this.state.pos;
  6375. this.readRegexp();
  6376. return;
  6377. }
  6378. const next = this.input.charCodeAt(this.state.pos + 1);
  6379. if (next === 61) {
  6380. this.finishOp(types.assign, 2);
  6381. } else {
  6382. this.finishOp(types.slash, 1);
  6383. }
  6384. }
  6385. readToken_interpreter() {
  6386. if (this.state.pos !== 0 || this.length < 2) return false;
  6387. let ch = this.input.charCodeAt(this.state.pos + 1);
  6388. if (ch !== 33) return false;
  6389. const start = this.state.pos;
  6390. this.state.pos += 1;
  6391. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6392. ch = this.input.charCodeAt(this.state.pos);
  6393. }
  6394. const value = this.input.slice(start + 2, this.state.pos);
  6395. this.finishToken(types.interpreterDirective, value);
  6396. return true;
  6397. }
  6398. readToken_mult_modulo(code) {
  6399. let type = code === 42 ? types.star : types.modulo;
  6400. let width = 1;
  6401. let next = this.input.charCodeAt(this.state.pos + 1);
  6402. const exprAllowed = this.state.exprAllowed;
  6403. if (code === 42 && next === 42) {
  6404. width++;
  6405. next = this.input.charCodeAt(this.state.pos + 2);
  6406. type = types.exponent;
  6407. }
  6408. if (next === 61 && !exprAllowed) {
  6409. width++;
  6410. type = types.assign;
  6411. }
  6412. this.finishOp(type, width);
  6413. }
  6414. readToken_pipe_amp(code) {
  6415. const next = this.input.charCodeAt(this.state.pos + 1);
  6416. if (next === code) {
  6417. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6418. this.finishOp(types.assign, 3);
  6419. } else {
  6420. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6421. }
  6422. return;
  6423. }
  6424. if (code === 124) {
  6425. if (next === 62) {
  6426. this.finishOp(types.pipeline, 2);
  6427. return;
  6428. }
  6429. if (this.hasPlugin("recordAndTuple") && next === 125) {
  6430. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6431. throw this.raise(this.state.pos, Errors.RecordExpressionBarIncorrectEndSyntaxType);
  6432. }
  6433. this.finishOp(types.braceBarR, 2);
  6434. return;
  6435. }
  6436. if (this.hasPlugin("recordAndTuple") && next === 93) {
  6437. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6438. throw this.raise(this.state.pos, Errors.TupleExpressionBarIncorrectEndSyntaxType);
  6439. }
  6440. this.finishOp(types.bracketBarR, 2);
  6441. return;
  6442. }
  6443. }
  6444. if (next === 61) {
  6445. this.finishOp(types.assign, 2);
  6446. return;
  6447. }
  6448. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6449. }
  6450. readToken_caret() {
  6451. const next = this.input.charCodeAt(this.state.pos + 1);
  6452. if (next === 61) {
  6453. this.finishOp(types.assign, 2);
  6454. } else {
  6455. this.finishOp(types.bitwiseXOR, 1);
  6456. }
  6457. }
  6458. readToken_plus_min(code) {
  6459. const next = this.input.charCodeAt(this.state.pos + 1);
  6460. if (next === code) {
  6461. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos)))) {
  6462. this.skipLineComment(3);
  6463. this.skipSpace();
  6464. this.nextToken();
  6465. return;
  6466. }
  6467. this.finishOp(types.incDec, 2);
  6468. return;
  6469. }
  6470. if (next === 61) {
  6471. this.finishOp(types.assign, 2);
  6472. } else {
  6473. this.finishOp(types.plusMin, 1);
  6474. }
  6475. }
  6476. readToken_lt_gt(code) {
  6477. const next = this.input.charCodeAt(this.state.pos + 1);
  6478. let size = 1;
  6479. if (next === code) {
  6480. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6481. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6482. this.finishOp(types.assign, size + 1);
  6483. return;
  6484. }
  6485. this.finishOp(types.bitShift, size);
  6486. return;
  6487. }
  6488. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6489. this.skipLineComment(4);
  6490. this.skipSpace();
  6491. this.nextToken();
  6492. return;
  6493. }
  6494. if (next === 61) {
  6495. size = 2;
  6496. }
  6497. this.finishOp(types.relational, size);
  6498. }
  6499. readToken_eq_excl(code) {
  6500. const next = this.input.charCodeAt(this.state.pos + 1);
  6501. if (next === 61) {
  6502. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6503. return;
  6504. }
  6505. if (code === 61 && next === 62) {
  6506. this.state.pos += 2;
  6507. this.finishToken(types.arrow);
  6508. return;
  6509. }
  6510. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6511. }
  6512. readToken_question() {
  6513. const next = this.input.charCodeAt(this.state.pos + 1);
  6514. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6515. if (next === 63 && !this.state.inType) {
  6516. if (next2 === 61) {
  6517. this.finishOp(types.assign, 3);
  6518. } else {
  6519. this.finishOp(types.nullishCoalescing, 2);
  6520. }
  6521. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6522. this.state.pos += 2;
  6523. this.finishToken(types.questionDot);
  6524. } else {
  6525. ++this.state.pos;
  6526. this.finishToken(types.question);
  6527. }
  6528. }
  6529. getTokenFromCode(code) {
  6530. switch (code) {
  6531. case 46:
  6532. this.readToken_dot();
  6533. return;
  6534. case 40:
  6535. ++this.state.pos;
  6536. this.finishToken(types.parenL);
  6537. return;
  6538. case 41:
  6539. ++this.state.pos;
  6540. this.finishToken(types.parenR);
  6541. return;
  6542. case 59:
  6543. ++this.state.pos;
  6544. this.finishToken(types.semi);
  6545. return;
  6546. case 44:
  6547. ++this.state.pos;
  6548. this.finishToken(types.comma);
  6549. return;
  6550. case 91:
  6551. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6552. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6553. throw this.raise(this.state.pos, Errors.TupleExpressionBarIncorrectStartSyntaxType);
  6554. }
  6555. this.finishToken(types.bracketBarL);
  6556. this.state.pos += 2;
  6557. } else {
  6558. ++this.state.pos;
  6559. this.finishToken(types.bracketL);
  6560. }
  6561. return;
  6562. case 93:
  6563. ++this.state.pos;
  6564. this.finishToken(types.bracketR);
  6565. return;
  6566. case 123:
  6567. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6568. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6569. throw this.raise(this.state.pos, Errors.RecordExpressionBarIncorrectStartSyntaxType);
  6570. }
  6571. this.finishToken(types.braceBarL);
  6572. this.state.pos += 2;
  6573. } else {
  6574. ++this.state.pos;
  6575. this.finishToken(types.braceL);
  6576. }
  6577. return;
  6578. case 125:
  6579. ++this.state.pos;
  6580. this.finishToken(types.braceR);
  6581. return;
  6582. case 58:
  6583. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6584. this.finishOp(types.doubleColon, 2);
  6585. } else {
  6586. ++this.state.pos;
  6587. this.finishToken(types.colon);
  6588. }
  6589. return;
  6590. case 63:
  6591. this.readToken_question();
  6592. return;
  6593. case 96:
  6594. ++this.state.pos;
  6595. this.finishToken(types.backQuote);
  6596. return;
  6597. case 48:
  6598. {
  6599. const next = this.input.charCodeAt(this.state.pos + 1);
  6600. if (next === 120 || next === 88) {
  6601. this.readRadixNumber(16);
  6602. return;
  6603. }
  6604. if (next === 111 || next === 79) {
  6605. this.readRadixNumber(8);
  6606. return;
  6607. }
  6608. if (next === 98 || next === 66) {
  6609. this.readRadixNumber(2);
  6610. return;
  6611. }
  6612. }
  6613. case 49:
  6614. case 50:
  6615. case 51:
  6616. case 52:
  6617. case 53:
  6618. case 54:
  6619. case 55:
  6620. case 56:
  6621. case 57:
  6622. this.readNumber(false);
  6623. return;
  6624. case 34:
  6625. case 39:
  6626. this.readString(code);
  6627. return;
  6628. case 47:
  6629. this.readToken_slash();
  6630. return;
  6631. case 37:
  6632. case 42:
  6633. this.readToken_mult_modulo(code);
  6634. return;
  6635. case 124:
  6636. case 38:
  6637. this.readToken_pipe_amp(code);
  6638. return;
  6639. case 94:
  6640. this.readToken_caret();
  6641. return;
  6642. case 43:
  6643. case 45:
  6644. this.readToken_plus_min(code);
  6645. return;
  6646. case 60:
  6647. case 62:
  6648. this.readToken_lt_gt(code);
  6649. return;
  6650. case 61:
  6651. case 33:
  6652. this.readToken_eq_excl(code);
  6653. return;
  6654. case 126:
  6655. this.finishOp(types.tilde, 1);
  6656. return;
  6657. case 64:
  6658. ++this.state.pos;
  6659. this.finishToken(types.at);
  6660. return;
  6661. case 35:
  6662. this.readToken_numberSign();
  6663. return;
  6664. case 92:
  6665. this.readWord();
  6666. return;
  6667. default:
  6668. if (isIdentifierStart(code)) {
  6669. this.readWord();
  6670. return;
  6671. }
  6672. }
  6673. throw this.raise(this.state.pos, Errors.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  6674. }
  6675. finishOp(type, size) {
  6676. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6677. this.state.pos += size;
  6678. this.finishToken(type, str);
  6679. }
  6680. readRegexp() {
  6681. const start = this.state.pos;
  6682. let escaped, inClass;
  6683. for (;;) {
  6684. if (this.state.pos >= this.length) {
  6685. throw this.raise(start, Errors.UnterminatedRegExp);
  6686. }
  6687. const ch = this.input.charAt(this.state.pos);
  6688. if (lineBreak.test(ch)) {
  6689. throw this.raise(start, Errors.UnterminatedRegExp);
  6690. }
  6691. if (escaped) {
  6692. escaped = false;
  6693. } else {
  6694. if (ch === "[") {
  6695. inClass = true;
  6696. } else if (ch === "]" && inClass) {
  6697. inClass = false;
  6698. } else if (ch === "/" && !inClass) {
  6699. break;
  6700. }
  6701. escaped = ch === "\\";
  6702. }
  6703. ++this.state.pos;
  6704. }
  6705. const content = this.input.slice(start, this.state.pos);
  6706. ++this.state.pos;
  6707. let mods = "";
  6708. while (this.state.pos < this.length) {
  6709. const char = this.input[this.state.pos];
  6710. const charCode = this.input.codePointAt(this.state.pos);
  6711. if (VALID_REGEX_FLAGS.has(char)) {
  6712. if (mods.indexOf(char) > -1) {
  6713. this.raise(this.state.pos + 1, Errors.DuplicateRegExpFlags);
  6714. }
  6715. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6716. this.raise(this.state.pos + 1, Errors.MalformedRegExpFlags);
  6717. } else {
  6718. break;
  6719. }
  6720. ++this.state.pos;
  6721. mods += char;
  6722. }
  6723. this.finishToken(types.regexp, {
  6724. pattern: content,
  6725. flags: mods
  6726. });
  6727. }
  6728. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6729. const start = this.state.pos;
  6730. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6731. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6732. let invalid = false;
  6733. let total = 0;
  6734. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  6735. const code = this.input.charCodeAt(this.state.pos);
  6736. let val;
  6737. if (this.hasPlugin("numericSeparator")) {
  6738. if (code === 95) {
  6739. const prev = this.input.charCodeAt(this.state.pos - 1);
  6740. const next = this.input.charCodeAt(this.state.pos + 1);
  6741. if (allowedSiblings.indexOf(next) === -1) {
  6742. this.raise(this.state.pos, Errors.UnexpectedNumericSeparator);
  6743. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  6744. this.raise(this.state.pos, Errors.UnexpectedNumericSeparator);
  6745. }
  6746. if (!allowNumSeparator) {
  6747. this.raise(this.state.pos, Errors.NumericSeparatorInEscapeSequence);
  6748. }
  6749. ++this.state.pos;
  6750. continue;
  6751. }
  6752. }
  6753. if (code >= 97) {
  6754. val = code - 97 + 10;
  6755. } else if (code >= 65) {
  6756. val = code - 65 + 10;
  6757. } else if (_isDigit(code)) {
  6758. val = code - 48;
  6759. } else {
  6760. val = Infinity;
  6761. }
  6762. if (val >= radix) {
  6763. if (this.options.errorRecovery && val <= 9) {
  6764. val = 0;
  6765. this.raise(this.state.start + i + 2, Errors.InvalidDigit, radix);
  6766. } else if (forceLen) {
  6767. val = 0;
  6768. invalid = true;
  6769. } else {
  6770. break;
  6771. }
  6772. }
  6773. ++this.state.pos;
  6774. total = total * radix + val;
  6775. }
  6776. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  6777. return null;
  6778. }
  6779. return total;
  6780. }
  6781. readRadixNumber(radix) {
  6782. const start = this.state.pos;
  6783. let isBigInt = false;
  6784. this.state.pos += 2;
  6785. const val = this.readInt(radix);
  6786. if (val == null) {
  6787. this.raise(this.state.start + 2, Errors.InvalidDigit, radix);
  6788. }
  6789. if (this.input.charCodeAt(this.state.pos) === 110) {
  6790. ++this.state.pos;
  6791. isBigInt = true;
  6792. }
  6793. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6794. throw this.raise(this.state.pos, Errors.NumberIdentifier);
  6795. }
  6796. if (isBigInt) {
  6797. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6798. this.finishToken(types.bigint, str);
  6799. return;
  6800. }
  6801. this.finishToken(types.num, val);
  6802. }
  6803. readNumber(startsWithDot) {
  6804. const start = this.state.pos;
  6805. let isFloat = false;
  6806. let isBigInt = false;
  6807. let isNonOctalDecimalInt = false;
  6808. if (!startsWithDot && this.readInt(10) === null) {
  6809. this.raise(start, Errors.InvalidNumber);
  6810. }
  6811. let octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  6812. if (octal) {
  6813. if (this.state.strict) {
  6814. this.raise(start, Errors.StrictOctalLiteral);
  6815. }
  6816. if (/[89]/.test(this.input.slice(start, this.state.pos))) {
  6817. octal = false;
  6818. isNonOctalDecimalInt = true;
  6819. }
  6820. }
  6821. let next = this.input.charCodeAt(this.state.pos);
  6822. if (next === 46 && !octal) {
  6823. ++this.state.pos;
  6824. this.readInt(10);
  6825. isFloat = true;
  6826. next = this.input.charCodeAt(this.state.pos);
  6827. }
  6828. if ((next === 69 || next === 101) && !octal) {
  6829. next = this.input.charCodeAt(++this.state.pos);
  6830. if (next === 43 || next === 45) {
  6831. ++this.state.pos;
  6832. }
  6833. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  6834. isFloat = true;
  6835. next = this.input.charCodeAt(this.state.pos);
  6836. }
  6837. if (this.hasPlugin("numericSeparator") && (octal || isNonOctalDecimalInt)) {
  6838. const underscorePos = this.input.slice(start, this.state.pos).indexOf("_");
  6839. if (underscorePos > 0) {
  6840. this.raise(underscorePos + start, Errors.ZeroDigitNumericSeparator);
  6841. }
  6842. }
  6843. if (next === 110) {
  6844. if (isFloat || octal || isNonOctalDecimalInt) {
  6845. this.raise(start, "Invalid BigIntLiteral");
  6846. }
  6847. ++this.state.pos;
  6848. isBigInt = true;
  6849. }
  6850. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6851. throw this.raise(this.state.pos, Errors.NumberIdentifier);
  6852. }
  6853. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6854. if (isBigInt) {
  6855. this.finishToken(types.bigint, str);
  6856. return;
  6857. }
  6858. const val = octal ? parseInt(str, 8) : parseFloat(str);
  6859. this.finishToken(types.num, val);
  6860. }
  6861. readCodePoint(throwOnInvalid) {
  6862. const ch = this.input.charCodeAt(this.state.pos);
  6863. let code;
  6864. if (ch === 123) {
  6865. const codePos = ++this.state.pos;
  6866. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  6867. ++this.state.pos;
  6868. if (code !== null && code > 0x10ffff) {
  6869. if (throwOnInvalid) {
  6870. this.raise(codePos, Errors.InvalidCodePoint);
  6871. } else {
  6872. return null;
  6873. }
  6874. }
  6875. } else {
  6876. code = this.readHexChar(4, false, throwOnInvalid);
  6877. }
  6878. return code;
  6879. }
  6880. readString(quote) {
  6881. let out = "",
  6882. chunkStart = ++this.state.pos;
  6883. for (;;) {
  6884. if (this.state.pos >= this.length) {
  6885. throw this.raise(this.state.start, Errors.UnterminatedString);
  6886. }
  6887. const ch = this.input.charCodeAt(this.state.pos);
  6888. if (ch === quote) break;
  6889. if (ch === 92) {
  6890. out += this.input.slice(chunkStart, this.state.pos);
  6891. out += this.readEscapedChar(false);
  6892. chunkStart = this.state.pos;
  6893. } else if (ch === 8232 || ch === 8233) {
  6894. ++this.state.pos;
  6895. ++this.state.curLine;
  6896. this.state.lineStart = this.state.pos;
  6897. } else if (isNewLine(ch)) {
  6898. throw this.raise(this.state.start, Errors.UnterminatedString);
  6899. } else {
  6900. ++this.state.pos;
  6901. }
  6902. }
  6903. out += this.input.slice(chunkStart, this.state.pos++);
  6904. this.finishToken(types.string, out);
  6905. }
  6906. readTmplToken() {
  6907. let out = "",
  6908. chunkStart = this.state.pos,
  6909. containsInvalid = false;
  6910. for (;;) {
  6911. if (this.state.pos >= this.length) {
  6912. throw this.raise(this.state.start, Errors.UnterminatedTemplate);
  6913. }
  6914. const ch = this.input.charCodeAt(this.state.pos);
  6915. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  6916. if (this.state.pos === this.state.start && this.match(types.template)) {
  6917. if (ch === 36) {
  6918. this.state.pos += 2;
  6919. this.finishToken(types.dollarBraceL);
  6920. return;
  6921. } else {
  6922. ++this.state.pos;
  6923. this.finishToken(types.backQuote);
  6924. return;
  6925. }
  6926. }
  6927. out += this.input.slice(chunkStart, this.state.pos);
  6928. this.finishToken(types.template, containsInvalid ? null : out);
  6929. return;
  6930. }
  6931. if (ch === 92) {
  6932. out += this.input.slice(chunkStart, this.state.pos);
  6933. const escaped = this.readEscapedChar(true);
  6934. if (escaped === null) {
  6935. containsInvalid = true;
  6936. } else {
  6937. out += escaped;
  6938. }
  6939. chunkStart = this.state.pos;
  6940. } else if (isNewLine(ch)) {
  6941. out += this.input.slice(chunkStart, this.state.pos);
  6942. ++this.state.pos;
  6943. switch (ch) {
  6944. case 13:
  6945. if (this.input.charCodeAt(this.state.pos) === 10) {
  6946. ++this.state.pos;
  6947. }
  6948. case 10:
  6949. out += "\n";
  6950. break;
  6951. default:
  6952. out += String.fromCharCode(ch);
  6953. break;
  6954. }
  6955. ++this.state.curLine;
  6956. this.state.lineStart = this.state.pos;
  6957. chunkStart = this.state.pos;
  6958. } else {
  6959. ++this.state.pos;
  6960. }
  6961. }
  6962. }
  6963. readEscapedChar(inTemplate) {
  6964. const throwOnInvalid = !inTemplate;
  6965. const ch = this.input.charCodeAt(++this.state.pos);
  6966. ++this.state.pos;
  6967. switch (ch) {
  6968. case 110:
  6969. return "\n";
  6970. case 114:
  6971. return "\r";
  6972. case 120:
  6973. {
  6974. const code = this.readHexChar(2, false, throwOnInvalid);
  6975. return code === null ? null : String.fromCharCode(code);
  6976. }
  6977. case 117:
  6978. {
  6979. const code = this.readCodePoint(throwOnInvalid);
  6980. return code === null ? null : String.fromCodePoint(code);
  6981. }
  6982. case 116:
  6983. return "\t";
  6984. case 98:
  6985. return "\b";
  6986. case 118:
  6987. return "\u000b";
  6988. case 102:
  6989. return "\f";
  6990. case 13:
  6991. if (this.input.charCodeAt(this.state.pos) === 10) {
  6992. ++this.state.pos;
  6993. }
  6994. case 10:
  6995. this.state.lineStart = this.state.pos;
  6996. ++this.state.curLine;
  6997. case 8232:
  6998. case 8233:
  6999. return "";
  7000. case 56:
  7001. case 57:
  7002. if (inTemplate) {
  7003. return null;
  7004. }
  7005. default:
  7006. if (ch >= 48 && ch <= 55) {
  7007. const codePos = this.state.pos - 1;
  7008. let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
  7009. let octal = parseInt(octalStr, 8);
  7010. if (octal > 255) {
  7011. octalStr = octalStr.slice(0, -1);
  7012. octal = parseInt(octalStr, 8);
  7013. }
  7014. this.state.pos += octalStr.length - 1;
  7015. const next = this.input.charCodeAt(this.state.pos);
  7016. if (octalStr !== "0" || next === 56 || next === 57) {
  7017. if (inTemplate) {
  7018. return null;
  7019. } else if (this.state.strict) {
  7020. this.raise(codePos, Errors.StrictOctalLiteral);
  7021. } else {
  7022. this.state.octalPositions.push(codePos);
  7023. }
  7024. }
  7025. return String.fromCharCode(octal);
  7026. }
  7027. return String.fromCharCode(ch);
  7028. }
  7029. }
  7030. readHexChar(len, forceLen, throwOnInvalid) {
  7031. const codePos = this.state.pos;
  7032. const n = this.readInt(16, len, forceLen, false);
  7033. if (n === null) {
  7034. if (throwOnInvalid) {
  7035. this.raise(codePos, Errors.InvalidEscapeSequence);
  7036. } else {
  7037. this.state.pos = codePos - 1;
  7038. }
  7039. }
  7040. return n;
  7041. }
  7042. readWord1() {
  7043. let word = "";
  7044. this.state.containsEsc = false;
  7045. const start = this.state.pos;
  7046. let chunkStart = this.state.pos;
  7047. while (this.state.pos < this.length) {
  7048. const ch = this.input.codePointAt(this.state.pos);
  7049. if (isIdentifierChar(ch)) {
  7050. this.state.pos += ch <= 0xffff ? 1 : 2;
  7051. } else if (this.state.isIterator && ch === 64) {
  7052. ++this.state.pos;
  7053. } else if (ch === 92) {
  7054. this.state.containsEsc = true;
  7055. word += this.input.slice(chunkStart, this.state.pos);
  7056. const escStart = this.state.pos;
  7057. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  7058. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  7059. this.raise(this.state.pos, Errors.MissingUnicodeEscape);
  7060. continue;
  7061. }
  7062. ++this.state.pos;
  7063. const esc = this.readCodePoint(true);
  7064. if (esc !== null) {
  7065. if (!identifierCheck(esc)) {
  7066. this.raise(escStart, Errors.EscapedCharNotAnIdentifier);
  7067. }
  7068. word += String.fromCodePoint(esc);
  7069. }
  7070. chunkStart = this.state.pos;
  7071. } else {
  7072. break;
  7073. }
  7074. }
  7075. return word + this.input.slice(chunkStart, this.state.pos);
  7076. }
  7077. isIterator(word) {
  7078. return word === "@@iterator" || word === "@@asyncIterator";
  7079. }
  7080. readWord() {
  7081. const word = this.readWord1();
  7082. const type = keywords.get(word) || types.name;
  7083. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  7084. this.raise(this.state.pos, Errors.InvalidIdentifier, word);
  7085. }
  7086. this.finishToken(type, word);
  7087. }
  7088. checkKeywordEscapes() {
  7089. const kw = this.state.type.keyword;
  7090. if (kw && this.state.containsEsc) {
  7091. this.raise(this.state.start, Errors.InvalidEscapedReservedWord, kw);
  7092. }
  7093. }
  7094. braceIsBlock(prevType) {
  7095. const parent = this.curContext();
  7096. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  7097. return true;
  7098. }
  7099. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  7100. return !parent.isExpr;
  7101. }
  7102. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  7103. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7104. }
  7105. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  7106. return true;
  7107. }
  7108. if (prevType === types.braceL) {
  7109. return parent === types$1.braceStatement;
  7110. }
  7111. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  7112. return false;
  7113. }
  7114. if (prevType === types.relational) {
  7115. return true;
  7116. }
  7117. return !this.state.exprAllowed;
  7118. }
  7119. updateContext(prevType) {
  7120. const type = this.state.type;
  7121. let update;
  7122. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  7123. this.state.exprAllowed = false;
  7124. } else if (update = type.updateContext) {
  7125. update.call(this, prevType);
  7126. } else {
  7127. this.state.exprAllowed = type.beforeExpr;
  7128. }
  7129. }
  7130. }
  7131. class UtilParser extends Tokenizer {
  7132. addExtra(node, key, val) {
  7133. if (!node) return;
  7134. const extra = node.extra = node.extra || {};
  7135. extra[key] = val;
  7136. }
  7137. isRelational(op) {
  7138. return this.match(types.relational) && this.state.value === op;
  7139. }
  7140. isLookaheadRelational(op) {
  7141. const next = this.nextTokenStart();
  7142. if (this.input.charAt(next) === op) {
  7143. if (next + 1 === this.input.length) {
  7144. return true;
  7145. }
  7146. const afterNext = this.input.charCodeAt(next + 1);
  7147. return afterNext !== op.charCodeAt(0) && afterNext !== 61;
  7148. }
  7149. return false;
  7150. }
  7151. expectRelational(op) {
  7152. if (this.isRelational(op)) {
  7153. this.next();
  7154. } else {
  7155. this.unexpected(null, types.relational);
  7156. }
  7157. }
  7158. isContextual(name) {
  7159. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  7160. }
  7161. isUnparsedContextual(nameStart, name) {
  7162. const nameEnd = nameStart + name.length;
  7163. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  7164. }
  7165. isLookaheadContextual(name) {
  7166. const next = this.nextTokenStart();
  7167. return this.isUnparsedContextual(next, name);
  7168. }
  7169. eatContextual(name) {
  7170. return this.isContextual(name) && this.eat(types.name);
  7171. }
  7172. expectContextual(name, message) {
  7173. if (!this.eatContextual(name)) this.unexpected(null, message);
  7174. }
  7175. canInsertSemicolon() {
  7176. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  7177. }
  7178. hasPrecedingLineBreak() {
  7179. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7180. }
  7181. isLineTerminator() {
  7182. return this.eat(types.semi) || this.canInsertSemicolon();
  7183. }
  7184. semicolon() {
  7185. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  7186. }
  7187. expect(type, pos) {
  7188. this.eat(type) || this.unexpected(pos, type);
  7189. }
  7190. assertNoSpace(message = "Unexpected space.") {
  7191. if (this.state.start > this.state.lastTokEnd) {
  7192. this.raise(this.state.lastTokEnd, message);
  7193. }
  7194. }
  7195. unexpected(pos, messageOrType = "Unexpected token") {
  7196. if (typeof messageOrType !== "string") {
  7197. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  7198. }
  7199. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  7200. }
  7201. expectPlugin(name, pos) {
  7202. if (!this.hasPlugin(name)) {
  7203. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7204. missingPlugin: [name]
  7205. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  7206. }
  7207. return true;
  7208. }
  7209. expectOnePlugin(names, pos) {
  7210. if (!names.some(n => this.hasPlugin(n))) {
  7211. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7212. missingPlugin: names
  7213. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  7214. }
  7215. }
  7216. checkYieldAwaitInDefaultParams() {
  7217. if (this.state.yieldPos !== -1 && (this.state.awaitPos === -1 || this.state.yieldPos < this.state.awaitPos)) {
  7218. this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function");
  7219. }
  7220. if (this.state.awaitPos !== -1) {
  7221. this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function");
  7222. }
  7223. }
  7224. tryParse(fn, oldState = this.state.clone()) {
  7225. const abortSignal = {
  7226. node: null
  7227. };
  7228. try {
  7229. const node = fn((node = null) => {
  7230. abortSignal.node = node;
  7231. throw abortSignal;
  7232. });
  7233. if (this.state.errors.length > oldState.errors.length) {
  7234. const failState = this.state;
  7235. this.state = oldState;
  7236. return {
  7237. node,
  7238. error: failState.errors[oldState.errors.length],
  7239. thrown: false,
  7240. aborted: false,
  7241. failState
  7242. };
  7243. }
  7244. return {
  7245. node,
  7246. error: null,
  7247. thrown: false,
  7248. aborted: false,
  7249. failState: null
  7250. };
  7251. } catch (error) {
  7252. const failState = this.state;
  7253. this.state = oldState;
  7254. if (error instanceof SyntaxError) {
  7255. return {
  7256. node: null,
  7257. error,
  7258. thrown: true,
  7259. aborted: false,
  7260. failState
  7261. };
  7262. }
  7263. if (error === abortSignal) {
  7264. return {
  7265. node: abortSignal.node,
  7266. error: null,
  7267. thrown: false,
  7268. aborted: true,
  7269. failState
  7270. };
  7271. }
  7272. throw error;
  7273. }
  7274. }
  7275. checkExpressionErrors(refExpressionErrors, andThrow) {
  7276. if (!refExpressionErrors) return false;
  7277. const {
  7278. shorthandAssign,
  7279. doubleProto
  7280. } = refExpressionErrors;
  7281. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  7282. if (shorthandAssign >= 0) {
  7283. this.unexpected(shorthandAssign);
  7284. }
  7285. if (doubleProto >= 0) {
  7286. this.raise(doubleProto, Errors.DuplicateProto);
  7287. }
  7288. }
  7289. }
  7290. class ExpressionErrors {
  7291. constructor() {
  7292. this.shorthandAssign = -1;
  7293. this.doubleProto = -1;
  7294. }
  7295. }
  7296. class Node {
  7297. constructor(parser, pos, loc) {
  7298. this.type = "";
  7299. this.start = pos;
  7300. this.end = 0;
  7301. this.loc = new SourceLocation(loc);
  7302. if (parser && parser.options.ranges) this.range = [pos, 0];
  7303. if (parser && parser.filename) this.loc.filename = parser.filename;
  7304. }
  7305. __clone() {
  7306. const newNode = new Node();
  7307. const keys = Object.keys(this);
  7308. for (let i = 0, length = keys.length; i < length; i++) {
  7309. const key = keys[i];
  7310. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  7311. newNode[key] = this[key];
  7312. }
  7313. }
  7314. return newNode;
  7315. }
  7316. }
  7317. class NodeUtils extends UtilParser {
  7318. startNode() {
  7319. return new Node(this, this.state.start, this.state.startLoc);
  7320. }
  7321. startNodeAt(pos, loc) {
  7322. return new Node(this, pos, loc);
  7323. }
  7324. startNodeAtNode(type) {
  7325. return this.startNodeAt(type.start, type.loc.start);
  7326. }
  7327. finishNode(node, type) {
  7328. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  7329. }
  7330. finishNodeAt(node, type, pos, loc) {
  7331. node.type = type;
  7332. node.end = pos;
  7333. node.loc.end = loc;
  7334. if (this.options.ranges) node.range[1] = pos;
  7335. this.processComment(node);
  7336. return node;
  7337. }
  7338. resetStartLocation(node, start, startLoc) {
  7339. node.start = start;
  7340. node.loc.start = startLoc;
  7341. if (this.options.ranges) node.range[0] = start;
  7342. }
  7343. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  7344. node.end = end;
  7345. node.loc.end = endLoc;
  7346. if (this.options.ranges) node.range[1] = end;
  7347. }
  7348. resetStartLocationFromNode(node, locationNode) {
  7349. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  7350. }
  7351. }
  7352. const unwrapParenthesizedExpression = node => {
  7353. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7354. };
  7355. class LValParser extends NodeUtils {
  7356. toAssignable(node) {
  7357. var _node$extra, _node$extra3;
  7358. let parenthesized = undefined;
  7359. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  7360. parenthesized = unwrapParenthesizedExpression(node);
  7361. if (parenthesized.type !== "Identifier" && parenthesized.type !== "MemberExpression") {
  7362. this.raise(node.start, Errors.InvalidParenthesizedAssignment);
  7363. }
  7364. }
  7365. switch (node.type) {
  7366. case "Identifier":
  7367. case "ObjectPattern":
  7368. case "ArrayPattern":
  7369. case "AssignmentPattern":
  7370. break;
  7371. case "ObjectExpression":
  7372. node.type = "ObjectPattern";
  7373. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7374. var _node$extra2;
  7375. const prop = node.properties[i];
  7376. const isLast = i === last;
  7377. this.toAssignableObjectExpressionProp(prop, isLast);
  7378. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  7379. this.raiseRestNotLast(node.extra.trailingComma);
  7380. }
  7381. }
  7382. break;
  7383. case "ObjectProperty":
  7384. this.toAssignable(node.value);
  7385. break;
  7386. case "SpreadElement":
  7387. {
  7388. this.checkToRestConversion(node);
  7389. node.type = "RestElement";
  7390. const arg = node.argument;
  7391. this.toAssignable(arg);
  7392. break;
  7393. }
  7394. case "ArrayExpression":
  7395. node.type = "ArrayPattern";
  7396. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma);
  7397. break;
  7398. case "AssignmentExpression":
  7399. if (node.operator !== "=") {
  7400. this.raise(node.left.end, Errors.MissingEqInAssignment);
  7401. }
  7402. node.type = "AssignmentPattern";
  7403. delete node.operator;
  7404. this.toAssignable(node.left);
  7405. break;
  7406. case "ParenthesizedExpression":
  7407. this.toAssignable(parenthesized);
  7408. break;
  7409. }
  7410. return node;
  7411. }
  7412. toAssignableObjectExpressionProp(prop, isLast) {
  7413. if (prop.type === "ObjectMethod") {
  7414. const error = prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod;
  7415. this.raise(prop.key.start, error);
  7416. } else if (prop.type === "SpreadElement" && !isLast) {
  7417. this.raiseRestNotLast(prop.start);
  7418. } else {
  7419. this.toAssignable(prop);
  7420. }
  7421. }
  7422. toAssignableList(exprList, trailingCommaPos) {
  7423. let end = exprList.length;
  7424. if (end) {
  7425. const last = exprList[end - 1];
  7426. if (last && last.type === "RestElement") {
  7427. --end;
  7428. } else if (last && last.type === "SpreadElement") {
  7429. last.type = "RestElement";
  7430. const arg = last.argument;
  7431. this.toAssignable(arg);
  7432. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7433. this.unexpected(arg.start);
  7434. }
  7435. if (trailingCommaPos) {
  7436. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7437. }
  7438. --end;
  7439. }
  7440. }
  7441. for (let i = 0; i < end; i++) {
  7442. const elt = exprList[i];
  7443. if (elt) {
  7444. this.toAssignable(elt);
  7445. if (elt.type === "RestElement") {
  7446. this.raiseRestNotLast(elt.start);
  7447. }
  7448. }
  7449. }
  7450. return exprList;
  7451. }
  7452. toReferencedList(exprList, isParenthesizedExpr) {
  7453. return exprList;
  7454. }
  7455. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7456. this.toReferencedList(exprList, isParenthesizedExpr);
  7457. for (let _i = 0; _i < exprList.length; _i++) {
  7458. const expr = exprList[_i];
  7459. if (expr && expr.type === "ArrayExpression") {
  7460. this.toReferencedListDeep(expr.elements);
  7461. }
  7462. }
  7463. }
  7464. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  7465. const node = this.startNode();
  7466. this.next();
  7467. node.argument = this.parseMaybeAssign(false, refExpressionErrors, undefined, refNeedsArrowPos);
  7468. return this.finishNode(node, "SpreadElement");
  7469. }
  7470. parseRestBinding() {
  7471. const node = this.startNode();
  7472. this.next();
  7473. node.argument = this.parseBindingAtom();
  7474. return this.finishNode(node, "RestElement");
  7475. }
  7476. parseBindingAtom() {
  7477. switch (this.state.type) {
  7478. case types.bracketL:
  7479. {
  7480. const node = this.startNode();
  7481. this.next();
  7482. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7483. return this.finishNode(node, "ArrayPattern");
  7484. }
  7485. case types.braceL:
  7486. return this.parseObj(types.braceR, true);
  7487. }
  7488. return this.parseIdentifier();
  7489. }
  7490. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7491. const elts = [];
  7492. let first = true;
  7493. while (!this.eat(close)) {
  7494. if (first) {
  7495. first = false;
  7496. } else {
  7497. this.expect(types.comma);
  7498. }
  7499. if (allowEmpty && this.match(types.comma)) {
  7500. elts.push(null);
  7501. } else if (this.eat(close)) {
  7502. break;
  7503. } else if (this.match(types.ellipsis)) {
  7504. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7505. this.checkCommaAfterRest(closeCharCode);
  7506. this.expect(close);
  7507. break;
  7508. } else {
  7509. const decorators = [];
  7510. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7511. this.raise(this.state.start, Errors.UnsupportedParameterDecorator);
  7512. }
  7513. while (this.match(types.at)) {
  7514. decorators.push(this.parseDecorator());
  7515. }
  7516. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7517. }
  7518. }
  7519. return elts;
  7520. }
  7521. parseAssignableListItem(allowModifiers, decorators) {
  7522. const left = this.parseMaybeDefault();
  7523. this.parseAssignableListItemTypes(left);
  7524. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7525. if (decorators.length) {
  7526. left.decorators = decorators;
  7527. }
  7528. return elt;
  7529. }
  7530. parseAssignableListItemTypes(param) {
  7531. return param;
  7532. }
  7533. parseMaybeDefault(startPos, startLoc, left) {
  7534. startLoc = startLoc || this.state.startLoc;
  7535. startPos = startPos || this.state.start;
  7536. left = left || this.parseBindingAtom();
  7537. if (!this.eat(types.eq)) return left;
  7538. const node = this.startNodeAt(startPos, startLoc);
  7539. node.left = left;
  7540. node.right = this.parseMaybeAssign();
  7541. return this.finishNode(node, "AssignmentPattern");
  7542. }
  7543. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding, strictModeChanged = false) {
  7544. switch (expr.type) {
  7545. case "Identifier":
  7546. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) {
  7547. this.raise(expr.start, bindingType === BIND_NONE ? Errors.StrictEvalArguments : Errors.StrictEvalArgumentsBinding, expr.name);
  7548. }
  7549. if (checkClashes) {
  7550. const key = `_${expr.name}`;
  7551. if (checkClashes[key]) {
  7552. this.raise(expr.start, Errors.ParamDupe);
  7553. } else {
  7554. checkClashes[key] = true;
  7555. }
  7556. }
  7557. if (disallowLetBinding && expr.name === "let") {
  7558. this.raise(expr.start, Errors.LetInLexicalBinding);
  7559. }
  7560. if (!(bindingType & BIND_NONE)) {
  7561. this.scope.declareName(expr.name, bindingType, expr.start);
  7562. }
  7563. break;
  7564. case "MemberExpression":
  7565. if (bindingType !== BIND_NONE) {
  7566. this.raise(expr.start, Errors.InvalidPropertyBindingPattern);
  7567. }
  7568. break;
  7569. case "ObjectPattern":
  7570. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7571. let prop = _expr$properties[_i2];
  7572. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  7573. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  7574. }
  7575. break;
  7576. case "ArrayPattern":
  7577. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7578. const elem = _expr$elements[_i3];
  7579. if (elem) {
  7580. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding);
  7581. }
  7582. }
  7583. break;
  7584. case "AssignmentPattern":
  7585. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  7586. break;
  7587. case "RestElement":
  7588. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  7589. break;
  7590. case "ParenthesizedExpression":
  7591. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  7592. break;
  7593. default:
  7594. {
  7595. this.raise(expr.start, bindingType === BIND_NONE ? Errors.InvalidLhs : Errors.InvalidLhsBinding, contextDescription);
  7596. }
  7597. }
  7598. }
  7599. checkToRestConversion(node) {
  7600. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7601. this.raise(node.argument.start, Errors.InvalidRestAssignmentPattern);
  7602. }
  7603. }
  7604. checkCommaAfterRest(close) {
  7605. if (this.match(types.comma)) {
  7606. if (this.lookaheadCharCode() === close) {
  7607. this.raiseTrailingCommaAfterRest(this.state.start);
  7608. } else {
  7609. this.raiseRestNotLast(this.state.start);
  7610. }
  7611. }
  7612. }
  7613. raiseRestNotLast(pos) {
  7614. throw this.raise(pos, Errors.ElementAfterRest);
  7615. }
  7616. raiseTrailingCommaAfterRest(pos) {
  7617. this.raise(pos, Errors.RestTrailingComma);
  7618. }
  7619. }
  7620. class ExpressionParser extends LValParser {
  7621. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  7622. if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) {
  7623. return;
  7624. }
  7625. const key = prop.key;
  7626. const name = key.type === "Identifier" ? key.name : String(key.value);
  7627. if (name === "__proto__") {
  7628. if (protoRef.used) {
  7629. if (refExpressionErrors) {
  7630. if (refExpressionErrors.doubleProto === -1) {
  7631. refExpressionErrors.doubleProto = key.start;
  7632. }
  7633. } else {
  7634. this.raise(key.start, Errors.DuplicateProto);
  7635. }
  7636. }
  7637. protoRef.used = true;
  7638. }
  7639. }
  7640. getExpression() {
  7641. let paramFlags = PARAM;
  7642. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  7643. paramFlags |= PARAM_AWAIT;
  7644. }
  7645. this.scope.enter(SCOPE_PROGRAM);
  7646. this.prodParam.enter(paramFlags);
  7647. this.nextToken();
  7648. const expr = this.parseExpression();
  7649. if (!this.match(types.eof)) {
  7650. this.unexpected();
  7651. }
  7652. expr.comments = this.state.comments;
  7653. expr.errors = this.state.errors;
  7654. return expr;
  7655. }
  7656. parseExpression(noIn, refExpressionErrors) {
  7657. const startPos = this.state.start;
  7658. const startLoc = this.state.startLoc;
  7659. const expr = this.parseMaybeAssign(noIn, refExpressionErrors);
  7660. if (this.match(types.comma)) {
  7661. const node = this.startNodeAt(startPos, startLoc);
  7662. node.expressions = [expr];
  7663. while (this.eat(types.comma)) {
  7664. node.expressions.push(this.parseMaybeAssign(noIn, refExpressionErrors));
  7665. }
  7666. this.toReferencedList(node.expressions);
  7667. return this.finishNode(node, "SequenceExpression");
  7668. }
  7669. return expr;
  7670. }
  7671. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  7672. const startPos = this.state.start;
  7673. const startLoc = this.state.startLoc;
  7674. if (this.isContextual("yield")) {
  7675. if (this.prodParam.hasYield) {
  7676. let left = this.parseYield(noIn);
  7677. if (afterLeftParse) {
  7678. left = afterLeftParse.call(this, left, startPos, startLoc);
  7679. }
  7680. return left;
  7681. } else {
  7682. this.state.exprAllowed = false;
  7683. }
  7684. }
  7685. let ownExpressionErrors;
  7686. if (refExpressionErrors) {
  7687. ownExpressionErrors = false;
  7688. } else {
  7689. refExpressionErrors = new ExpressionErrors();
  7690. ownExpressionErrors = true;
  7691. }
  7692. if (this.match(types.parenL) || this.match(types.name)) {
  7693. this.state.potentialArrowAt = this.state.start;
  7694. }
  7695. let left = this.parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos);
  7696. if (afterLeftParse) {
  7697. left = afterLeftParse.call(this, left, startPos, startLoc);
  7698. }
  7699. if (this.state.type.isAssign) {
  7700. const node = this.startNodeAt(startPos, startLoc);
  7701. const operator = this.state.value;
  7702. node.operator = operator;
  7703. if (operator === "??=") {
  7704. this.expectPlugin("logicalAssignment");
  7705. }
  7706. if (operator === "||=" || operator === "&&=") {
  7707. this.expectPlugin("logicalAssignment");
  7708. }
  7709. if (this.match(types.eq)) {
  7710. node.left = this.toAssignable(left);
  7711. refExpressionErrors.doubleProto = -1;
  7712. } else {
  7713. node.left = left;
  7714. }
  7715. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  7716. refExpressionErrors.shorthandAssign = -1;
  7717. }
  7718. this.checkLVal(left, undefined, undefined, "assignment expression");
  7719. this.next();
  7720. node.right = this.parseMaybeAssign(noIn);
  7721. return this.finishNode(node, "AssignmentExpression");
  7722. } else if (ownExpressionErrors) {
  7723. this.checkExpressionErrors(refExpressionErrors, true);
  7724. }
  7725. return left;
  7726. }
  7727. parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos) {
  7728. const startPos = this.state.start;
  7729. const startLoc = this.state.startLoc;
  7730. const potentialArrowAt = this.state.potentialArrowAt;
  7731. const expr = this.parseExprOps(noIn, refExpressionErrors);
  7732. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7733. return expr;
  7734. }
  7735. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7736. return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  7737. }
  7738. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  7739. if (this.eat(types.question)) {
  7740. const node = this.startNodeAt(startPos, startLoc);
  7741. node.test = expr;
  7742. node.consequent = this.parseMaybeAssign();
  7743. this.expect(types.colon);
  7744. node.alternate = this.parseMaybeAssign(noIn);
  7745. return this.finishNode(node, "ConditionalExpression");
  7746. }
  7747. return expr;
  7748. }
  7749. parseExprOps(noIn, refExpressionErrors) {
  7750. const startPos = this.state.start;
  7751. const startLoc = this.state.startLoc;
  7752. const potentialArrowAt = this.state.potentialArrowAt;
  7753. const expr = this.parseMaybeUnary(refExpressionErrors);
  7754. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7755. return expr;
  7756. }
  7757. if (this.checkExpressionErrors(refExpressionErrors, false)) {
  7758. return expr;
  7759. }
  7760. return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  7761. }
  7762. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  7763. let prec = this.state.type.binop;
  7764. if (prec != null && (!noIn || !this.match(types._in))) {
  7765. if (prec > minPrec) {
  7766. const operator = this.state.value;
  7767. if (operator === "|>" && this.state.inFSharpPipelineDirectBody) {
  7768. return left;
  7769. }
  7770. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  7771. node.left = left;
  7772. node.operator = operator;
  7773. if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  7774. this.raise(left.argument.start, Errors.UnexpectedTokenUnaryExponentiation);
  7775. }
  7776. const op = this.state.type;
  7777. const logical = op === types.logicalOR || op === types.logicalAND;
  7778. const coalesce = op === types.nullishCoalescing;
  7779. if (op === types.pipeline) {
  7780. this.expectPlugin("pipelineOperator");
  7781. this.state.inPipeline = true;
  7782. this.checkPipelineAtInfixOperator(left, leftStartPos);
  7783. } else if (coalesce) {
  7784. prec = types.logicalAND.binop;
  7785. }
  7786. this.next();
  7787. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  7788. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  7789. throw this.raise(this.state.start, Errors.UnexpectedAwaitAfterPipelineBody);
  7790. }
  7791. }
  7792. node.right = this.parseExprOpRightExpr(op, prec, noIn);
  7793. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  7794. const nextOp = this.state.type;
  7795. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  7796. throw this.raise(this.state.start, Errors.MixingCoalesceWithLogical);
  7797. }
  7798. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  7799. }
  7800. }
  7801. return left;
  7802. }
  7803. parseExprOpRightExpr(op, prec, noIn) {
  7804. const startPos = this.state.start;
  7805. const startLoc = this.state.startLoc;
  7806. switch (op) {
  7807. case types.pipeline:
  7808. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  7809. case "smart":
  7810. return this.withTopicPermittingContext(() => {
  7811. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc);
  7812. });
  7813. case "fsharp":
  7814. return this.withSoloAwaitPermittingContext(() => {
  7815. return this.parseFSharpPipelineBody(prec, noIn);
  7816. });
  7817. }
  7818. default:
  7819. return this.parseExprOpBaseRightExpr(op, prec, noIn);
  7820. }
  7821. }
  7822. parseExprOpBaseRightExpr(op, prec, noIn) {
  7823. const startPos = this.state.start;
  7824. const startLoc = this.state.startLoc;
  7825. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
  7826. }
  7827. parseMaybeUnary(refExpressionErrors) {
  7828. if (this.isContextual("await") && this.isAwaitAllowed()) {
  7829. return this.parseAwait();
  7830. } else if (this.state.type.prefix) {
  7831. const node = this.startNode();
  7832. const update = this.match(types.incDec);
  7833. node.operator = this.state.value;
  7834. node.prefix = true;
  7835. if (node.operator === "throw") {
  7836. this.expectPlugin("throwExpressions");
  7837. }
  7838. this.next();
  7839. node.argument = this.parseMaybeUnary();
  7840. this.checkExpressionErrors(refExpressionErrors, true);
  7841. if (update) {
  7842. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  7843. } else if (this.state.strict && node.operator === "delete") {
  7844. const arg = node.argument;
  7845. if (arg.type === "Identifier") {
  7846. this.raise(node.start, Errors.StrictDelete);
  7847. } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") {
  7848. this.raise(node.start, Errors.DeletePrivateField);
  7849. }
  7850. }
  7851. return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  7852. }
  7853. const startPos = this.state.start;
  7854. const startLoc = this.state.startLoc;
  7855. let expr = this.parseExprSubscripts(refExpressionErrors);
  7856. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7857. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  7858. const node = this.startNodeAt(startPos, startLoc);
  7859. node.operator = this.state.value;
  7860. node.prefix = false;
  7861. node.argument = expr;
  7862. this.checkLVal(expr, undefined, undefined, "postfix operation");
  7863. this.next();
  7864. expr = this.finishNode(node, "UpdateExpression");
  7865. }
  7866. return expr;
  7867. }
  7868. parseExprSubscripts(refExpressionErrors) {
  7869. const startPos = this.state.start;
  7870. const startLoc = this.state.startLoc;
  7871. const potentialArrowAt = this.state.potentialArrowAt;
  7872. const expr = this.parseExprAtom(refExpressionErrors);
  7873. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7874. return expr;
  7875. }
  7876. return this.parseSubscripts(expr, startPos, startLoc);
  7877. }
  7878. parseSubscripts(base, startPos, startLoc, noCalls) {
  7879. const state = {
  7880. optionalChainMember: false,
  7881. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  7882. stop: false
  7883. };
  7884. do {
  7885. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  7886. if (state.maybeAsyncArrow) {
  7887. this.state.maybeInAsyncArrowHead = true;
  7888. }
  7889. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  7890. state.maybeAsyncArrow = false;
  7891. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  7892. } while (!state.stop);
  7893. return base;
  7894. }
  7895. parseSubscript(base, startPos, startLoc, noCalls, state) {
  7896. if (!noCalls && this.eat(types.doubleColon)) {
  7897. const node = this.startNodeAt(startPos, startLoc);
  7898. node.object = base;
  7899. node.callee = this.parseNoCallExpr();
  7900. state.stop = true;
  7901. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  7902. }
  7903. let optional = false;
  7904. if (this.match(types.questionDot)) {
  7905. state.optionalChainMember = optional = true;
  7906. if (noCalls && this.lookaheadCharCode() === 40) {
  7907. state.stop = true;
  7908. return base;
  7909. }
  7910. this.next();
  7911. }
  7912. const computed = this.eat(types.bracketL);
  7913. if (optional && !this.match(types.parenL) && !this.match(types.backQuote) || computed || this.eat(types.dot)) {
  7914. const node = this.startNodeAt(startPos, startLoc);
  7915. node.object = base;
  7916. node.property = computed ? this.parseExpression() : optional ? this.parseIdentifier(true) : this.parseMaybePrivateName(true);
  7917. node.computed = computed;
  7918. if (node.property.type === "PrivateName") {
  7919. if (node.object.type === "Super") {
  7920. this.raise(startPos, Errors.SuperPrivateField);
  7921. }
  7922. this.classScope.usePrivateName(node.property.id.name, node.property.start);
  7923. }
  7924. if (computed) {
  7925. this.expect(types.bracketR);
  7926. }
  7927. if (state.optionalChainMember) {
  7928. node.optional = optional;
  7929. return this.finishNode(node, "OptionalMemberExpression");
  7930. } else {
  7931. return this.finishNode(node, "MemberExpression");
  7932. }
  7933. } else if (!noCalls && this.match(types.parenL)) {
  7934. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7935. const oldYieldPos = this.state.yieldPos;
  7936. const oldAwaitPos = this.state.awaitPos;
  7937. this.state.maybeInArrowParameters = true;
  7938. this.state.yieldPos = -1;
  7939. this.state.awaitPos = -1;
  7940. this.next();
  7941. let node = this.startNodeAt(startPos, startLoc);
  7942. node.callee = base;
  7943. if (optional) {
  7944. node.optional = true;
  7945. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  7946. } else {
  7947. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  7948. }
  7949. this.finishCallExpression(node, state.optionalChainMember);
  7950. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  7951. state.stop = true;
  7952. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  7953. this.checkYieldAwaitInDefaultParams();
  7954. this.state.yieldPos = oldYieldPos;
  7955. this.state.awaitPos = oldAwaitPos;
  7956. } else {
  7957. this.toReferencedListDeep(node.arguments);
  7958. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  7959. if (!this.isAwaitAllowed() && !oldMaybeInArrowParameters || oldAwaitPos !== -1) {
  7960. this.state.awaitPos = oldAwaitPos;
  7961. }
  7962. }
  7963. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7964. return node;
  7965. } else if (this.match(types.backQuote)) {
  7966. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state);
  7967. } else {
  7968. state.stop = true;
  7969. return base;
  7970. }
  7971. }
  7972. parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) {
  7973. const node = this.startNodeAt(startPos, startLoc);
  7974. node.tag = base;
  7975. node.quasi = this.parseTemplate(true);
  7976. if (typeArguments) node.typeParameters = typeArguments;
  7977. if (state.optionalChainMember) {
  7978. this.raise(startPos, Errors.OptionalChainingNoTemplate);
  7979. }
  7980. return this.finishNode(node, "TaggedTemplateExpression");
  7981. }
  7982. atPossibleAsyncArrow(base) {
  7983. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  7984. }
  7985. finishCallExpression(node, optional) {
  7986. if (node.callee.type === "Import") {
  7987. if (node.arguments.length !== 1) {
  7988. this.raise(node.start, Errors.ImportCallArity);
  7989. } else {
  7990. const importArg = node.arguments[0];
  7991. if (importArg && importArg.type === "SpreadElement") {
  7992. this.raise(importArg.start, Errors.ImportCallSpreadArgument);
  7993. }
  7994. }
  7995. }
  7996. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  7997. }
  7998. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  7999. const elts = [];
  8000. let innerParenStart;
  8001. let first = true;
  8002. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8003. this.state.inFSharpPipelineDirectBody = false;
  8004. while (!this.eat(close)) {
  8005. if (first) {
  8006. first = false;
  8007. } else {
  8008. this.expect(types.comma);
  8009. if (this.match(close)) {
  8010. if (dynamicImport) {
  8011. this.raise(this.state.lastTokStart, Errors.ImportCallArgumentTrailingComma);
  8012. }
  8013. if (nodeForExtra) {
  8014. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8015. }
  8016. this.next();
  8017. break;
  8018. }
  8019. }
  8020. if (this.match(types.parenL) && !innerParenStart) {
  8021. innerParenStart = this.state.start;
  8022. }
  8023. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8024. start: 0
  8025. } : undefined, allowPlaceholder));
  8026. }
  8027. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  8028. this.unexpected();
  8029. }
  8030. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8031. return elts;
  8032. }
  8033. shouldParseAsyncArrow() {
  8034. return this.match(types.arrow) && !this.canInsertSemicolon();
  8035. }
  8036. parseAsyncArrowFromCallExpression(node, call) {
  8037. var _call$extra;
  8038. this.expect(types.arrow);
  8039. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8040. return node;
  8041. }
  8042. parseNoCallExpr() {
  8043. const startPos = this.state.start;
  8044. const startLoc = this.state.startLoc;
  8045. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8046. }
  8047. parseExprAtom(refExpressionErrors) {
  8048. if (this.state.type === types.slash) this.readRegexp();
  8049. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8050. let node;
  8051. switch (this.state.type) {
  8052. case types._super:
  8053. node = this.startNode();
  8054. this.next();
  8055. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  8056. this.raise(node.start, Errors.SuperNotAllowed);
  8057. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  8058. this.raise(node.start, Errors.UnexpectedSuper);
  8059. }
  8060. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  8061. this.raise(node.start, Errors.UnsupportedSuper);
  8062. }
  8063. return this.finishNode(node, "Super");
  8064. case types._import:
  8065. node = this.startNode();
  8066. this.next();
  8067. if (this.match(types.dot)) {
  8068. return this.parseImportMetaProperty(node);
  8069. }
  8070. if (!this.match(types.parenL)) {
  8071. this.raise(this.state.lastTokStart, Errors.UnsupportedImport);
  8072. }
  8073. return this.finishNode(node, "Import");
  8074. case types._this:
  8075. node = this.startNode();
  8076. this.next();
  8077. return this.finishNode(node, "ThisExpression");
  8078. case types.name:
  8079. {
  8080. node = this.startNode();
  8081. const containsEsc = this.state.containsEsc;
  8082. const id = this.parseIdentifier();
  8083. if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) {
  8084. const last = this.state.context.length - 1;
  8085. if (this.state.context[last] !== types$1.functionStatement) {
  8086. throw new Error("Internal error");
  8087. }
  8088. this.state.context[last] = types$1.functionExpression;
  8089. this.next();
  8090. return this.parseFunction(node, undefined, true);
  8091. } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) {
  8092. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8093. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  8094. const oldYieldPos = this.state.yieldPos;
  8095. const oldAwaitPos = this.state.awaitPos;
  8096. this.state.maybeInArrowParameters = true;
  8097. this.state.maybeInAsyncArrowHead = true;
  8098. this.state.yieldPos = -1;
  8099. this.state.awaitPos = -1;
  8100. const params = [this.parseIdentifier()];
  8101. this.expect(types.arrow);
  8102. this.checkYieldAwaitInDefaultParams();
  8103. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8104. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  8105. this.state.yieldPos = oldYieldPos;
  8106. this.state.awaitPos = oldAwaitPos;
  8107. this.parseArrowExpression(node, params, true);
  8108. return node;
  8109. }
  8110. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8111. this.next();
  8112. this.parseArrowExpression(node, [id], false);
  8113. return node;
  8114. }
  8115. return id;
  8116. }
  8117. case types._do:
  8118. {
  8119. this.expectPlugin("doExpressions");
  8120. const node = this.startNode();
  8121. this.next();
  8122. const oldLabels = this.state.labels;
  8123. this.state.labels = [];
  8124. node.body = this.parseBlock();
  8125. this.state.labels = oldLabels;
  8126. return this.finishNode(node, "DoExpression");
  8127. }
  8128. case types.regexp:
  8129. {
  8130. const value = this.state.value;
  8131. node = this.parseLiteral(value.value, "RegExpLiteral");
  8132. node.pattern = value.pattern;
  8133. node.flags = value.flags;
  8134. return node;
  8135. }
  8136. case types.num:
  8137. return this.parseLiteral(this.state.value, "NumericLiteral");
  8138. case types.bigint:
  8139. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8140. case types.string:
  8141. return this.parseLiteral(this.state.value, "StringLiteral");
  8142. case types._null:
  8143. node = this.startNode();
  8144. this.next();
  8145. return this.finishNode(node, "NullLiteral");
  8146. case types._true:
  8147. case types._false:
  8148. return this.parseBooleanLiteral();
  8149. case types.parenL:
  8150. return this.parseParenAndDistinguishExpression(canBeArrow);
  8151. case types.bracketBarL:
  8152. case types.bracketHashL:
  8153. {
  8154. this.expectPlugin("recordAndTuple");
  8155. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8156. const close = this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR;
  8157. this.state.inFSharpPipelineDirectBody = false;
  8158. node = this.startNode();
  8159. this.next();
  8160. node.elements = this.parseExprList(close, true, refExpressionErrors, node);
  8161. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8162. return this.finishNode(node, "TupleExpression");
  8163. }
  8164. case types.bracketL:
  8165. {
  8166. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8167. this.state.inFSharpPipelineDirectBody = false;
  8168. node = this.startNode();
  8169. this.next();
  8170. node.elements = this.parseExprList(types.bracketR, true, refExpressionErrors, node);
  8171. if (!this.state.maybeInArrowParameters) {
  8172. this.toReferencedList(node.elements);
  8173. }
  8174. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8175. return this.finishNode(node, "ArrayExpression");
  8176. }
  8177. case types.braceBarL:
  8178. case types.braceHashL:
  8179. {
  8180. this.expectPlugin("recordAndTuple");
  8181. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8182. const close = this.state.type === types.braceBarL ? types.braceBarR : types.braceR;
  8183. this.state.inFSharpPipelineDirectBody = false;
  8184. const ret = this.parseObj(close, false, true, refExpressionErrors);
  8185. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8186. return ret;
  8187. }
  8188. case types.braceL:
  8189. {
  8190. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8191. this.state.inFSharpPipelineDirectBody = false;
  8192. const ret = this.parseObj(types.braceR, false, false, refExpressionErrors);
  8193. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8194. return ret;
  8195. }
  8196. case types._function:
  8197. return this.parseFunctionExpression();
  8198. case types.at:
  8199. this.parseDecorators();
  8200. case types._class:
  8201. node = this.startNode();
  8202. this.takeDecorators(node);
  8203. return this.parseClass(node, false);
  8204. case types._new:
  8205. return this.parseNew();
  8206. case types.backQuote:
  8207. return this.parseTemplate(false);
  8208. case types.doubleColon:
  8209. {
  8210. node = this.startNode();
  8211. this.next();
  8212. node.object = null;
  8213. const callee = node.callee = this.parseNoCallExpr();
  8214. if (callee.type === "MemberExpression") {
  8215. return this.finishNode(node, "BindExpression");
  8216. } else {
  8217. throw this.raise(callee.start, Errors.UnsupportedBind);
  8218. }
  8219. }
  8220. case types.hash:
  8221. {
  8222. if (this.state.inPipeline) {
  8223. node = this.startNode();
  8224. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  8225. this.raise(node.start, Errors.PrimaryTopicRequiresSmartPipeline);
  8226. }
  8227. this.next();
  8228. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  8229. this.raise(node.start, Errors.PrimaryTopicNotAllowed);
  8230. }
  8231. this.registerTopicReference();
  8232. return this.finishNode(node, "PipelinePrimaryTopicReference");
  8233. }
  8234. }
  8235. default:
  8236. throw this.unexpected();
  8237. }
  8238. }
  8239. parseBooleanLiteral() {
  8240. const node = this.startNode();
  8241. node.value = this.match(types._true);
  8242. this.next();
  8243. return this.finishNode(node, "BooleanLiteral");
  8244. }
  8245. parseMaybePrivateName(isPrivateNameAllowed) {
  8246. const isPrivate = this.match(types.hash);
  8247. if (isPrivate) {
  8248. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  8249. if (!isPrivateNameAllowed) {
  8250. this.raise(this.state.pos, Errors.UnexpectedPrivateField);
  8251. }
  8252. const node = this.startNode();
  8253. this.next();
  8254. this.assertNoSpace("Unexpected space between # and identifier");
  8255. node.id = this.parseIdentifier(true);
  8256. return this.finishNode(node, "PrivateName");
  8257. } else {
  8258. return this.parseIdentifier(true);
  8259. }
  8260. }
  8261. parseFunctionExpression() {
  8262. const node = this.startNode();
  8263. let meta = this.startNode();
  8264. this.next();
  8265. meta = this.createIdentifier(meta, "function");
  8266. if (this.prodParam.hasYield && this.eat(types.dot)) {
  8267. return this.parseMetaProperty(node, meta, "sent");
  8268. }
  8269. return this.parseFunction(node);
  8270. }
  8271. parseMetaProperty(node, meta, propertyName) {
  8272. node.meta = meta;
  8273. if (meta.name === "function" && propertyName === "sent") {
  8274. if (this.isContextual(propertyName)) {
  8275. this.expectPlugin("functionSent");
  8276. } else if (!this.hasPlugin("functionSent")) {
  8277. this.unexpected();
  8278. }
  8279. }
  8280. const containsEsc = this.state.containsEsc;
  8281. node.property = this.parseIdentifier(true);
  8282. if (node.property.name !== propertyName || containsEsc) {
  8283. this.raise(node.property.start, Errors.UnsupportedMetaProperty, meta.name, propertyName);
  8284. }
  8285. return this.finishNode(node, "MetaProperty");
  8286. }
  8287. parseImportMetaProperty(node) {
  8288. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  8289. this.expect(types.dot);
  8290. if (this.isContextual("meta")) {
  8291. this.expectPlugin("importMeta");
  8292. if (!this.inModule) {
  8293. this.raiseWithData(id.start, {
  8294. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8295. }, Errors.ImportMetaOutsideModule);
  8296. }
  8297. this.sawUnambiguousESM = true;
  8298. } else if (!this.hasPlugin("importMeta")) {
  8299. this.raise(id.start, Errors.ImportCallArityLtOne);
  8300. }
  8301. return this.parseMetaProperty(node, id, "meta");
  8302. }
  8303. parseLiteral(value, type, startPos, startLoc) {
  8304. startPos = startPos || this.state.start;
  8305. startLoc = startLoc || this.state.startLoc;
  8306. const node = this.startNodeAt(startPos, startLoc);
  8307. this.addExtra(node, "rawValue", value);
  8308. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  8309. node.value = value;
  8310. this.next();
  8311. return this.finishNode(node, type);
  8312. }
  8313. parseParenAndDistinguishExpression(canBeArrow) {
  8314. const startPos = this.state.start;
  8315. const startLoc = this.state.startLoc;
  8316. let val;
  8317. this.expect(types.parenL);
  8318. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8319. const oldYieldPos = this.state.yieldPos;
  8320. const oldAwaitPos = this.state.awaitPos;
  8321. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8322. this.state.maybeInArrowParameters = true;
  8323. this.state.yieldPos = -1;
  8324. this.state.awaitPos = -1;
  8325. this.state.inFSharpPipelineDirectBody = false;
  8326. const innerStartPos = this.state.start;
  8327. const innerStartLoc = this.state.startLoc;
  8328. const exprList = [];
  8329. const refExpressionErrors = new ExpressionErrors();
  8330. const refNeedsArrowPos = {
  8331. start: 0
  8332. };
  8333. let first = true;
  8334. let spreadStart;
  8335. let optionalCommaStart;
  8336. while (!this.match(types.parenR)) {
  8337. if (first) {
  8338. first = false;
  8339. } else {
  8340. this.expect(types.comma, refNeedsArrowPos.start || null);
  8341. if (this.match(types.parenR)) {
  8342. optionalCommaStart = this.state.start;
  8343. break;
  8344. }
  8345. }
  8346. if (this.match(types.ellipsis)) {
  8347. const spreadNodeStartPos = this.state.start;
  8348. const spreadNodeStartLoc = this.state.startLoc;
  8349. spreadStart = this.state.start;
  8350. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  8351. this.checkCommaAfterRest(41);
  8352. break;
  8353. } else {
  8354. exprList.push(this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  8355. }
  8356. }
  8357. const innerEndPos = this.state.start;
  8358. const innerEndLoc = this.state.startLoc;
  8359. this.expect(types.parenR);
  8360. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8361. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8362. let arrowNode = this.startNodeAt(startPos, startLoc);
  8363. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  8364. if (!this.isAwaitAllowed() && !this.state.maybeInAsyncArrowHead) {
  8365. this.state.awaitPos = oldAwaitPos;
  8366. }
  8367. this.checkYieldAwaitInDefaultParams();
  8368. this.state.yieldPos = oldYieldPos;
  8369. this.state.awaitPos = oldAwaitPos;
  8370. for (let _i = 0; _i < exprList.length; _i++) {
  8371. const param = exprList[_i];
  8372. if (param.extra && param.extra.parenthesized) {
  8373. this.unexpected(param.extra.parenStart);
  8374. }
  8375. }
  8376. this.parseArrowExpression(arrowNode, exprList, false);
  8377. return arrowNode;
  8378. }
  8379. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  8380. if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
  8381. if (!exprList.length) {
  8382. this.unexpected(this.state.lastTokStart);
  8383. }
  8384. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8385. if (spreadStart) this.unexpected(spreadStart);
  8386. this.checkExpressionErrors(refExpressionErrors, true);
  8387. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8388. this.toReferencedListDeep(exprList, true);
  8389. if (exprList.length > 1) {
  8390. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8391. val.expressions = exprList;
  8392. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8393. } else {
  8394. val = exprList[0];
  8395. }
  8396. if (!this.options.createParenthesizedExpressions) {
  8397. this.addExtra(val, "parenthesized", true);
  8398. this.addExtra(val, "parenStart", startPos);
  8399. return val;
  8400. }
  8401. const parenExpression = this.startNodeAt(startPos, startLoc);
  8402. parenExpression.expression = val;
  8403. this.finishNode(parenExpression, "ParenthesizedExpression");
  8404. return parenExpression;
  8405. }
  8406. shouldParseArrow() {
  8407. return !this.canInsertSemicolon();
  8408. }
  8409. parseArrow(node) {
  8410. if (this.eat(types.arrow)) {
  8411. return node;
  8412. }
  8413. }
  8414. parseParenItem(node, startPos, startLoc) {
  8415. return node;
  8416. }
  8417. parseNew() {
  8418. const node = this.startNode();
  8419. let meta = this.startNode();
  8420. this.next();
  8421. meta = this.createIdentifier(meta, "new");
  8422. if (this.eat(types.dot)) {
  8423. const metaProp = this.parseMetaProperty(node, meta, "target");
  8424. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  8425. let error = Errors.UnexpectedNewTarget;
  8426. if (this.hasPlugin("classProperties")) {
  8427. error += " or class properties";
  8428. }
  8429. this.raise(metaProp.start, error);
  8430. }
  8431. return metaProp;
  8432. }
  8433. node.callee = this.parseNoCallExpr();
  8434. if (node.callee.type === "Import") {
  8435. this.raise(node.callee.start, Errors.ImportCallNotNewExpression);
  8436. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  8437. this.raise(this.state.lastTokEnd, Errors.OptionalChainingNoNew);
  8438. } else if (this.eat(types.questionDot)) {
  8439. this.raise(this.state.start, Errors.OptionalChainingNoNew);
  8440. }
  8441. this.parseNewArguments(node);
  8442. return this.finishNode(node, "NewExpression");
  8443. }
  8444. parseNewArguments(node) {
  8445. if (this.eat(types.parenL)) {
  8446. const args = this.parseExprList(types.parenR);
  8447. this.toReferencedList(args);
  8448. node.arguments = args;
  8449. } else {
  8450. node.arguments = [];
  8451. }
  8452. }
  8453. parseTemplateElement(isTagged) {
  8454. const elem = this.startNode();
  8455. if (this.state.value === null) {
  8456. if (!isTagged) {
  8457. this.raise(this.state.start + 1, Errors.InvalidEscapeSequenceTemplate);
  8458. }
  8459. }
  8460. elem.value = {
  8461. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8462. cooked: this.state.value
  8463. };
  8464. this.next();
  8465. elem.tail = this.match(types.backQuote);
  8466. return this.finishNode(elem, "TemplateElement");
  8467. }
  8468. parseTemplate(isTagged) {
  8469. const node = this.startNode();
  8470. this.next();
  8471. node.expressions = [];
  8472. let curElt = this.parseTemplateElement(isTagged);
  8473. node.quasis = [curElt];
  8474. while (!curElt.tail) {
  8475. this.expect(types.dollarBraceL);
  8476. node.expressions.push(this.parseExpression());
  8477. this.expect(types.braceR);
  8478. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8479. }
  8480. this.next();
  8481. return this.finishNode(node, "TemplateLiteral");
  8482. }
  8483. parseObj(close, isPattern, isRecord, refExpressionErrors) {
  8484. const propHash = Object.create(null);
  8485. let first = true;
  8486. const node = this.startNode();
  8487. node.properties = [];
  8488. this.next();
  8489. while (!this.eat(close)) {
  8490. if (first) {
  8491. first = false;
  8492. } else {
  8493. this.expect(types.comma);
  8494. if (this.match(close)) {
  8495. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8496. this.next();
  8497. break;
  8498. }
  8499. }
  8500. const prop = this.parseObjectMember(isPattern, refExpressionErrors);
  8501. if (!isPattern) {
  8502. this.checkDuplicatedProto(prop, propHash, refExpressionErrors);
  8503. }
  8504. if (prop.shorthand) {
  8505. this.addExtra(prop, "shorthand", true);
  8506. }
  8507. node.properties.push(prop);
  8508. }
  8509. let type = "ObjectExpression";
  8510. if (isPattern) {
  8511. type = "ObjectPattern";
  8512. } else if (isRecord) {
  8513. type = "RecordExpression";
  8514. }
  8515. return this.finishNode(node, type);
  8516. }
  8517. isAsyncProp(prop) {
  8518. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.match(types.name) || this.match(types.num) || this.match(types.string) || this.match(types.bracketL) || this.state.type.keyword || this.match(types.star)) && !this.hasPrecedingLineBreak();
  8519. }
  8520. parseObjectMember(isPattern, refExpressionErrors) {
  8521. let decorators = [];
  8522. if (this.match(types.at)) {
  8523. if (this.hasPlugin("decorators")) {
  8524. this.raise(this.state.start, Errors.UnsupportedPropertyDecorator);
  8525. }
  8526. while (this.match(types.at)) {
  8527. decorators.push(this.parseDecorator());
  8528. }
  8529. }
  8530. const prop = this.startNode();
  8531. let isGenerator = false;
  8532. let isAsync = false;
  8533. let startPos;
  8534. let startLoc;
  8535. if (this.match(types.ellipsis)) {
  8536. if (decorators.length) this.unexpected();
  8537. if (isPattern) {
  8538. this.next();
  8539. prop.argument = this.parseIdentifier();
  8540. this.checkCommaAfterRest(125);
  8541. return this.finishNode(prop, "RestElement");
  8542. }
  8543. return this.parseSpread();
  8544. }
  8545. if (decorators.length) {
  8546. prop.decorators = decorators;
  8547. decorators = [];
  8548. }
  8549. prop.method = false;
  8550. if (isPattern || refExpressionErrors) {
  8551. startPos = this.state.start;
  8552. startLoc = this.state.startLoc;
  8553. }
  8554. if (!isPattern) {
  8555. isGenerator = this.eat(types.star);
  8556. }
  8557. const containsEsc = this.state.containsEsc;
  8558. this.parsePropertyName(prop, false);
  8559. if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) {
  8560. isAsync = true;
  8561. isGenerator = this.eat(types.star);
  8562. this.parsePropertyName(prop, false);
  8563. } else {
  8564. isAsync = false;
  8565. }
  8566. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  8567. return prop;
  8568. }
  8569. isGetterOrSetterMethod(prop, isPattern) {
  8570. return !isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.match(types.string) || this.match(types.num) || this.match(types.bracketL) || this.match(types.name) || !!this.state.type.keyword);
  8571. }
  8572. getGetterSetterExpectedParamCount(method) {
  8573. return method.kind === "get" ? 0 : 1;
  8574. }
  8575. checkGetterSetterParams(method) {
  8576. const paramCount = this.getGetterSetterExpectedParamCount(method);
  8577. const start = method.start;
  8578. if (method.params.length !== paramCount) {
  8579. if (method.kind === "get") {
  8580. this.raise(start, Errors.BadGetterArity);
  8581. } else {
  8582. this.raise(start, Errors.BadSetterArity);
  8583. }
  8584. }
  8585. if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") {
  8586. this.raise(start, Errors.BadSetterRestParameter);
  8587. }
  8588. }
  8589. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  8590. if (isAsync || isGenerator || this.match(types.parenL)) {
  8591. if (isPattern) this.unexpected();
  8592. prop.kind = "method";
  8593. prop.method = true;
  8594. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  8595. }
  8596. if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) {
  8597. if (isGenerator || isAsync) this.unexpected();
  8598. prop.kind = prop.key.name;
  8599. this.parsePropertyName(prop, false);
  8600. this.parseMethod(prop, false, false, false, false, "ObjectMethod");
  8601. this.checkGetterSetterParams(prop);
  8602. return prop;
  8603. }
  8604. }
  8605. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  8606. prop.shorthand = false;
  8607. if (this.eat(types.colon)) {
  8608. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refExpressionErrors);
  8609. return this.finishNode(prop, "ObjectProperty");
  8610. }
  8611. if (!prop.computed && prop.key.type === "Identifier") {
  8612. this.checkReservedWord(prop.key.name, prop.key.start, true, true);
  8613. if (isPattern) {
  8614. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8615. } else if (this.match(types.eq) && refExpressionErrors) {
  8616. if (refExpressionErrors.shorthandAssign === -1) {
  8617. refExpressionErrors.shorthandAssign = this.state.start;
  8618. }
  8619. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8620. } else {
  8621. prop.value = prop.key.__clone();
  8622. }
  8623. prop.shorthand = true;
  8624. return this.finishNode(prop, "ObjectProperty");
  8625. }
  8626. }
  8627. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  8628. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  8629. if (!node) this.unexpected();
  8630. return node;
  8631. }
  8632. parsePropertyName(prop, isPrivateNameAllowed) {
  8633. if (this.eat(types.bracketL)) {
  8634. prop.computed = true;
  8635. prop.key = this.parseMaybeAssign();
  8636. this.expect(types.bracketR);
  8637. } else {
  8638. const oldInPropertyName = this.state.inPropertyName;
  8639. this.state.inPropertyName = true;
  8640. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  8641. if (prop.key.type !== "PrivateName") {
  8642. prop.computed = false;
  8643. }
  8644. this.state.inPropertyName = oldInPropertyName;
  8645. }
  8646. return prop.key;
  8647. }
  8648. initFunction(node, isAsync) {
  8649. node.id = null;
  8650. node.generator = false;
  8651. node.async = !!isAsync;
  8652. }
  8653. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  8654. const oldYieldPos = this.state.yieldPos;
  8655. const oldAwaitPos = this.state.awaitPos;
  8656. this.state.yieldPos = -1;
  8657. this.state.awaitPos = -1;
  8658. this.initFunction(node, isAsync);
  8659. node.generator = !!isGenerator;
  8660. const allowModifiers = isConstructor;
  8661. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  8662. this.prodParam.enter(functionFlags(isAsync, node.generator));
  8663. this.parseFunctionParams(node, allowModifiers);
  8664. this.parseFunctionBodyAndFinish(node, type, true);
  8665. this.prodParam.exit();
  8666. this.scope.exit();
  8667. this.state.yieldPos = oldYieldPos;
  8668. this.state.awaitPos = oldAwaitPos;
  8669. return node;
  8670. }
  8671. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  8672. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  8673. this.prodParam.enter(functionFlags(isAsync, false));
  8674. this.initFunction(node, isAsync);
  8675. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8676. const oldYieldPos = this.state.yieldPos;
  8677. const oldAwaitPos = this.state.awaitPos;
  8678. if (params) {
  8679. this.state.maybeInArrowParameters = true;
  8680. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  8681. }
  8682. this.state.maybeInArrowParameters = false;
  8683. this.state.yieldPos = -1;
  8684. this.state.awaitPos = -1;
  8685. this.parseFunctionBody(node, true);
  8686. this.prodParam.exit();
  8687. this.scope.exit();
  8688. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8689. this.state.yieldPos = oldYieldPos;
  8690. this.state.awaitPos = oldAwaitPos;
  8691. return this.finishNode(node, "ArrowFunctionExpression");
  8692. }
  8693. setArrowFunctionParameters(node, params, trailingCommaPos) {
  8694. node.params = this.toAssignableList(params, trailingCommaPos);
  8695. }
  8696. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8697. this.parseFunctionBody(node, false, isMethod);
  8698. this.finishNode(node, type);
  8699. }
  8700. parseFunctionBody(node, allowExpression, isMethod = false) {
  8701. const isExpression = allowExpression && !this.match(types.braceL);
  8702. const oldInParameters = this.state.inParameters;
  8703. this.state.inParameters = false;
  8704. if (isExpression) {
  8705. node.body = this.parseMaybeAssign();
  8706. this.checkParams(node, false, allowExpression, false);
  8707. } else {
  8708. const oldStrict = this.state.strict;
  8709. const oldLabels = this.state.labels;
  8710. this.state.labels = [];
  8711. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  8712. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  8713. const nonSimple = !this.isSimpleParamList(node.params);
  8714. if (hasStrictModeDirective && nonSimple) {
  8715. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  8716. this.raise(errorPos, Errors.IllegalLanguageModeDirective);
  8717. }
  8718. const strictModeChanged = !oldStrict && this.state.strict;
  8719. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  8720. if (this.state.strict && node.id) {
  8721. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, strictModeChanged);
  8722. }
  8723. });
  8724. this.prodParam.exit();
  8725. this.state.labels = oldLabels;
  8726. }
  8727. this.state.inParameters = oldInParameters;
  8728. }
  8729. isSimpleParamList(params) {
  8730. for (let i = 0, len = params.length; i < len; i++) {
  8731. if (params[i].type !== "Identifier") return false;
  8732. }
  8733. return true;
  8734. }
  8735. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  8736. const nameHash = Object.create(null);
  8737. for (let i = 0; i < node.params.length; i++) {
  8738. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged);
  8739. }
  8740. }
  8741. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  8742. const elts = [];
  8743. let first = true;
  8744. while (!this.eat(close)) {
  8745. if (first) {
  8746. first = false;
  8747. } else {
  8748. this.expect(types.comma);
  8749. if (this.match(close)) {
  8750. if (nodeForExtra) {
  8751. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8752. }
  8753. this.next();
  8754. break;
  8755. }
  8756. }
  8757. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  8758. }
  8759. return elts;
  8760. }
  8761. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  8762. let elt;
  8763. if (allowEmpty && this.match(types.comma)) {
  8764. elt = null;
  8765. } else if (this.match(types.ellipsis)) {
  8766. const spreadNodeStartPos = this.state.start;
  8767. const spreadNodeStartLoc = this.state.startLoc;
  8768. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  8769. } else if (this.match(types.question)) {
  8770. this.expectPlugin("partialApplication");
  8771. if (!allowPlaceholder) {
  8772. this.raise(this.state.start, Errors.UnexpectedArgumentPlaceholder);
  8773. }
  8774. const node = this.startNode();
  8775. this.next();
  8776. elt = this.finishNode(node, "ArgumentPlaceholder");
  8777. } else {
  8778. elt = this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  8779. }
  8780. return elt;
  8781. }
  8782. parseIdentifier(liberal) {
  8783. const node = this.startNode();
  8784. const name = this.parseIdentifierName(node.start, liberal);
  8785. return this.createIdentifier(node, name);
  8786. }
  8787. createIdentifier(node, name) {
  8788. node.name = name;
  8789. node.loc.identifierName = name;
  8790. return this.finishNode(node, "Identifier");
  8791. }
  8792. parseIdentifierName(pos, liberal) {
  8793. let name;
  8794. if (this.match(types.name)) {
  8795. name = this.state.value;
  8796. } else if (this.state.type.keyword) {
  8797. name = this.state.type.keyword;
  8798. if ((name === "class" || name === "function") && (this.state.lastTokEnd !== this.state.lastTokStart + 1 || this.input.charCodeAt(this.state.lastTokStart) !== 46)) {
  8799. this.state.context.pop();
  8800. }
  8801. } else {
  8802. throw this.unexpected();
  8803. }
  8804. if (liberal) {
  8805. this.state.type = types.name;
  8806. } else {
  8807. this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false);
  8808. }
  8809. this.next();
  8810. return name;
  8811. }
  8812. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  8813. if (this.prodParam.hasYield && word === "yield") {
  8814. this.raise(startLoc, Errors.YieldBindingIdentifier);
  8815. return;
  8816. }
  8817. if (word === "await") {
  8818. if (this.prodParam.hasAwait) {
  8819. this.raise(startLoc, Errors.AwaitBindingIdentifier);
  8820. return;
  8821. }
  8822. if (this.state.awaitPos === -1 && (this.state.maybeInAsyncArrowHead || this.isAwaitAllowed())) {
  8823. this.state.awaitPos = this.state.start;
  8824. }
  8825. }
  8826. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  8827. this.raise(startLoc, Errors.ArgumentsDisallowedInInitializer);
  8828. return;
  8829. }
  8830. if (checkKeywords && isKeyword(word)) {
  8831. this.raise(startLoc, Errors.UnexpectedKeyword, word);
  8832. return;
  8833. }
  8834. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  8835. if (reservedTest(word, this.inModule)) {
  8836. if (!this.prodParam.hasAwait && word === "await") {
  8837. this.raise(startLoc, Errors.AwaitNotInAsyncFunction);
  8838. } else {
  8839. this.raise(startLoc, Errors.UnexpectedReservedWord, word);
  8840. }
  8841. }
  8842. }
  8843. isAwaitAllowed() {
  8844. if (this.scope.inFunction) return this.prodParam.hasAwait;
  8845. if (this.options.allowAwaitOutsideFunction) return true;
  8846. if (this.hasPlugin("topLevelAwait")) {
  8847. return this.inModule && this.prodParam.hasAwait;
  8848. }
  8849. return false;
  8850. }
  8851. parseAwait() {
  8852. const node = this.startNode();
  8853. this.next();
  8854. if (this.state.inParameters) {
  8855. this.raise(node.start, Errors.AwaitExpressionFormalParameter);
  8856. } else if (this.state.awaitPos === -1) {
  8857. this.state.awaitPos = node.start;
  8858. }
  8859. if (this.eat(types.star)) {
  8860. this.raise(node.start, Errors.ObsoleteAwaitStar);
  8861. }
  8862. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  8863. 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)) {
  8864. this.ambiguousScriptDifferentAst = true;
  8865. } else {
  8866. this.sawUnambiguousESM = true;
  8867. }
  8868. }
  8869. if (!this.state.soloAwait) {
  8870. node.argument = this.parseMaybeUnary();
  8871. }
  8872. return this.finishNode(node, "AwaitExpression");
  8873. }
  8874. parseYield(noIn) {
  8875. const node = this.startNode();
  8876. if (this.state.inParameters) {
  8877. this.raise(node.start, Errors.YieldInParameter);
  8878. } else if (this.state.yieldPos === -1) {
  8879. this.state.yieldPos = node.start;
  8880. }
  8881. this.next();
  8882. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  8883. node.delegate = false;
  8884. node.argument = null;
  8885. } else {
  8886. node.delegate = this.eat(types.star);
  8887. node.argument = this.parseMaybeAssign(noIn);
  8888. }
  8889. return this.finishNode(node, "YieldExpression");
  8890. }
  8891. checkPipelineAtInfixOperator(left, leftStartPos) {
  8892. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  8893. if (left.type === "SequenceExpression") {
  8894. this.raise(leftStartPos, Errors.PipelineHeadSequenceExpression);
  8895. }
  8896. }
  8897. }
  8898. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  8899. const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
  8900. this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos);
  8901. return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc);
  8902. }
  8903. checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) {
  8904. if (this.match(types.arrow)) {
  8905. throw this.raise(this.state.start, Errors.PipelineBodyNoArrow);
  8906. } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") {
  8907. this.raise(startPos, Errors.PipelineBodySequenceExpression);
  8908. }
  8909. }
  8910. parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) {
  8911. const bodyNode = this.startNodeAt(startPos, startLoc);
  8912. switch (pipelineStyle) {
  8913. case "PipelineBareFunction":
  8914. bodyNode.callee = childExpression;
  8915. break;
  8916. case "PipelineBareConstructor":
  8917. bodyNode.callee = childExpression.callee;
  8918. break;
  8919. case "PipelineBareAwaitedFunction":
  8920. bodyNode.callee = childExpression.argument;
  8921. break;
  8922. case "PipelineTopicExpression":
  8923. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  8924. this.raise(startPos, Errors.PipelineTopicUnused);
  8925. }
  8926. bodyNode.expression = childExpression;
  8927. break;
  8928. default:
  8929. throw new Error(`Internal @babel/parser error: Unknown pipeline style (${pipelineStyle})`);
  8930. }
  8931. return this.finishNode(bodyNode, pipelineStyle);
  8932. }
  8933. checkSmartPipelineBodyStyle(expression) {
  8934. switch (expression.type) {
  8935. default:
  8936. return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression";
  8937. }
  8938. }
  8939. isSimpleReference(expression) {
  8940. switch (expression.type) {
  8941. case "MemberExpression":
  8942. return !expression.computed && this.isSimpleReference(expression.object);
  8943. case "Identifier":
  8944. return true;
  8945. default:
  8946. return false;
  8947. }
  8948. }
  8949. withTopicPermittingContext(callback) {
  8950. const outerContextTopicState = this.state.topicContext;
  8951. this.state.topicContext = {
  8952. maxNumOfResolvableTopics: 1,
  8953. maxTopicIndex: null
  8954. };
  8955. try {
  8956. return callback();
  8957. } finally {
  8958. this.state.topicContext = outerContextTopicState;
  8959. }
  8960. }
  8961. withTopicForbiddingContext(callback) {
  8962. const outerContextTopicState = this.state.topicContext;
  8963. this.state.topicContext = {
  8964. maxNumOfResolvableTopics: 0,
  8965. maxTopicIndex: null
  8966. };
  8967. try {
  8968. return callback();
  8969. } finally {
  8970. this.state.topicContext = outerContextTopicState;
  8971. }
  8972. }
  8973. withSoloAwaitPermittingContext(callback) {
  8974. const outerContextSoloAwaitState = this.state.soloAwait;
  8975. this.state.soloAwait = true;
  8976. try {
  8977. return callback();
  8978. } finally {
  8979. this.state.soloAwait = outerContextSoloAwaitState;
  8980. }
  8981. }
  8982. registerTopicReference() {
  8983. this.state.topicContext.maxTopicIndex = 0;
  8984. }
  8985. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  8986. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  8987. }
  8988. topicReferenceWasUsedInCurrentTopicContext() {
  8989. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  8990. }
  8991. parseFSharpPipelineBody(prec, noIn) {
  8992. const startPos = this.state.start;
  8993. const startLoc = this.state.startLoc;
  8994. this.state.potentialArrowAt = this.state.start;
  8995. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8996. this.state.inFSharpPipelineDirectBody = true;
  8997. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
  8998. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8999. return ret;
  9000. }
  9001. }
  9002. const loopLabel = {
  9003. kind: "loop"
  9004. },
  9005. switchLabel = {
  9006. kind: "switch"
  9007. };
  9008. const FUNC_NO_FLAGS = 0b000,
  9009. FUNC_STATEMENT = 0b001,
  9010. FUNC_HANGING_STATEMENT = 0b010,
  9011. FUNC_NULLABLE_ID = 0b100;
  9012. class StatementParser extends ExpressionParser {
  9013. parseTopLevel(file, program) {
  9014. program.sourceType = this.options.sourceType;
  9015. program.interpreter = this.parseInterpreterDirective();
  9016. this.parseBlockBody(program, true, true, types.eof);
  9017. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9018. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  9019. const [name] = _Array$from[_i];
  9020. const pos = this.scope.undefinedExports.get(name);
  9021. this.raise(pos, Errors.ModuleExportUndefined, name);
  9022. }
  9023. }
  9024. file.program = this.finishNode(program, "Program");
  9025. file.comments = this.state.comments;
  9026. if (this.options.tokens) file.tokens = this.tokens;
  9027. return this.finishNode(file, "File");
  9028. }
  9029. stmtToDirective(stmt) {
  9030. const expr = stmt.expression;
  9031. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9032. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9033. const raw = this.input.slice(expr.start, expr.end);
  9034. const val = directiveLiteral.value = raw.slice(1, -1);
  9035. this.addExtra(directiveLiteral, "raw", raw);
  9036. this.addExtra(directiveLiteral, "rawValue", val);
  9037. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9038. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9039. }
  9040. parseInterpreterDirective() {
  9041. if (!this.match(types.interpreterDirective)) {
  9042. return null;
  9043. }
  9044. const node = this.startNode();
  9045. node.value = this.state.value;
  9046. this.next();
  9047. return this.finishNode(node, "InterpreterDirective");
  9048. }
  9049. isLet(context) {
  9050. if (!this.isContextual("let")) {
  9051. return false;
  9052. }
  9053. const next = this.nextTokenStart();
  9054. const nextCh = this.input.charCodeAt(next);
  9055. if (nextCh === 91) return true;
  9056. if (context) return false;
  9057. if (nextCh === 123) return true;
  9058. if (isIdentifierStart(nextCh)) {
  9059. let pos = next + 1;
  9060. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9061. ++pos;
  9062. }
  9063. const ident = this.input.slice(next, pos);
  9064. if (!keywordRelationalOperator.test(ident)) return true;
  9065. }
  9066. return false;
  9067. }
  9068. parseStatement(context, topLevel) {
  9069. if (this.match(types.at)) {
  9070. this.parseDecorators(true);
  9071. }
  9072. return this.parseStatementContent(context, topLevel);
  9073. }
  9074. parseStatementContent(context, topLevel) {
  9075. let starttype = this.state.type;
  9076. const node = this.startNode();
  9077. let kind;
  9078. if (this.isLet(context)) {
  9079. starttype = types._var;
  9080. kind = "let";
  9081. }
  9082. switch (starttype) {
  9083. case types._break:
  9084. case types._continue:
  9085. return this.parseBreakContinueStatement(node, starttype.keyword);
  9086. case types._debugger:
  9087. return this.parseDebuggerStatement(node);
  9088. case types._do:
  9089. return this.parseDoStatement(node);
  9090. case types._for:
  9091. return this.parseForStatement(node);
  9092. case types._function:
  9093. if (this.lookaheadCharCode() === 46) break;
  9094. if (context) {
  9095. if (this.state.strict) {
  9096. this.raise(this.state.start, Errors.StrictFunction);
  9097. } else if (context !== "if" && context !== "label") {
  9098. this.raise(this.state.start, Errors.SloppyFunction);
  9099. }
  9100. }
  9101. return this.parseFunctionStatement(node, false, !context);
  9102. case types._class:
  9103. if (context) this.unexpected();
  9104. return this.parseClass(node, true);
  9105. case types._if:
  9106. return this.parseIfStatement(node);
  9107. case types._return:
  9108. return this.parseReturnStatement(node);
  9109. case types._switch:
  9110. return this.parseSwitchStatement(node);
  9111. case types._throw:
  9112. return this.parseThrowStatement(node);
  9113. case types._try:
  9114. return this.parseTryStatement(node);
  9115. case types._const:
  9116. case types._var:
  9117. kind = kind || this.state.value;
  9118. if (context && kind !== "var") {
  9119. this.raise(this.state.start, Errors.UnexpectedLexicalDeclaration);
  9120. }
  9121. return this.parseVarStatement(node, kind);
  9122. case types._while:
  9123. return this.parseWhileStatement(node);
  9124. case types._with:
  9125. return this.parseWithStatement(node);
  9126. case types.braceL:
  9127. return this.parseBlock();
  9128. case types.semi:
  9129. return this.parseEmptyStatement(node);
  9130. case types._export:
  9131. case types._import:
  9132. {
  9133. const nextTokenCharCode = this.lookaheadCharCode();
  9134. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  9135. break;
  9136. }
  9137. if (!this.options.allowImportExportEverywhere && !topLevel) {
  9138. this.raise(this.state.start, Errors.UnexpectedImportExport);
  9139. }
  9140. this.next();
  9141. let result;
  9142. if (starttype === types._import) {
  9143. result = this.parseImport(node);
  9144. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  9145. this.sawUnambiguousESM = true;
  9146. }
  9147. } else {
  9148. result = this.parseExport(node);
  9149. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  9150. this.sawUnambiguousESM = true;
  9151. }
  9152. }
  9153. this.assertModuleNodeAllowed(node);
  9154. return result;
  9155. }
  9156. default:
  9157. {
  9158. if (this.isAsyncFunction()) {
  9159. if (context) {
  9160. this.raise(this.state.start, Errors.AsyncFunctionInSingleStatementContext);
  9161. }
  9162. this.next();
  9163. return this.parseFunctionStatement(node, true, !context);
  9164. }
  9165. }
  9166. }
  9167. const maybeName = this.state.value;
  9168. const expr = this.parseExpression();
  9169. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  9170. return this.parseLabeledStatement(node, maybeName, expr, context);
  9171. } else {
  9172. return this.parseExpressionStatement(node, expr);
  9173. }
  9174. }
  9175. assertModuleNodeAllowed(node) {
  9176. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  9177. this.raiseWithData(node.start, {
  9178. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9179. }, Errors.ImportOutsideModule);
  9180. }
  9181. }
  9182. takeDecorators(node) {
  9183. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9184. if (decorators.length) {
  9185. node.decorators = decorators;
  9186. this.resetStartLocationFromNode(node, decorators[0]);
  9187. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  9188. }
  9189. }
  9190. canHaveLeadingDecorator() {
  9191. return this.match(types._class);
  9192. }
  9193. parseDecorators(allowExport) {
  9194. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9195. while (this.match(types.at)) {
  9196. const decorator = this.parseDecorator();
  9197. currentContextDecorators.push(decorator);
  9198. }
  9199. if (this.match(types._export)) {
  9200. if (!allowExport) {
  9201. this.unexpected();
  9202. }
  9203. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9204. this.raise(this.state.start, Errors.DecoratorExportClass);
  9205. }
  9206. } else if (!this.canHaveLeadingDecorator()) {
  9207. throw this.raise(this.state.start, Errors.UnexpectedLeadingDecorator);
  9208. }
  9209. }
  9210. parseDecorator() {
  9211. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  9212. const node = this.startNode();
  9213. this.next();
  9214. if (this.hasPlugin("decorators")) {
  9215. this.state.decoratorStack.push([]);
  9216. const startPos = this.state.start;
  9217. const startLoc = this.state.startLoc;
  9218. let expr;
  9219. if (this.eat(types.parenL)) {
  9220. expr = this.parseExpression();
  9221. this.expect(types.parenR);
  9222. } else {
  9223. expr = this.parseIdentifier(false);
  9224. while (this.eat(types.dot)) {
  9225. const node = this.startNodeAt(startPos, startLoc);
  9226. node.object = expr;
  9227. node.property = this.parseIdentifier(true);
  9228. node.computed = false;
  9229. expr = this.finishNode(node, "MemberExpression");
  9230. }
  9231. }
  9232. node.expression = this.parseMaybeDecoratorArguments(expr);
  9233. this.state.decoratorStack.pop();
  9234. } else {
  9235. node.expression = this.parseExprSubscripts();
  9236. }
  9237. return this.finishNode(node, "Decorator");
  9238. }
  9239. parseMaybeDecoratorArguments(expr) {
  9240. if (this.eat(types.parenL)) {
  9241. const node = this.startNodeAtNode(expr);
  9242. node.callee = expr;
  9243. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  9244. this.toReferencedList(node.arguments);
  9245. return this.finishNode(node, "CallExpression");
  9246. }
  9247. return expr;
  9248. }
  9249. parseBreakContinueStatement(node, keyword) {
  9250. const isBreak = keyword === "break";
  9251. this.next();
  9252. if (this.isLineTerminator()) {
  9253. node.label = null;
  9254. } else {
  9255. node.label = this.parseIdentifier();
  9256. this.semicolon();
  9257. }
  9258. this.verifyBreakContinue(node, keyword);
  9259. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  9260. }
  9261. verifyBreakContinue(node, keyword) {
  9262. const isBreak = keyword === "break";
  9263. let i;
  9264. for (i = 0; i < this.state.labels.length; ++i) {
  9265. const lab = this.state.labels[i];
  9266. if (node.label == null || lab.name === node.label.name) {
  9267. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  9268. if (node.label && isBreak) break;
  9269. }
  9270. }
  9271. if (i === this.state.labels.length) {
  9272. this.raise(node.start, Errors.IllegalBreakContinue, keyword);
  9273. }
  9274. }
  9275. parseDebuggerStatement(node) {
  9276. this.next();
  9277. this.semicolon();
  9278. return this.finishNode(node, "DebuggerStatement");
  9279. }
  9280. parseHeaderExpression() {
  9281. this.expect(types.parenL);
  9282. const val = this.parseExpression();
  9283. this.expect(types.parenR);
  9284. return val;
  9285. }
  9286. parseDoStatement(node) {
  9287. this.next();
  9288. this.state.labels.push(loopLabel);
  9289. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  9290. this.state.labels.pop();
  9291. this.expect(types._while);
  9292. node.test = this.parseHeaderExpression();
  9293. this.eat(types.semi);
  9294. return this.finishNode(node, "DoWhileStatement");
  9295. }
  9296. parseForStatement(node) {
  9297. this.next();
  9298. this.state.labels.push(loopLabel);
  9299. let awaitAt = -1;
  9300. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  9301. awaitAt = this.state.lastTokStart;
  9302. }
  9303. this.scope.enter(SCOPE_OTHER);
  9304. this.expect(types.parenL);
  9305. if (this.match(types.semi)) {
  9306. if (awaitAt > -1) {
  9307. this.unexpected(awaitAt);
  9308. }
  9309. return this.parseFor(node, null);
  9310. }
  9311. const isLet = this.isLet();
  9312. if (this.match(types._var) || this.match(types._const) || isLet) {
  9313. const init = this.startNode();
  9314. const kind = isLet ? "let" : this.state.value;
  9315. this.next();
  9316. this.parseVar(init, true, kind);
  9317. this.finishNode(init, "VariableDeclaration");
  9318. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  9319. return this.parseForIn(node, init, awaitAt);
  9320. }
  9321. if (awaitAt > -1) {
  9322. this.unexpected(awaitAt);
  9323. }
  9324. return this.parseFor(node, init);
  9325. }
  9326. const refExpressionErrors = new ExpressionErrors();
  9327. const init = this.parseExpression(true, refExpressionErrors);
  9328. if (this.match(types._in) || this.isContextual("of")) {
  9329. this.toAssignable(init);
  9330. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  9331. this.checkLVal(init, undefined, undefined, description);
  9332. return this.parseForIn(node, init, awaitAt);
  9333. } else {
  9334. this.checkExpressionErrors(refExpressionErrors, true);
  9335. }
  9336. if (awaitAt > -1) {
  9337. this.unexpected(awaitAt);
  9338. }
  9339. return this.parseFor(node, init);
  9340. }
  9341. parseFunctionStatement(node, isAsync, declarationPosition) {
  9342. this.next();
  9343. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  9344. }
  9345. parseIfStatement(node) {
  9346. this.next();
  9347. node.test = this.parseHeaderExpression();
  9348. node.consequent = this.parseStatement("if");
  9349. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  9350. return this.finishNode(node, "IfStatement");
  9351. }
  9352. parseReturnStatement(node) {
  9353. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  9354. this.raise(this.state.start, Errors.IllegalReturn);
  9355. }
  9356. this.next();
  9357. if (this.isLineTerminator()) {
  9358. node.argument = null;
  9359. } else {
  9360. node.argument = this.parseExpression();
  9361. this.semicolon();
  9362. }
  9363. return this.finishNode(node, "ReturnStatement");
  9364. }
  9365. parseSwitchStatement(node) {
  9366. this.next();
  9367. node.discriminant = this.parseHeaderExpression();
  9368. const cases = node.cases = [];
  9369. this.expect(types.braceL);
  9370. this.state.labels.push(switchLabel);
  9371. this.scope.enter(SCOPE_OTHER);
  9372. let cur;
  9373. for (let sawDefault; !this.match(types.braceR);) {
  9374. if (this.match(types._case) || this.match(types._default)) {
  9375. const isCase = this.match(types._case);
  9376. if (cur) this.finishNode(cur, "SwitchCase");
  9377. cases.push(cur = this.startNode());
  9378. cur.consequent = [];
  9379. this.next();
  9380. if (isCase) {
  9381. cur.test = this.parseExpression();
  9382. } else {
  9383. if (sawDefault) {
  9384. this.raise(this.state.lastTokStart, Errors.MultipleDefaultsInSwitch);
  9385. }
  9386. sawDefault = true;
  9387. cur.test = null;
  9388. }
  9389. this.expect(types.colon);
  9390. } else {
  9391. if (cur) {
  9392. cur.consequent.push(this.parseStatement(null));
  9393. } else {
  9394. this.unexpected();
  9395. }
  9396. }
  9397. }
  9398. this.scope.exit();
  9399. if (cur) this.finishNode(cur, "SwitchCase");
  9400. this.next();
  9401. this.state.labels.pop();
  9402. return this.finishNode(node, "SwitchStatement");
  9403. }
  9404. parseThrowStatement(node) {
  9405. this.next();
  9406. if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) {
  9407. this.raise(this.state.lastTokEnd, Errors.NewlineAfterThrow);
  9408. }
  9409. node.argument = this.parseExpression();
  9410. this.semicolon();
  9411. return this.finishNode(node, "ThrowStatement");
  9412. }
  9413. parseTryStatement(node) {
  9414. this.next();
  9415. node.block = this.parseBlock();
  9416. node.handler = null;
  9417. if (this.match(types._catch)) {
  9418. const clause = this.startNode();
  9419. this.next();
  9420. if (this.match(types.parenL)) {
  9421. this.expect(types.parenL);
  9422. clause.param = this.parseBindingAtom();
  9423. const simple = clause.param.type === "Identifier";
  9424. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9425. this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause");
  9426. this.expect(types.parenR);
  9427. } else {
  9428. clause.param = null;
  9429. this.scope.enter(SCOPE_OTHER);
  9430. }
  9431. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9432. this.scope.exit();
  9433. node.handler = this.finishNode(clause, "CatchClause");
  9434. }
  9435. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9436. if (!node.handler && !node.finalizer) {
  9437. this.raise(node.start, Errors.NoCatchOrFinally);
  9438. }
  9439. return this.finishNode(node, "TryStatement");
  9440. }
  9441. parseVarStatement(node, kind) {
  9442. this.next();
  9443. this.parseVar(node, false, kind);
  9444. this.semicolon();
  9445. return this.finishNode(node, "VariableDeclaration");
  9446. }
  9447. parseWhileStatement(node) {
  9448. this.next();
  9449. node.test = this.parseHeaderExpression();
  9450. this.state.labels.push(loopLabel);
  9451. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9452. this.state.labels.pop();
  9453. return this.finishNode(node, "WhileStatement");
  9454. }
  9455. parseWithStatement(node) {
  9456. if (this.state.strict) {
  9457. this.raise(this.state.start, Errors.StrictWith);
  9458. }
  9459. this.next();
  9460. node.object = this.parseHeaderExpression();
  9461. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9462. return this.finishNode(node, "WithStatement");
  9463. }
  9464. parseEmptyStatement(node) {
  9465. this.next();
  9466. return this.finishNode(node, "EmptyStatement");
  9467. }
  9468. parseLabeledStatement(node, maybeName, expr, context) {
  9469. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9470. const label = _this$state$labels[_i2];
  9471. if (label.name === maybeName) {
  9472. this.raise(expr.start, Errors.LabelRedeclaration, maybeName);
  9473. }
  9474. }
  9475. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9476. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9477. const label = this.state.labels[i];
  9478. if (label.statementStart === node.start) {
  9479. label.statementStart = this.state.start;
  9480. label.kind = kind;
  9481. } else {
  9482. break;
  9483. }
  9484. }
  9485. this.state.labels.push({
  9486. name: maybeName,
  9487. kind: kind,
  9488. statementStart: this.state.start
  9489. });
  9490. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9491. this.state.labels.pop();
  9492. node.label = expr;
  9493. return this.finishNode(node, "LabeledStatement");
  9494. }
  9495. parseExpressionStatement(node, expr) {
  9496. node.expression = expr;
  9497. this.semicolon();
  9498. return this.finishNode(node, "ExpressionStatement");
  9499. }
  9500. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  9501. const node = this.startNode();
  9502. this.expect(types.braceL);
  9503. if (createNewLexicalScope) {
  9504. this.scope.enter(SCOPE_OTHER);
  9505. }
  9506. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  9507. if (createNewLexicalScope) {
  9508. this.scope.exit();
  9509. }
  9510. return this.finishNode(node, "BlockStatement");
  9511. }
  9512. isValidDirective(stmt) {
  9513. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9514. }
  9515. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  9516. const body = node.body = [];
  9517. const directives = node.directives = [];
  9518. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  9519. }
  9520. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  9521. const octalPositions = [];
  9522. const oldStrict = this.state.strict;
  9523. let hasStrictModeDirective = false;
  9524. let parsedNonDirective = false;
  9525. while (!this.match(end)) {
  9526. if (!parsedNonDirective && this.state.octalPositions.length) {
  9527. octalPositions.push(...this.state.octalPositions);
  9528. }
  9529. const stmt = this.parseStatement(null, topLevel);
  9530. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  9531. const directive = this.stmtToDirective(stmt);
  9532. directives.push(directive);
  9533. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  9534. hasStrictModeDirective = true;
  9535. this.setStrict(true);
  9536. }
  9537. continue;
  9538. }
  9539. parsedNonDirective = true;
  9540. body.push(stmt);
  9541. }
  9542. if (this.state.strict && octalPositions.length) {
  9543. for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
  9544. const pos = octalPositions[_i3];
  9545. this.raise(pos, Errors.StrictOctalLiteral);
  9546. }
  9547. }
  9548. if (afterBlockParse) {
  9549. afterBlockParse.call(this, hasStrictModeDirective);
  9550. }
  9551. if (!oldStrict) {
  9552. this.setStrict(false);
  9553. }
  9554. this.next();
  9555. }
  9556. parseFor(node, init) {
  9557. node.init = init;
  9558. this.expect(types.semi);
  9559. node.test = this.match(types.semi) ? null : this.parseExpression();
  9560. this.expect(types.semi);
  9561. node.update = this.match(types.parenR) ? null : this.parseExpression();
  9562. this.expect(types.parenR);
  9563. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9564. this.scope.exit();
  9565. this.state.labels.pop();
  9566. return this.finishNode(node, "ForStatement");
  9567. }
  9568. parseForIn(node, init, awaitAt) {
  9569. const isForIn = this.match(types._in);
  9570. this.next();
  9571. if (isForIn) {
  9572. if (awaitAt > -1) this.unexpected(awaitAt);
  9573. } else {
  9574. node.await = awaitAt > -1;
  9575. }
  9576. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  9577. this.raise(init.start, Errors.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  9578. } else if (init.type === "AssignmentPattern") {
  9579. this.raise(init.start, Errors.InvalidLhs, "for-loop");
  9580. }
  9581. node.left = init;
  9582. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  9583. this.expect(types.parenR);
  9584. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9585. this.scope.exit();
  9586. this.state.labels.pop();
  9587. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  9588. }
  9589. parseVar(node, isFor, kind) {
  9590. const declarations = node.declarations = [];
  9591. const isTypescript = this.hasPlugin("typescript");
  9592. node.kind = kind;
  9593. for (;;) {
  9594. const decl = this.startNode();
  9595. this.parseVarId(decl, kind);
  9596. if (this.eat(types.eq)) {
  9597. decl.init = this.parseMaybeAssign(isFor);
  9598. } else {
  9599. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  9600. if (!isTypescript) {
  9601. this.unexpected();
  9602. }
  9603. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  9604. this.raise(this.state.lastTokEnd, Errors.DeclarationMissingInitializer, "Complex binding patterns");
  9605. }
  9606. decl.init = null;
  9607. }
  9608. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  9609. if (!this.eat(types.comma)) break;
  9610. }
  9611. return node;
  9612. }
  9613. parseVarId(decl, kind) {
  9614. decl.id = this.parseBindingAtom();
  9615. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var");
  9616. }
  9617. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  9618. const isStatement = statement & FUNC_STATEMENT;
  9619. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  9620. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  9621. this.initFunction(node, isAsync);
  9622. if (this.match(types.star) && isHangingStatement) {
  9623. this.raise(this.state.start, Errors.GeneratorInSingleStatementContext);
  9624. }
  9625. node.generator = this.eat(types.star);
  9626. if (isStatement) {
  9627. node.id = this.parseFunctionId(requireId);
  9628. }
  9629. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9630. const oldYieldPos = this.state.yieldPos;
  9631. const oldAwaitPos = this.state.awaitPos;
  9632. this.state.maybeInArrowParameters = false;
  9633. this.state.yieldPos = -1;
  9634. this.state.awaitPos = -1;
  9635. this.scope.enter(SCOPE_FUNCTION);
  9636. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9637. if (!isStatement) {
  9638. node.id = this.parseFunctionId();
  9639. }
  9640. this.parseFunctionParams(node);
  9641. this.withTopicForbiddingContext(() => {
  9642. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  9643. });
  9644. this.prodParam.exit();
  9645. this.scope.exit();
  9646. if (isStatement && !isHangingStatement) {
  9647. this.registerFunctionStatementId(node);
  9648. }
  9649. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9650. this.state.yieldPos = oldYieldPos;
  9651. this.state.awaitPos = oldAwaitPos;
  9652. return node;
  9653. }
  9654. parseFunctionId(requireId) {
  9655. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  9656. }
  9657. parseFunctionParams(node, allowModifiers) {
  9658. const oldInParameters = this.state.inParameters;
  9659. this.state.inParameters = true;
  9660. this.expect(types.parenL);
  9661. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  9662. this.state.inParameters = oldInParameters;
  9663. this.checkYieldAwaitInDefaultParams();
  9664. }
  9665. registerFunctionStatementId(node) {
  9666. if (!node.id) return;
  9667. 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);
  9668. }
  9669. parseClass(node, isStatement, optionalId) {
  9670. this.next();
  9671. this.takeDecorators(node);
  9672. const oldStrict = this.state.strict;
  9673. this.state.strict = true;
  9674. this.parseClassId(node, isStatement, optionalId);
  9675. this.parseClassSuper(node);
  9676. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  9677. this.state.strict = oldStrict;
  9678. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  9679. }
  9680. isClassProperty() {
  9681. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  9682. }
  9683. isClassMethod() {
  9684. return this.match(types.parenL);
  9685. }
  9686. isNonstaticConstructor(method) {
  9687. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  9688. }
  9689. parseClassBody(constructorAllowsSuper, oldStrict) {
  9690. this.classScope.enter();
  9691. const state = {
  9692. hadConstructor: false
  9693. };
  9694. let decorators = [];
  9695. const classBody = this.startNode();
  9696. classBody.body = [];
  9697. this.expect(types.braceL);
  9698. this.withTopicForbiddingContext(() => {
  9699. while (!this.match(types.braceR)) {
  9700. if (this.eat(types.semi)) {
  9701. if (decorators.length > 0) {
  9702. throw this.raise(this.state.lastTokEnd, Errors.DecoratorSemicolon);
  9703. }
  9704. continue;
  9705. }
  9706. if (this.match(types.at)) {
  9707. decorators.push(this.parseDecorator());
  9708. continue;
  9709. }
  9710. const member = this.startNode();
  9711. if (decorators.length) {
  9712. member.decorators = decorators;
  9713. this.resetStartLocationFromNode(member, decorators[0]);
  9714. decorators = [];
  9715. }
  9716. this.parseClassMember(classBody, member, state, constructorAllowsSuper);
  9717. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  9718. this.raise(member.start, Errors.DecoratorConstructor);
  9719. }
  9720. }
  9721. });
  9722. if (!oldStrict) {
  9723. this.state.strict = false;
  9724. }
  9725. this.next();
  9726. if (decorators.length) {
  9727. throw this.raise(this.state.start, Errors.TrailingDecorator);
  9728. }
  9729. this.classScope.exit();
  9730. return this.finishNode(classBody, "ClassBody");
  9731. }
  9732. parseClassMemberFromModifier(classBody, member) {
  9733. const containsEsc = this.state.containsEsc;
  9734. const key = this.parseIdentifier(true);
  9735. if (this.isClassMethod()) {
  9736. const method = member;
  9737. method.kind = "method";
  9738. method.computed = false;
  9739. method.key = key;
  9740. method.static = false;
  9741. this.pushClassMethod(classBody, method, false, false, false, false);
  9742. return true;
  9743. } else if (this.isClassProperty()) {
  9744. const prop = member;
  9745. prop.computed = false;
  9746. prop.key = key;
  9747. prop.static = false;
  9748. classBody.body.push(this.parseClassProperty(prop));
  9749. return true;
  9750. } else if (containsEsc) {
  9751. throw this.unexpected();
  9752. }
  9753. return false;
  9754. }
  9755. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  9756. const isStatic = this.isContextual("static");
  9757. if (isStatic && this.parseClassMemberFromModifier(classBody, member)) {
  9758. return;
  9759. }
  9760. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  9761. }
  9762. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  9763. const publicMethod = member;
  9764. const privateMethod = member;
  9765. const publicProp = member;
  9766. const privateProp = member;
  9767. const method = publicMethod;
  9768. const publicMember = publicMethod;
  9769. member.static = isStatic;
  9770. if (this.eat(types.star)) {
  9771. method.kind = "method";
  9772. this.parseClassPropertyName(method);
  9773. if (method.key.type === "PrivateName") {
  9774. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  9775. return;
  9776. }
  9777. if (this.isNonstaticConstructor(publicMethod)) {
  9778. this.raise(publicMethod.key.start, Errors.ConstructorIsGenerator);
  9779. }
  9780. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  9781. return;
  9782. }
  9783. const containsEsc = this.state.containsEsc;
  9784. const key = this.parseClassPropertyName(member);
  9785. const isPrivate = key.type === "PrivateName";
  9786. const isSimple = key.type === "Identifier";
  9787. const maybeQuestionTokenStart = this.state.start;
  9788. this.parsePostMemberNameModifiers(publicMember);
  9789. if (this.isClassMethod()) {
  9790. method.kind = "method";
  9791. if (isPrivate) {
  9792. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9793. return;
  9794. }
  9795. const isConstructor = this.isNonstaticConstructor(publicMethod);
  9796. let allowsDirectSuper = false;
  9797. if (isConstructor) {
  9798. publicMethod.kind = "constructor";
  9799. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  9800. this.raise(key.start, Errors.DuplicateConstructor);
  9801. }
  9802. state.hadConstructor = true;
  9803. allowsDirectSuper = constructorAllowsSuper;
  9804. }
  9805. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  9806. } else if (this.isClassProperty()) {
  9807. if (isPrivate) {
  9808. this.pushClassPrivateProperty(classBody, privateProp);
  9809. } else {
  9810. this.pushClassProperty(classBody, publicProp);
  9811. }
  9812. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  9813. const isGenerator = this.eat(types.star);
  9814. if (publicMember.optional) {
  9815. this.unexpected(maybeQuestionTokenStart);
  9816. }
  9817. method.kind = "method";
  9818. this.parseClassPropertyName(method);
  9819. this.parsePostMemberNameModifiers(publicMember);
  9820. if (method.key.type === "PrivateName") {
  9821. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  9822. } else {
  9823. if (this.isNonstaticConstructor(publicMethod)) {
  9824. this.raise(publicMethod.key.start, Errors.ConstructorIsAsync);
  9825. }
  9826. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  9827. }
  9828. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  9829. method.kind = key.name;
  9830. this.parseClassPropertyName(publicMethod);
  9831. if (method.key.type === "PrivateName") {
  9832. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9833. } else {
  9834. if (this.isNonstaticConstructor(publicMethod)) {
  9835. this.raise(publicMethod.key.start, Errors.ConstructorIsAccessor);
  9836. }
  9837. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  9838. }
  9839. this.checkGetterSetterParams(publicMethod);
  9840. } else if (this.isLineTerminator()) {
  9841. if (isPrivate) {
  9842. this.pushClassPrivateProperty(classBody, privateProp);
  9843. } else {
  9844. this.pushClassProperty(classBody, publicProp);
  9845. }
  9846. } else {
  9847. this.unexpected();
  9848. }
  9849. }
  9850. parseClassPropertyName(member) {
  9851. const key = this.parsePropertyName(member, true);
  9852. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  9853. this.raise(key.start, Errors.StaticPrototype);
  9854. }
  9855. if (key.type === "PrivateName" && key.id.name === "constructor") {
  9856. this.raise(key.start, Errors.ConstructorClassPrivateField);
  9857. }
  9858. return key;
  9859. }
  9860. pushClassProperty(classBody, prop) {
  9861. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  9862. this.raise(prop.key.start, Errors.ConstructorClassField);
  9863. }
  9864. classBody.body.push(this.parseClassProperty(prop));
  9865. }
  9866. pushClassPrivateProperty(classBody, prop) {
  9867. this.expectPlugin("classPrivateProperties", prop.key.start);
  9868. const node = this.parseClassPrivateProperty(prop);
  9869. classBody.body.push(node);
  9870. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  9871. }
  9872. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9873. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  9874. }
  9875. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9876. this.expectPlugin("classPrivateMethods", method.key.start);
  9877. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  9878. classBody.body.push(node);
  9879. 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;
  9880. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  9881. }
  9882. parsePostMemberNameModifiers(methodOrProp) {}
  9883. parseAccessModifier() {
  9884. return undefined;
  9885. }
  9886. parseClassPrivateProperty(node) {
  9887. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9888. this.prodParam.enter(PARAM);
  9889. node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null;
  9890. this.semicolon();
  9891. this.prodParam.exit();
  9892. this.scope.exit();
  9893. return this.finishNode(node, "ClassPrivateProperty");
  9894. }
  9895. parseClassProperty(node) {
  9896. if (!node.typeAnnotation) {
  9897. this.expectPlugin("classProperties");
  9898. }
  9899. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9900. this.prodParam.enter(PARAM);
  9901. if (this.match(types.eq)) {
  9902. this.expectPlugin("classProperties");
  9903. this.next();
  9904. node.value = this.parseMaybeAssign();
  9905. } else {
  9906. node.value = null;
  9907. }
  9908. this.semicolon();
  9909. this.prodParam.exit();
  9910. this.scope.exit();
  9911. return this.finishNode(node, "ClassProperty");
  9912. }
  9913. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  9914. if (this.match(types.name)) {
  9915. node.id = this.parseIdentifier();
  9916. if (isStatement) {
  9917. this.checkLVal(node.id, bindingType, undefined, "class name");
  9918. }
  9919. } else {
  9920. if (optionalId || !isStatement) {
  9921. node.id = null;
  9922. } else {
  9923. this.unexpected(null, Errors.MissingClassName);
  9924. }
  9925. }
  9926. }
  9927. parseClassSuper(node) {
  9928. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  9929. }
  9930. parseExport(node) {
  9931. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  9932. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  9933. const hasStar = parseAfterDefault && this.eatExportStar(node);
  9934. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  9935. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  9936. const isFromRequired = hasDefault || hasStar;
  9937. if (hasStar && !hasNamespace) {
  9938. if (hasDefault) this.unexpected();
  9939. this.parseExportFrom(node, true);
  9940. return this.finishNode(node, "ExportAllDeclaration");
  9941. }
  9942. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  9943. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  9944. throw this.unexpected(null, types.braceL);
  9945. }
  9946. let hasDeclaration;
  9947. if (isFromRequired || hasSpecifiers) {
  9948. hasDeclaration = false;
  9949. this.parseExportFrom(node, isFromRequired);
  9950. } else {
  9951. hasDeclaration = this.maybeParseExportDeclaration(node);
  9952. }
  9953. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  9954. this.checkExport(node, true, false, !!node.source);
  9955. return this.finishNode(node, "ExportNamedDeclaration");
  9956. }
  9957. if (this.eat(types._default)) {
  9958. node.declaration = this.parseExportDefaultExpression();
  9959. this.checkExport(node, true, true);
  9960. return this.finishNode(node, "ExportDefaultDeclaration");
  9961. }
  9962. throw this.unexpected(null, types.braceL);
  9963. }
  9964. eatExportStar(node) {
  9965. return this.eat(types.star);
  9966. }
  9967. maybeParseExportDefaultSpecifier(node) {
  9968. if (this.isExportDefaultSpecifier()) {
  9969. this.expectPlugin("exportDefaultFrom");
  9970. const specifier = this.startNode();
  9971. specifier.exported = this.parseIdentifier(true);
  9972. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9973. return true;
  9974. }
  9975. return false;
  9976. }
  9977. maybeParseExportNamespaceSpecifier(node) {
  9978. if (this.isContextual("as")) {
  9979. if (!node.specifiers) node.specifiers = [];
  9980. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  9981. this.next();
  9982. specifier.exported = this.parseIdentifier(true);
  9983. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  9984. return true;
  9985. }
  9986. return false;
  9987. }
  9988. maybeParseExportNamedSpecifiers(node) {
  9989. if (this.match(types.braceL)) {
  9990. if (!node.specifiers) node.specifiers = [];
  9991. node.specifiers.push(...this.parseExportSpecifiers());
  9992. node.source = null;
  9993. node.declaration = null;
  9994. return true;
  9995. }
  9996. return false;
  9997. }
  9998. maybeParseExportDeclaration(node) {
  9999. if (this.shouldParseExportDeclaration()) {
  10000. if (this.isContextual("async")) {
  10001. const next = this.nextTokenStart();
  10002. if (!this.isUnparsedContextual(next, "function")) {
  10003. this.unexpected(next, types._function);
  10004. }
  10005. }
  10006. node.specifiers = [];
  10007. node.source = null;
  10008. node.declaration = this.parseExportDeclaration(node);
  10009. return true;
  10010. }
  10011. return false;
  10012. }
  10013. isAsyncFunction() {
  10014. if (!this.isContextual("async")) return false;
  10015. const next = this.nextTokenStart();
  10016. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10017. }
  10018. parseExportDefaultExpression() {
  10019. const expr = this.startNode();
  10020. const isAsync = this.isAsyncFunction();
  10021. if (this.match(types._function) || isAsync) {
  10022. this.next();
  10023. if (isAsync) {
  10024. this.next();
  10025. }
  10026. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10027. } else if (this.match(types._class)) {
  10028. return this.parseClass(expr, true, true);
  10029. } else if (this.match(types.at)) {
  10030. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10031. this.raise(this.state.start, Errors.DecoratorBeforeExport);
  10032. }
  10033. this.parseDecorators(false);
  10034. return this.parseClass(expr, true, true);
  10035. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10036. throw this.raise(this.state.start, Errors.UnsupportedDefaultExport);
  10037. } else {
  10038. const res = this.parseMaybeAssign();
  10039. this.semicolon();
  10040. return res;
  10041. }
  10042. }
  10043. parseExportDeclaration(node) {
  10044. return this.parseStatement(null);
  10045. }
  10046. isExportDefaultSpecifier() {
  10047. if (this.match(types.name)) {
  10048. return this.state.value !== "async" && this.state.value !== "let";
  10049. }
  10050. if (!this.match(types._default)) {
  10051. return false;
  10052. }
  10053. const next = this.nextTokenStart();
  10054. return this.input.charCodeAt(next) === 44 || this.isUnparsedContextual(next, "from");
  10055. }
  10056. parseExportFrom(node, expect) {
  10057. if (this.eatContextual("from")) {
  10058. node.source = this.parseImportSource();
  10059. this.checkExport(node);
  10060. } else {
  10061. if (expect) {
  10062. this.unexpected();
  10063. } else {
  10064. node.source = null;
  10065. }
  10066. }
  10067. this.semicolon();
  10068. }
  10069. shouldParseExportDeclaration() {
  10070. if (this.match(types.at)) {
  10071. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  10072. if (this.hasPlugin("decorators")) {
  10073. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10074. this.unexpected(this.state.start, Errors.DecoratorBeforeExport);
  10075. } else {
  10076. return true;
  10077. }
  10078. }
  10079. }
  10080. 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();
  10081. }
  10082. checkExport(node, checkNames, isDefault, isFrom) {
  10083. if (checkNames) {
  10084. if (isDefault) {
  10085. this.checkDuplicateExports(node, "default");
  10086. } else if (node.specifiers && node.specifiers.length) {
  10087. for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
  10088. const specifier = _node$specifiers[_i4];
  10089. this.checkDuplicateExports(specifier, specifier.exported.name);
  10090. if (!isFrom && specifier.local) {
  10091. this.checkReservedWord(specifier.local.name, specifier.local.start, true, false);
  10092. this.scope.checkLocalExport(specifier.local);
  10093. }
  10094. }
  10095. } else if (node.declaration) {
  10096. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  10097. const id = node.declaration.id;
  10098. if (!id) throw new Error("Assertion failure");
  10099. this.checkDuplicateExports(node, id.name);
  10100. } else if (node.declaration.type === "VariableDeclaration") {
  10101. for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
  10102. const declaration = _node$declaration$dec[_i5];
  10103. this.checkDeclaration(declaration.id);
  10104. }
  10105. }
  10106. }
  10107. }
  10108. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10109. if (currentContextDecorators.length) {
  10110. const isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
  10111. if (!node.declaration || !isClass) {
  10112. throw this.raise(node.start, Errors.UnsupportedDecoratorExport);
  10113. }
  10114. this.takeDecorators(node.declaration);
  10115. }
  10116. }
  10117. checkDeclaration(node) {
  10118. if (node.type === "Identifier") {
  10119. this.checkDuplicateExports(node, node.name);
  10120. } else if (node.type === "ObjectPattern") {
  10121. for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
  10122. const prop = _node$properties[_i6];
  10123. this.checkDeclaration(prop);
  10124. }
  10125. } else if (node.type === "ArrayPattern") {
  10126. for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
  10127. const elem = _node$elements[_i7];
  10128. if (elem) {
  10129. this.checkDeclaration(elem);
  10130. }
  10131. }
  10132. } else if (node.type === "ObjectProperty") {
  10133. this.checkDeclaration(node.value);
  10134. } else if (node.type === "RestElement") {
  10135. this.checkDeclaration(node.argument);
  10136. } else if (node.type === "AssignmentPattern") {
  10137. this.checkDeclaration(node.left);
  10138. }
  10139. }
  10140. checkDuplicateExports(node, name) {
  10141. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  10142. this.raise(node.start, name === "default" ? Errors.DuplicateDefaultExport : Errors.DuplicateExport, name);
  10143. }
  10144. this.state.exportedIdentifiers.push(name);
  10145. }
  10146. parseExportSpecifiers() {
  10147. const nodes = [];
  10148. let first = true;
  10149. this.expect(types.braceL);
  10150. while (!this.eat(types.braceR)) {
  10151. if (first) {
  10152. first = false;
  10153. } else {
  10154. this.expect(types.comma);
  10155. if (this.eat(types.braceR)) break;
  10156. }
  10157. const node = this.startNode();
  10158. node.local = this.parseIdentifier(true);
  10159. node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
  10160. nodes.push(this.finishNode(node, "ExportSpecifier"));
  10161. }
  10162. return nodes;
  10163. }
  10164. parseImport(node) {
  10165. node.specifiers = [];
  10166. if (!this.match(types.string)) {
  10167. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  10168. const parseNext = !hasDefault || this.eat(types.comma);
  10169. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  10170. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  10171. this.expectContextual("from");
  10172. }
  10173. node.source = this.parseImportSource();
  10174. this.semicolon();
  10175. return this.finishNode(node, "ImportDeclaration");
  10176. }
  10177. parseImportSource() {
  10178. if (!this.match(types.string)) this.unexpected();
  10179. return this.parseExprAtom();
  10180. }
  10181. shouldParseDefaultImport(node) {
  10182. return this.match(types.name);
  10183. }
  10184. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  10185. specifier.local = this.parseIdentifier();
  10186. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  10187. node.specifiers.push(this.finishNode(specifier, type));
  10188. }
  10189. maybeParseDefaultImportSpecifier(node) {
  10190. if (this.shouldParseDefaultImport(node)) {
  10191. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  10192. return true;
  10193. }
  10194. return false;
  10195. }
  10196. maybeParseStarImportSpecifier(node) {
  10197. if (this.match(types.star)) {
  10198. const specifier = this.startNode();
  10199. this.next();
  10200. this.expectContextual("as");
  10201. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  10202. return true;
  10203. }
  10204. return false;
  10205. }
  10206. parseNamedImportSpecifiers(node) {
  10207. let first = true;
  10208. this.expect(types.braceL);
  10209. while (!this.eat(types.braceR)) {
  10210. if (first) {
  10211. first = false;
  10212. } else {
  10213. if (this.eat(types.colon)) {
  10214. throw this.raise(this.state.start, Errors.DestructureNamedImport);
  10215. }
  10216. this.expect(types.comma);
  10217. if (this.eat(types.braceR)) break;
  10218. }
  10219. this.parseImportSpecifier(node);
  10220. }
  10221. }
  10222. parseImportSpecifier(node) {
  10223. const specifier = this.startNode();
  10224. specifier.imported = this.parseIdentifier(true);
  10225. if (this.eatContextual("as")) {
  10226. specifier.local = this.parseIdentifier();
  10227. } else {
  10228. this.checkReservedWord(specifier.imported.name, specifier.start, true, true);
  10229. specifier.local = specifier.imported.__clone();
  10230. }
  10231. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  10232. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  10233. }
  10234. }
  10235. class ClassScope {
  10236. constructor() {
  10237. this.privateNames = new Set();
  10238. this.loneAccessors = new Map();
  10239. this.undefinedPrivateNames = new Map();
  10240. }
  10241. }
  10242. class ClassScopeHandler {
  10243. constructor(raise) {
  10244. this.stack = [];
  10245. this.undefinedPrivateNames = new Map();
  10246. this.raise = raise;
  10247. }
  10248. current() {
  10249. return this.stack[this.stack.length - 1];
  10250. }
  10251. enter() {
  10252. this.stack.push(new ClassScope());
  10253. }
  10254. exit() {
  10255. const oldClassScope = this.stack.pop();
  10256. const current = this.current();
  10257. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  10258. const [name, pos] = _Array$from[_i];
  10259. if (current) {
  10260. if (!current.undefinedPrivateNames.has(name)) {
  10261. current.undefinedPrivateNames.set(name, pos);
  10262. }
  10263. } else {
  10264. this.raise(pos, Errors.InvalidPrivateFieldResolution, name);
  10265. }
  10266. }
  10267. }
  10268. declarePrivateName(name, elementType, pos) {
  10269. const classScope = this.current();
  10270. let redefined = classScope.privateNames.has(name);
  10271. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  10272. const accessor = redefined && classScope.loneAccessors.get(name);
  10273. if (accessor) {
  10274. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  10275. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  10276. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  10277. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  10278. redefined = oldKind === newKind || oldStatic !== newStatic;
  10279. if (!redefined) classScope.loneAccessors.delete(name);
  10280. } else if (!redefined) {
  10281. classScope.loneAccessors.set(name, elementType);
  10282. }
  10283. }
  10284. if (redefined) {
  10285. this.raise(pos, Errors.PrivateNameRedeclaration, name);
  10286. }
  10287. classScope.privateNames.add(name);
  10288. classScope.undefinedPrivateNames.delete(name);
  10289. }
  10290. usePrivateName(name, pos) {
  10291. let classScope;
  10292. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  10293. classScope = _this$stack[_i2];
  10294. if (classScope.privateNames.has(name)) return;
  10295. }
  10296. if (classScope) {
  10297. classScope.undefinedPrivateNames.set(name, pos);
  10298. } else {
  10299. this.raise(pos, Errors.InvalidPrivateFieldResolution, name);
  10300. }
  10301. }
  10302. }
  10303. class Parser extends StatementParser {
  10304. constructor(options, input) {
  10305. options = getOptions(options);
  10306. super(options, input);
  10307. const ScopeHandler = this.getScopeHandler();
  10308. this.options = options;
  10309. this.inModule = this.options.sourceType === "module";
  10310. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  10311. this.prodParam = new ProductionParameterHandler();
  10312. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  10313. this.plugins = pluginsMap(this.options.plugins);
  10314. this.filename = options.sourceFilename;
  10315. }
  10316. getScopeHandler() {
  10317. return ScopeHandler;
  10318. }
  10319. parse() {
  10320. let paramFlags = PARAM;
  10321. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  10322. paramFlags |= PARAM_AWAIT;
  10323. }
  10324. this.scope.enter(SCOPE_PROGRAM);
  10325. this.prodParam.enter(paramFlags);
  10326. const file = this.startNode();
  10327. const program = this.startNode();
  10328. this.nextToken();
  10329. file.errors = null;
  10330. this.parseTopLevel(file, program);
  10331. file.errors = this.state.errors;
  10332. return file;
  10333. }
  10334. }
  10335. function pluginsMap(plugins) {
  10336. const pluginMap = new Map();
  10337. for (let _i = 0; _i < plugins.length; _i++) {
  10338. const plugin = plugins[_i];
  10339. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  10340. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  10341. }
  10342. return pluginMap;
  10343. }
  10344. function parse(input, options) {
  10345. if (options && options.sourceType === "unambiguous") {
  10346. options = Object.assign({}, options);
  10347. try {
  10348. options.sourceType = "module";
  10349. const parser = getParser(options, input);
  10350. const ast = parser.parse();
  10351. if (parser.sawUnambiguousESM) {
  10352. return ast;
  10353. }
  10354. if (parser.ambiguousScriptDifferentAst) {
  10355. try {
  10356. options.sourceType = "script";
  10357. return getParser(options, input).parse();
  10358. } catch (_unused) {}
  10359. } else {
  10360. ast.program.sourceType = "script";
  10361. }
  10362. return ast;
  10363. } catch (moduleError) {
  10364. try {
  10365. options.sourceType = "script";
  10366. return getParser(options, input).parse();
  10367. } catch (_unused2) {}
  10368. throw moduleError;
  10369. }
  10370. } else {
  10371. return getParser(options, input).parse();
  10372. }
  10373. }
  10374. function parseExpression(input, options) {
  10375. const parser = getParser(options, input);
  10376. if (parser.options.strictMode) {
  10377. parser.state.strict = true;
  10378. }
  10379. return parser.getExpression();
  10380. }
  10381. function getParser(options, input) {
  10382. let cls = Parser;
  10383. if (options && options.plugins) {
  10384. validatePlugins(options.plugins);
  10385. cls = getParserClass(options.plugins);
  10386. }
  10387. return new cls(options, input);
  10388. }
  10389. const parserClassCache = {};
  10390. function getParserClass(pluginsFromOptions) {
  10391. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  10392. const key = pluginList.join("/");
  10393. let cls = parserClassCache[key];
  10394. if (!cls) {
  10395. cls = Parser;
  10396. for (let _i = 0; _i < pluginList.length; _i++) {
  10397. const plugin = pluginList[_i];
  10398. cls = mixinPlugins[plugin](cls);
  10399. }
  10400. parserClassCache[key] = cls;
  10401. }
  10402. return cls;
  10403. }
  10404. exports.parse = parse;
  10405. exports.parseExpression = parseExpression;
  10406. exports.tokTypes = types;
  10407. //# sourceMappingURL=index.js.map