index.js 327 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293
  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. bracketR: new TokenType("]"),
  59. braceL: new TokenType("{", {
  60. beforeExpr,
  61. startsExpr
  62. }),
  63. braceBarL: new TokenType("{|", {
  64. beforeExpr,
  65. startsExpr
  66. }),
  67. braceR: new TokenType("}"),
  68. braceBarR: new TokenType("|}"),
  69. parenL: new TokenType("(", {
  70. beforeExpr,
  71. startsExpr
  72. }),
  73. parenR: new TokenType(")"),
  74. comma: new TokenType(",", {
  75. beforeExpr
  76. }),
  77. semi: new TokenType(";", {
  78. beforeExpr
  79. }),
  80. colon: new TokenType(":", {
  81. beforeExpr
  82. }),
  83. doubleColon: new TokenType("::", {
  84. beforeExpr
  85. }),
  86. dot: new TokenType("."),
  87. question: new TokenType("?", {
  88. beforeExpr
  89. }),
  90. questionDot: new TokenType("?."),
  91. arrow: new TokenType("=>", {
  92. beforeExpr
  93. }),
  94. template: new TokenType("template"),
  95. ellipsis: new TokenType("...", {
  96. beforeExpr
  97. }),
  98. backQuote: new TokenType("`", {
  99. startsExpr
  100. }),
  101. dollarBraceL: new TokenType("${", {
  102. beforeExpr,
  103. startsExpr
  104. }),
  105. at: new TokenType("@"),
  106. hash: new TokenType("#", {
  107. startsExpr
  108. }),
  109. interpreterDirective: new TokenType("#!..."),
  110. eq: new TokenType("=", {
  111. beforeExpr,
  112. isAssign
  113. }),
  114. assign: new TokenType("_=", {
  115. beforeExpr,
  116. isAssign
  117. }),
  118. incDec: new TokenType("++/--", {
  119. prefix,
  120. postfix,
  121. startsExpr
  122. }),
  123. bang: new TokenType("!", {
  124. beforeExpr,
  125. prefix,
  126. startsExpr
  127. }),
  128. tilde: new TokenType("~", {
  129. beforeExpr,
  130. prefix,
  131. startsExpr
  132. }),
  133. pipeline: createBinop("|>", 0),
  134. nullishCoalescing: createBinop("??", 1),
  135. logicalOR: createBinop("||", 1),
  136. logicalAND: createBinop("&&", 2),
  137. bitwiseOR: createBinop("|", 3),
  138. bitwiseXOR: createBinop("^", 4),
  139. bitwiseAND: createBinop("&", 5),
  140. equality: createBinop("==/!=/===/!==", 6),
  141. relational: createBinop("</>/<=/>=", 7),
  142. bitShift: createBinop("<</>>/>>>", 8),
  143. plusMin: new TokenType("+/-", {
  144. beforeExpr,
  145. binop: 9,
  146. prefix,
  147. startsExpr
  148. }),
  149. modulo: createBinop("%", 10),
  150. star: createBinop("*", 10),
  151. slash: createBinop("/", 10),
  152. exponent: new TokenType("**", {
  153. beforeExpr,
  154. binop: 11,
  155. rightAssociative: true
  156. }),
  157. _break: createKeyword("break"),
  158. _case: createKeyword("case", {
  159. beforeExpr
  160. }),
  161. _catch: createKeyword("catch"),
  162. _continue: createKeyword("continue"),
  163. _debugger: createKeyword("debugger"),
  164. _default: createKeyword("default", {
  165. beforeExpr
  166. }),
  167. _do: createKeyword("do", {
  168. isLoop,
  169. beforeExpr
  170. }),
  171. _else: createKeyword("else", {
  172. beforeExpr
  173. }),
  174. _finally: createKeyword("finally"),
  175. _for: createKeyword("for", {
  176. isLoop
  177. }),
  178. _function: createKeyword("function", {
  179. startsExpr
  180. }),
  181. _if: createKeyword("if"),
  182. _return: createKeyword("return", {
  183. beforeExpr
  184. }),
  185. _switch: createKeyword("switch"),
  186. _throw: createKeyword("throw", {
  187. beforeExpr,
  188. prefix,
  189. startsExpr
  190. }),
  191. _try: createKeyword("try"),
  192. _var: createKeyword("var"),
  193. _const: createKeyword("const"),
  194. _while: createKeyword("while", {
  195. isLoop
  196. }),
  197. _with: createKeyword("with"),
  198. _new: createKeyword("new", {
  199. beforeExpr,
  200. startsExpr
  201. }),
  202. _this: createKeyword("this", {
  203. startsExpr
  204. }),
  205. _super: createKeyword("super", {
  206. startsExpr
  207. }),
  208. _class: createKeyword("class", {
  209. startsExpr
  210. }),
  211. _extends: createKeyword("extends", {
  212. beforeExpr
  213. }),
  214. _export: createKeyword("export"),
  215. _import: createKeyword("import", {
  216. startsExpr
  217. }),
  218. _null: createKeyword("null", {
  219. startsExpr
  220. }),
  221. _true: createKeyword("true", {
  222. startsExpr
  223. }),
  224. _false: createKeyword("false", {
  225. startsExpr
  226. }),
  227. _in: createKeyword("in", {
  228. beforeExpr,
  229. binop: 7
  230. }),
  231. _instanceof: createKeyword("instanceof", {
  232. beforeExpr,
  233. binop: 7
  234. }),
  235. _typeof: createKeyword("typeof", {
  236. beforeExpr,
  237. prefix,
  238. startsExpr
  239. }),
  240. _void: createKeyword("void", {
  241. beforeExpr,
  242. prefix,
  243. startsExpr
  244. }),
  245. _delete: createKeyword("delete", {
  246. beforeExpr,
  247. prefix,
  248. startsExpr
  249. })
  250. };
  251. const SCOPE_OTHER = 0b000000000,
  252. SCOPE_PROGRAM = 0b000000001,
  253. SCOPE_FUNCTION = 0b000000010,
  254. SCOPE_ASYNC = 0b000000100,
  255. SCOPE_GENERATOR = 0b000001000,
  256. SCOPE_ARROW = 0b000010000,
  257. SCOPE_SIMPLE_CATCH = 0b000100000,
  258. SCOPE_SUPER = 0b001000000,
  259. SCOPE_DIRECT_SUPER = 0b010000000,
  260. SCOPE_CLASS = 0b100000000,
  261. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION;
  262. function functionFlags(isAsync, isGenerator) {
  263. return SCOPE_FUNCTION | (isAsync ? SCOPE_ASYNC : 0) | (isGenerator ? SCOPE_GENERATOR : 0);
  264. }
  265. const BIND_KIND_VALUE = 0b00000000001,
  266. BIND_KIND_TYPE = 0b00000000010,
  267. BIND_SCOPE_VAR = 0b00000000100,
  268. BIND_SCOPE_LEXICAL = 0b00000001000,
  269. BIND_SCOPE_FUNCTION = 0b00000010000,
  270. BIND_FLAGS_NONE = 0b00001000000,
  271. BIND_FLAGS_CLASS = 0b00010000000,
  272. BIND_FLAGS_TS_ENUM = 0b00100000000,
  273. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  274. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  275. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  276. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  277. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  278. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  279. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  280. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  281. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  282. BIND_TS_FN_TYPE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  283. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  284. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  285. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  286. BIND_TS_NAMESPACE = BIND_TS_FN_TYPE;
  287. function isSimpleProperty(node) {
  288. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  289. }
  290. var estree = (superClass => class extends superClass {
  291. estreeParseRegExpLiteral({
  292. pattern,
  293. flags
  294. }) {
  295. let regex = null;
  296. try {
  297. regex = new RegExp(pattern, flags);
  298. } catch (e) {}
  299. const node = this.estreeParseLiteral(regex);
  300. node.regex = {
  301. pattern,
  302. flags
  303. };
  304. return node;
  305. }
  306. estreeParseLiteral(value) {
  307. return this.parseLiteral(value, "Literal");
  308. }
  309. directiveToStmt(directive) {
  310. const directiveLiteral = directive.value;
  311. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  312. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  313. expression.value = directiveLiteral.value;
  314. expression.raw = directiveLiteral.extra.raw;
  315. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  316. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  317. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  318. }
  319. initFunction(node, isAsync) {
  320. super.initFunction(node, isAsync);
  321. node.expression = false;
  322. }
  323. checkDeclaration(node) {
  324. if (isSimpleProperty(node)) {
  325. this.checkDeclaration(node.value);
  326. } else {
  327. super.checkDeclaration(node);
  328. }
  329. }
  330. checkGetterSetterParams(method) {
  331. const prop = method;
  332. const paramCount = prop.kind === "get" ? 0 : 1;
  333. const start = prop.start;
  334. if (prop.value.params.length !== paramCount) {
  335. if (prop.kind === "get") {
  336. this.raise(start, "getter must not have any formal parameters");
  337. } else {
  338. this.raise(start, "setter must have exactly one formal parameter");
  339. }
  340. }
  341. if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
  342. this.raise(start, "setter function argument must not be a rest parameter");
  343. }
  344. }
  345. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  346. switch (expr.type) {
  347. case "ObjectPattern":
  348. expr.properties.forEach(prop => {
  349. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern");
  350. });
  351. break;
  352. default:
  353. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  354. }
  355. }
  356. checkPropClash(prop, propHash) {
  357. if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) {
  358. return;
  359. }
  360. const key = prop.key;
  361. const name = key.type === "Identifier" ? key.name : String(key.value);
  362. if (name === "__proto__" && prop.kind === "init") {
  363. if (propHash.proto) {
  364. this.raise(key.start, "Redefinition of __proto__ property");
  365. }
  366. propHash.proto = true;
  367. }
  368. }
  369. isStrictBody(node) {
  370. const isBlockStatement = node.body.type === "BlockStatement";
  371. if (isBlockStatement && node.body.body.length > 0) {
  372. for (let _i = 0, _node$body$body = node.body.body; _i < _node$body$body.length; _i++) {
  373. const directive = _node$body$body[_i];
  374. if (directive.type === "ExpressionStatement" && directive.expression.type === "Literal") {
  375. if (directive.expression.value === "use strict") return true;
  376. } else {
  377. break;
  378. }
  379. }
  380. }
  381. return false;
  382. }
  383. isValidDirective(stmt) {
  384. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized);
  385. }
  386. stmtToDirective(stmt) {
  387. const directive = super.stmtToDirective(stmt);
  388. const value = stmt.expression.value;
  389. directive.value.value = value;
  390. return directive;
  391. }
  392. parseBlockBody(node, allowDirectives, topLevel, end) {
  393. super.parseBlockBody(node, allowDirectives, topLevel, end);
  394. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  395. node.body = directiveStatements.concat(node.body);
  396. delete node.directives;
  397. }
  398. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  399. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  400. if (method.typeParameters) {
  401. method.value.typeParameters = method.typeParameters;
  402. delete method.typeParameters;
  403. }
  404. classBody.body.push(method);
  405. }
  406. parseExprAtom(refShorthandDefaultPos) {
  407. switch (this.state.type) {
  408. case types.regexp:
  409. return this.estreeParseRegExpLiteral(this.state.value);
  410. case types.num:
  411. case types.string:
  412. return this.estreeParseLiteral(this.state.value);
  413. case types._null:
  414. return this.estreeParseLiteral(null);
  415. case types._true:
  416. return this.estreeParseLiteral(true);
  417. case types._false:
  418. return this.estreeParseLiteral(false);
  419. default:
  420. return super.parseExprAtom(refShorthandDefaultPos);
  421. }
  422. }
  423. parseLiteral(value, type, startPos, startLoc) {
  424. const node = super.parseLiteral(value, type, startPos, startLoc);
  425. node.raw = node.extra.raw;
  426. delete node.extra;
  427. return node;
  428. }
  429. parseFunctionBody(node, allowExpression, isMethod = false) {
  430. super.parseFunctionBody(node, allowExpression, isMethod);
  431. node.expression = node.body.type !== "BlockStatement";
  432. }
  433. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  434. let funcNode = this.startNode();
  435. funcNode.kind = node.kind;
  436. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  437. funcNode.type = "FunctionExpression";
  438. delete funcNode.kind;
  439. node.value = funcNode;
  440. type = type === "ClassMethod" ? "MethodDefinition" : type;
  441. return this.finishNode(node, type);
  442. }
  443. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  444. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc);
  445. if (node) {
  446. node.type = "Property";
  447. if (node.kind === "method") node.kind = "init";
  448. node.shorthand = false;
  449. }
  450. return node;
  451. }
  452. parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) {
  453. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos);
  454. if (node) {
  455. node.kind = "init";
  456. node.type = "Property";
  457. }
  458. return node;
  459. }
  460. toAssignable(node, isBinding, contextDescription) {
  461. if (isSimpleProperty(node)) {
  462. this.toAssignable(node.value, isBinding, contextDescription);
  463. return node;
  464. }
  465. return super.toAssignable(node, isBinding, contextDescription);
  466. }
  467. toAssignableObjectExpressionProp(prop, isBinding, isLast) {
  468. if (prop.kind === "get" || prop.kind === "set") {
  469. this.raise(prop.key.start, "Object pattern can't contain getter or setter");
  470. } else if (prop.method) {
  471. this.raise(prop.key.start, "Object pattern can't contain methods");
  472. } else {
  473. super.toAssignableObjectExpressionProp(prop, isBinding, isLast);
  474. }
  475. }
  476. });
  477. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  478. const lineBreakG = new RegExp(lineBreak.source, "g");
  479. function isNewLine(code) {
  480. switch (code) {
  481. case 10:
  482. case 13:
  483. case 8232:
  484. case 8233:
  485. return true;
  486. default:
  487. return false;
  488. }
  489. }
  490. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  491. function isWhitespace(code) {
  492. switch (code) {
  493. case 0x0009:
  494. case 0x000b:
  495. case 0x000c:
  496. case 32:
  497. case 160:
  498. case 5760:
  499. case 0x2000:
  500. case 0x2001:
  501. case 0x2002:
  502. case 0x2003:
  503. case 0x2004:
  504. case 0x2005:
  505. case 0x2006:
  506. case 0x2007:
  507. case 0x2008:
  508. case 0x2009:
  509. case 0x200a:
  510. case 0x202f:
  511. case 0x205f:
  512. case 0x3000:
  513. case 0xfeff:
  514. return true;
  515. default:
  516. return false;
  517. }
  518. }
  519. class TokContext {
  520. constructor(token, isExpr, preserveSpace, override) {
  521. this.token = token;
  522. this.isExpr = !!isExpr;
  523. this.preserveSpace = !!preserveSpace;
  524. this.override = override;
  525. }
  526. }
  527. const types$1 = {
  528. braceStatement: new TokContext("{", false),
  529. braceExpression: new TokContext("{", true),
  530. templateQuasi: new TokContext("${", false),
  531. parenStatement: new TokContext("(", false),
  532. parenExpression: new TokContext("(", true),
  533. template: new TokContext("`", true, true, p => p.readTmplToken()),
  534. functionExpression: new TokContext("function", true),
  535. functionStatement: new TokContext("function", false)
  536. };
  537. types.parenR.updateContext = types.braceR.updateContext = function () {
  538. if (this.state.context.length === 1) {
  539. this.state.exprAllowed = true;
  540. return;
  541. }
  542. let out = this.state.context.pop();
  543. if (out === types$1.braceStatement && this.curContext().token === "function") {
  544. out = this.state.context.pop();
  545. }
  546. this.state.exprAllowed = !out.isExpr;
  547. };
  548. types.name.updateContext = function (prevType) {
  549. let allowed = false;
  550. if (prevType !== types.dot) {
  551. if (this.state.value === "of" && !this.state.exprAllowed || this.state.value === "yield" && this.scope.inGenerator) {
  552. allowed = true;
  553. }
  554. }
  555. this.state.exprAllowed = allowed;
  556. if (this.state.isIterator) {
  557. this.state.isIterator = false;
  558. }
  559. };
  560. types.braceL.updateContext = function (prevType) {
  561. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  562. this.state.exprAllowed = true;
  563. };
  564. types.dollarBraceL.updateContext = function () {
  565. this.state.context.push(types$1.templateQuasi);
  566. this.state.exprAllowed = true;
  567. };
  568. types.parenL.updateContext = function (prevType) {
  569. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  570. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  571. this.state.exprAllowed = true;
  572. };
  573. types.incDec.updateContext = function () {};
  574. types._function.updateContext = types._class.updateContext = function (prevType) {
  575. 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)) {
  576. this.state.context.push(types$1.functionExpression);
  577. } else {
  578. this.state.context.push(types$1.functionStatement);
  579. }
  580. this.state.exprAllowed = false;
  581. };
  582. types.backQuote.updateContext = function () {
  583. if (this.curContext() === types$1.template) {
  584. this.state.context.pop();
  585. } else {
  586. this.state.context.push(types$1.template);
  587. }
  588. this.state.exprAllowed = false;
  589. };
  590. const reservedWords = {
  591. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  592. strictBind: ["eval", "arguments"]
  593. };
  594. const reservedWordsStrictSet = new Set(reservedWords.strict);
  595. const reservedWordsStrictBindSet = new Set(reservedWords.strict.concat(reservedWords.strictBind));
  596. const isReservedWord = (word, inModule) => {
  597. return inModule && word === "await" || word === "enum";
  598. };
  599. function isStrictReservedWord(word, inModule) {
  600. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  601. }
  602. function isStrictBindReservedWord(word, inModule) {
  603. return isReservedWord(word, inModule) || reservedWordsStrictBindSet.has(word);
  604. }
  605. function isKeyword(word) {
  606. return keywords.has(word);
  607. }
  608. const keywordRelationalOperator = /^in(stanceof)?$/;
  609. 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-\u08bd\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\u0d05-\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-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\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-\uab67\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";
  610. 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\u0b56\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\u0d82\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\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\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";
  611. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  612. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  613. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  614. 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, 477, 28, 11, 0, 9, 21, 155, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 12, 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, 0, 33, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 0, 161, 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, 270, 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, 754, 9486, 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, 42710, 42, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541];
  615. 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, 525, 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, 4, 9, 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, 232, 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, 19723, 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, 792487, 239];
  616. function isInAstralSet(code, set) {
  617. let pos = 0x10000;
  618. for (let i = 0, length = set.length; i < length; i += 2) {
  619. pos += set[i];
  620. if (pos > code) return false;
  621. pos += set[i + 1];
  622. if (pos >= code) return true;
  623. }
  624. return false;
  625. }
  626. function isIdentifierStart(code) {
  627. if (code < 65) return code === 36;
  628. if (code <= 90) return true;
  629. if (code < 97) return code === 95;
  630. if (code <= 122) return true;
  631. if (code <= 0xffff) {
  632. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  633. }
  634. return isInAstralSet(code, astralIdentifierStartCodes);
  635. }
  636. function isIteratorStart(current, next) {
  637. return current === 64 && next === 64;
  638. }
  639. function isIdentifierChar(code) {
  640. if (code < 48) return code === 36;
  641. if (code < 58) return true;
  642. if (code < 65) return false;
  643. if (code <= 90) return true;
  644. if (code < 97) return code === 95;
  645. if (code <= 122) return true;
  646. if (code <= 0xffff) {
  647. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  648. }
  649. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  650. }
  651. const reservedTypes = ["any", "bool", "boolean", "empty", "false", "mixed", "null", "number", "static", "string", "true", "typeof", "void", "interface", "extends", "_"];
  652. function isEsModuleType(bodyElement) {
  653. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  654. }
  655. function hasTypeImportKind(node) {
  656. return node.importKind === "type" || node.importKind === "typeof";
  657. }
  658. function isMaybeDefaultImport(state) {
  659. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  660. }
  661. const exportSuggestions = {
  662. const: "declare export var",
  663. let: "declare export var",
  664. type: "export type",
  665. interface: "export interface"
  666. };
  667. function partition(list, test) {
  668. const list1 = [];
  669. const list2 = [];
  670. for (let i = 0; i < list.length; i++) {
  671. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  672. }
  673. return [list1, list2];
  674. }
  675. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  676. var flow = (superClass => class extends superClass {
  677. constructor(options, input) {
  678. super(options, input);
  679. this.flowPragma = undefined;
  680. }
  681. shouldParseTypes() {
  682. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  683. }
  684. finishToken(type, val) {
  685. if (!(type === types.string || type === types.semi)) {
  686. if (this.flowPragma === undefined) {
  687. this.flowPragma = null;
  688. }
  689. }
  690. return super.finishToken(type, val);
  691. }
  692. addComment(comment) {
  693. if (this.flowPragma === undefined) {
  694. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  695. if (!matches) ; else if (matches[1] === "flow") {
  696. this.flowPragma = "flow";
  697. } else if (matches[1] === "noflow") {
  698. this.flowPragma = "noflow";
  699. } else {
  700. throw new Error("Unexpected flow pragma");
  701. }
  702. }
  703. return super.addComment(comment);
  704. }
  705. flowParseTypeInitialiser(tok) {
  706. const oldInType = this.state.inType;
  707. this.state.inType = true;
  708. this.expect(tok || types.colon);
  709. const type = this.flowParseType();
  710. this.state.inType = oldInType;
  711. return type;
  712. }
  713. flowParsePredicate() {
  714. const node = this.startNode();
  715. const moduloLoc = this.state.startLoc;
  716. const moduloPos = this.state.start;
  717. this.expect(types.modulo);
  718. const checksLoc = this.state.startLoc;
  719. this.expectContextual("checks");
  720. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  721. this.raise(moduloPos, "Spaces between ´%´ and ´checks´ are not allowed here.");
  722. }
  723. if (this.eat(types.parenL)) {
  724. node.value = this.parseExpression();
  725. this.expect(types.parenR);
  726. return this.finishNode(node, "DeclaredPredicate");
  727. } else {
  728. return this.finishNode(node, "InferredPredicate");
  729. }
  730. }
  731. flowParseTypeAndPredicateInitialiser() {
  732. const oldInType = this.state.inType;
  733. this.state.inType = true;
  734. this.expect(types.colon);
  735. let type = null;
  736. let predicate = null;
  737. if (this.match(types.modulo)) {
  738. this.state.inType = oldInType;
  739. predicate = this.flowParsePredicate();
  740. } else {
  741. type = this.flowParseType();
  742. this.state.inType = oldInType;
  743. if (this.match(types.modulo)) {
  744. predicate = this.flowParsePredicate();
  745. }
  746. }
  747. return [type, predicate];
  748. }
  749. flowParseDeclareClass(node) {
  750. this.next();
  751. this.flowParseInterfaceish(node, true);
  752. return this.finishNode(node, "DeclareClass");
  753. }
  754. flowParseDeclareFunction(node) {
  755. this.next();
  756. const id = node.id = this.parseIdentifier();
  757. const typeNode = this.startNode();
  758. const typeContainer = this.startNode();
  759. if (this.isRelational("<")) {
  760. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  761. } else {
  762. typeNode.typeParameters = null;
  763. }
  764. this.expect(types.parenL);
  765. const tmp = this.flowParseFunctionTypeParams();
  766. typeNode.params = tmp.params;
  767. typeNode.rest = tmp.rest;
  768. this.expect(types.parenR);
  769. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  770. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  771. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  772. this.finishNode(id, id.type);
  773. this.semicolon();
  774. return this.finishNode(node, "DeclareFunction");
  775. }
  776. flowParseDeclare(node, insideModule) {
  777. if (this.match(types._class)) {
  778. return this.flowParseDeclareClass(node);
  779. } else if (this.match(types._function)) {
  780. return this.flowParseDeclareFunction(node);
  781. } else if (this.match(types._var)) {
  782. return this.flowParseDeclareVariable(node);
  783. } else if (this.isContextual("module")) {
  784. if (this.lookahead().type === types.dot) {
  785. return this.flowParseDeclareModuleExports(node);
  786. } else {
  787. if (insideModule) {
  788. this.unexpected(null, "`declare module` cannot be used inside another `declare module`");
  789. }
  790. return this.flowParseDeclareModule(node);
  791. }
  792. } else if (this.isContextual("type")) {
  793. return this.flowParseDeclareTypeAlias(node);
  794. } else if (this.isContextual("opaque")) {
  795. return this.flowParseDeclareOpaqueType(node);
  796. } else if (this.isContextual("interface")) {
  797. return this.flowParseDeclareInterface(node);
  798. } else if (this.match(types._export)) {
  799. return this.flowParseDeclareExportDeclaration(node, insideModule);
  800. } else {
  801. throw this.unexpected();
  802. }
  803. }
  804. flowParseDeclareVariable(node) {
  805. this.next();
  806. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  807. this.semicolon();
  808. return this.finishNode(node, "DeclareVariable");
  809. }
  810. flowParseDeclareModule(node) {
  811. this.next();
  812. this.scope.enter(SCOPE_OTHER);
  813. if (this.match(types.string)) {
  814. node.id = this.parseExprAtom();
  815. } else {
  816. node.id = this.parseIdentifier();
  817. }
  818. const bodyNode = node.body = this.startNode();
  819. const body = bodyNode.body = [];
  820. this.expect(types.braceL);
  821. while (!this.match(types.braceR)) {
  822. let bodyNode = this.startNode();
  823. if (this.match(types._import)) {
  824. const lookahead = this.lookahead();
  825. if (lookahead.value !== "type" && lookahead.value !== "typeof") {
  826. this.unexpected(null, "Imports within a `declare module` body must always be `import type` or `import typeof`");
  827. }
  828. this.next();
  829. this.parseImport(bodyNode);
  830. } else {
  831. this.expectContextual("declare", "Only declares and type imports are allowed inside declare module");
  832. bodyNode = this.flowParseDeclare(bodyNode, true);
  833. }
  834. body.push(bodyNode);
  835. }
  836. this.scope.exit();
  837. this.expect(types.braceR);
  838. this.finishNode(bodyNode, "BlockStatement");
  839. let kind = null;
  840. let hasModuleExport = false;
  841. const errorMessage = "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";
  842. body.forEach(bodyElement => {
  843. if (isEsModuleType(bodyElement)) {
  844. if (kind === "CommonJS") {
  845. this.unexpected(bodyElement.start, errorMessage);
  846. }
  847. kind = "ES";
  848. } else if (bodyElement.type === "DeclareModuleExports") {
  849. if (hasModuleExport) {
  850. this.unexpected(bodyElement.start, "Duplicate `declare module.exports` statement");
  851. }
  852. if (kind === "ES") this.unexpected(bodyElement.start, errorMessage);
  853. kind = "CommonJS";
  854. hasModuleExport = true;
  855. }
  856. });
  857. node.kind = kind || "CommonJS";
  858. return this.finishNode(node, "DeclareModule");
  859. }
  860. flowParseDeclareExportDeclaration(node, insideModule) {
  861. this.expect(types._export);
  862. if (this.eat(types._default)) {
  863. if (this.match(types._function) || this.match(types._class)) {
  864. node.declaration = this.flowParseDeclare(this.startNode());
  865. } else {
  866. node.declaration = this.flowParseType();
  867. this.semicolon();
  868. }
  869. node.default = true;
  870. return this.finishNode(node, "DeclareExportDeclaration");
  871. } else {
  872. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  873. const label = this.state.value;
  874. const suggestion = exportSuggestions[label];
  875. this.unexpected(this.state.start, `\`declare export ${label}\` is not supported. Use \`${suggestion}\` instead`);
  876. }
  877. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  878. node.declaration = this.flowParseDeclare(this.startNode());
  879. node.default = false;
  880. return this.finishNode(node, "DeclareExportDeclaration");
  881. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  882. node = this.parseExport(node);
  883. if (node.type === "ExportNamedDeclaration") {
  884. node.type = "ExportDeclaration";
  885. node.default = false;
  886. delete node.exportKind;
  887. }
  888. node.type = "Declare" + node.type;
  889. return node;
  890. }
  891. }
  892. throw this.unexpected();
  893. }
  894. flowParseDeclareModuleExports(node) {
  895. this.expectContextual("module");
  896. this.expect(types.dot);
  897. this.expectContextual("exports");
  898. node.typeAnnotation = this.flowParseTypeAnnotation();
  899. this.semicolon();
  900. return this.finishNode(node, "DeclareModuleExports");
  901. }
  902. flowParseDeclareTypeAlias(node) {
  903. this.next();
  904. this.flowParseTypeAlias(node);
  905. return this.finishNode(node, "DeclareTypeAlias");
  906. }
  907. flowParseDeclareOpaqueType(node) {
  908. this.next();
  909. this.flowParseOpaqueType(node, true);
  910. return this.finishNode(node, "DeclareOpaqueType");
  911. }
  912. flowParseDeclareInterface(node) {
  913. this.next();
  914. this.flowParseInterfaceish(node);
  915. return this.finishNode(node, "DeclareInterface");
  916. }
  917. flowParseInterfaceish(node, isClass = false) {
  918. node.id = this.flowParseRestrictedIdentifier(!isClass);
  919. if (this.isRelational("<")) {
  920. node.typeParameters = this.flowParseTypeParameterDeclaration();
  921. } else {
  922. node.typeParameters = null;
  923. }
  924. node.extends = [];
  925. node.implements = [];
  926. node.mixins = [];
  927. if (this.eat(types._extends)) {
  928. do {
  929. node.extends.push(this.flowParseInterfaceExtends());
  930. } while (!isClass && this.eat(types.comma));
  931. }
  932. if (this.isContextual("mixins")) {
  933. this.next();
  934. do {
  935. node.mixins.push(this.flowParseInterfaceExtends());
  936. } while (this.eat(types.comma));
  937. }
  938. if (this.isContextual("implements")) {
  939. this.next();
  940. do {
  941. node.implements.push(this.flowParseInterfaceExtends());
  942. } while (this.eat(types.comma));
  943. }
  944. node.body = this.flowParseObjectType({
  945. allowStatic: isClass,
  946. allowExact: false,
  947. allowSpread: false,
  948. allowProto: isClass,
  949. allowInexact: false
  950. });
  951. }
  952. flowParseInterfaceExtends() {
  953. const node = this.startNode();
  954. node.id = this.flowParseQualifiedTypeIdentifier();
  955. if (this.isRelational("<")) {
  956. node.typeParameters = this.flowParseTypeParameterInstantiation();
  957. } else {
  958. node.typeParameters = null;
  959. }
  960. return this.finishNode(node, "InterfaceExtends");
  961. }
  962. flowParseInterface(node) {
  963. this.flowParseInterfaceish(node);
  964. return this.finishNode(node, "InterfaceDeclaration");
  965. }
  966. checkNotUnderscore(word) {
  967. if (word === "_") {
  968. throw this.unexpected(null, "`_` is only allowed as a type argument to call or new");
  969. }
  970. }
  971. checkReservedType(word, startLoc) {
  972. if (reservedTypes.indexOf(word) > -1) {
  973. this.raise(startLoc, `Cannot overwrite reserved type ${word}`);
  974. }
  975. }
  976. flowParseRestrictedIdentifier(liberal) {
  977. this.checkReservedType(this.state.value, this.state.start);
  978. return this.parseIdentifier(liberal);
  979. }
  980. flowParseTypeAlias(node) {
  981. node.id = this.flowParseRestrictedIdentifier();
  982. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  983. if (this.isRelational("<")) {
  984. node.typeParameters = this.flowParseTypeParameterDeclaration();
  985. } else {
  986. node.typeParameters = null;
  987. }
  988. node.right = this.flowParseTypeInitialiser(types.eq);
  989. this.semicolon();
  990. return this.finishNode(node, "TypeAlias");
  991. }
  992. flowParseOpaqueType(node, declare) {
  993. this.expectContextual("type");
  994. node.id = this.flowParseRestrictedIdentifier(true);
  995. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  996. if (this.isRelational("<")) {
  997. node.typeParameters = this.flowParseTypeParameterDeclaration();
  998. } else {
  999. node.typeParameters = null;
  1000. }
  1001. node.supertype = null;
  1002. if (this.match(types.colon)) {
  1003. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1004. }
  1005. node.impltype = null;
  1006. if (!declare) {
  1007. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1008. }
  1009. this.semicolon();
  1010. return this.finishNode(node, "OpaqueType");
  1011. }
  1012. flowParseTypeParameter(allowDefault = true, requireDefault = false) {
  1013. if (!allowDefault && requireDefault) {
  1014. throw new Error("Cannot disallow a default value (`allowDefault`) while also requiring it (`requireDefault`).");
  1015. }
  1016. const nodeStart = this.state.start;
  1017. const node = this.startNode();
  1018. const variance = this.flowParseVariance();
  1019. const ident = this.flowParseTypeAnnotatableIdentifier();
  1020. node.name = ident.name;
  1021. node.variance = variance;
  1022. node.bound = ident.typeAnnotation;
  1023. if (this.match(types.eq)) {
  1024. if (allowDefault) {
  1025. this.eat(types.eq);
  1026. node.default = this.flowParseType();
  1027. } else {
  1028. this.unexpected();
  1029. }
  1030. } else {
  1031. if (requireDefault) {
  1032. this.unexpected(nodeStart, "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.");
  1033. }
  1034. }
  1035. return this.finishNode(node, "TypeParameter");
  1036. }
  1037. flowParseTypeParameterDeclaration(allowDefault = true) {
  1038. const oldInType = this.state.inType;
  1039. const node = this.startNode();
  1040. node.params = [];
  1041. this.state.inType = true;
  1042. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1043. this.next();
  1044. } else {
  1045. this.unexpected();
  1046. }
  1047. let defaultRequired = false;
  1048. do {
  1049. const typeParameter = this.flowParseTypeParameter(allowDefault, defaultRequired);
  1050. node.params.push(typeParameter);
  1051. if (typeParameter.default) {
  1052. defaultRequired = true;
  1053. }
  1054. if (!this.isRelational(">")) {
  1055. this.expect(types.comma);
  1056. }
  1057. } while (!this.isRelational(">"));
  1058. this.expectRelational(">");
  1059. this.state.inType = oldInType;
  1060. return this.finishNode(node, "TypeParameterDeclaration");
  1061. }
  1062. flowParseTypeParameterInstantiation() {
  1063. const node = this.startNode();
  1064. const oldInType = this.state.inType;
  1065. node.params = [];
  1066. this.state.inType = true;
  1067. this.expectRelational("<");
  1068. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1069. this.state.noAnonFunctionType = false;
  1070. while (!this.isRelational(">")) {
  1071. node.params.push(this.flowParseType());
  1072. if (!this.isRelational(">")) {
  1073. this.expect(types.comma);
  1074. }
  1075. }
  1076. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1077. this.expectRelational(">");
  1078. this.state.inType = oldInType;
  1079. return this.finishNode(node, "TypeParameterInstantiation");
  1080. }
  1081. flowParseTypeParameterInstantiationCallOrNew() {
  1082. const node = this.startNode();
  1083. const oldInType = this.state.inType;
  1084. node.params = [];
  1085. this.state.inType = true;
  1086. this.expectRelational("<");
  1087. while (!this.isRelational(">")) {
  1088. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1089. if (!this.isRelational(">")) {
  1090. this.expect(types.comma);
  1091. }
  1092. }
  1093. this.expectRelational(">");
  1094. this.state.inType = oldInType;
  1095. return this.finishNode(node, "TypeParameterInstantiation");
  1096. }
  1097. flowParseInterfaceType() {
  1098. const node = this.startNode();
  1099. this.expectContextual("interface");
  1100. node.extends = [];
  1101. if (this.eat(types._extends)) {
  1102. do {
  1103. node.extends.push(this.flowParseInterfaceExtends());
  1104. } while (this.eat(types.comma));
  1105. }
  1106. node.body = this.flowParseObjectType({
  1107. allowStatic: false,
  1108. allowExact: false,
  1109. allowSpread: false,
  1110. allowProto: false,
  1111. allowInexact: false
  1112. });
  1113. return this.finishNode(node, "InterfaceTypeAnnotation");
  1114. }
  1115. flowParseObjectPropertyKey() {
  1116. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1117. }
  1118. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1119. node.static = isStatic;
  1120. if (this.lookahead().type === types.colon) {
  1121. node.id = this.flowParseObjectPropertyKey();
  1122. node.key = this.flowParseTypeInitialiser();
  1123. } else {
  1124. node.id = null;
  1125. node.key = this.flowParseType();
  1126. }
  1127. this.expect(types.bracketR);
  1128. node.value = this.flowParseTypeInitialiser();
  1129. node.variance = variance;
  1130. return this.finishNode(node, "ObjectTypeIndexer");
  1131. }
  1132. flowParseObjectTypeInternalSlot(node, isStatic) {
  1133. node.static = isStatic;
  1134. node.id = this.flowParseObjectPropertyKey();
  1135. this.expect(types.bracketR);
  1136. this.expect(types.bracketR);
  1137. if (this.isRelational("<") || this.match(types.parenL)) {
  1138. node.method = true;
  1139. node.optional = false;
  1140. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1141. } else {
  1142. node.method = false;
  1143. if (this.eat(types.question)) {
  1144. node.optional = true;
  1145. }
  1146. node.value = this.flowParseTypeInitialiser();
  1147. }
  1148. return this.finishNode(node, "ObjectTypeInternalSlot");
  1149. }
  1150. flowParseObjectTypeMethodish(node) {
  1151. node.params = [];
  1152. node.rest = null;
  1153. node.typeParameters = null;
  1154. if (this.isRelational("<")) {
  1155. node.typeParameters = this.flowParseTypeParameterDeclaration(false);
  1156. }
  1157. this.expect(types.parenL);
  1158. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1159. node.params.push(this.flowParseFunctionTypeParam());
  1160. if (!this.match(types.parenR)) {
  1161. this.expect(types.comma);
  1162. }
  1163. }
  1164. if (this.eat(types.ellipsis)) {
  1165. node.rest = this.flowParseFunctionTypeParam();
  1166. }
  1167. this.expect(types.parenR);
  1168. node.returnType = this.flowParseTypeInitialiser();
  1169. return this.finishNode(node, "FunctionTypeAnnotation");
  1170. }
  1171. flowParseObjectTypeCallProperty(node, isStatic) {
  1172. const valueNode = this.startNode();
  1173. node.static = isStatic;
  1174. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1175. return this.finishNode(node, "ObjectTypeCallProperty");
  1176. }
  1177. flowParseObjectType({
  1178. allowStatic,
  1179. allowExact,
  1180. allowSpread,
  1181. allowProto,
  1182. allowInexact
  1183. }) {
  1184. const oldInType = this.state.inType;
  1185. this.state.inType = true;
  1186. const nodeStart = this.startNode();
  1187. nodeStart.callProperties = [];
  1188. nodeStart.properties = [];
  1189. nodeStart.indexers = [];
  1190. nodeStart.internalSlots = [];
  1191. let endDelim;
  1192. let exact;
  1193. let inexact = false;
  1194. if (allowExact && this.match(types.braceBarL)) {
  1195. this.expect(types.braceBarL);
  1196. endDelim = types.braceBarR;
  1197. exact = true;
  1198. } else {
  1199. this.expect(types.braceL);
  1200. endDelim = types.braceR;
  1201. exact = false;
  1202. }
  1203. nodeStart.exact = exact;
  1204. while (!this.match(endDelim)) {
  1205. let isStatic = false;
  1206. let protoStart = null;
  1207. const node = this.startNode();
  1208. if (allowProto && this.isContextual("proto")) {
  1209. const lookahead = this.lookahead();
  1210. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1211. this.next();
  1212. protoStart = this.state.start;
  1213. allowStatic = false;
  1214. }
  1215. }
  1216. if (allowStatic && this.isContextual("static")) {
  1217. const lookahead = this.lookahead();
  1218. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1219. this.next();
  1220. isStatic = true;
  1221. }
  1222. }
  1223. const variance = this.flowParseVariance();
  1224. if (this.eat(types.bracketL)) {
  1225. if (protoStart != null) {
  1226. this.unexpected(protoStart);
  1227. }
  1228. if (this.eat(types.bracketL)) {
  1229. if (variance) {
  1230. this.unexpected(variance.start);
  1231. }
  1232. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1233. } else {
  1234. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1235. }
  1236. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1237. if (protoStart != null) {
  1238. this.unexpected(protoStart);
  1239. }
  1240. if (variance) {
  1241. this.unexpected(variance.start);
  1242. }
  1243. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1244. } else {
  1245. let kind = "init";
  1246. if (this.isContextual("get") || this.isContextual("set")) {
  1247. const lookahead = this.lookahead();
  1248. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1249. kind = this.state.value;
  1250. this.next();
  1251. }
  1252. }
  1253. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact);
  1254. if (propOrInexact === null) {
  1255. inexact = true;
  1256. } else {
  1257. nodeStart.properties.push(propOrInexact);
  1258. }
  1259. }
  1260. this.flowObjectTypeSemicolon();
  1261. }
  1262. this.expect(endDelim);
  1263. if (allowSpread) {
  1264. nodeStart.inexact = inexact;
  1265. }
  1266. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1267. this.state.inType = oldInType;
  1268. return out;
  1269. }
  1270. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1271. if (this.match(types.ellipsis)) {
  1272. if (!allowSpread) {
  1273. this.unexpected(null, "Spread operator cannot appear in class or interface definitions");
  1274. }
  1275. if (protoStart != null) {
  1276. this.unexpected(protoStart);
  1277. }
  1278. if (variance) {
  1279. this.unexpected(variance.start, "Spread properties cannot have variance");
  1280. }
  1281. this.expect(types.ellipsis);
  1282. const isInexactToken = this.eat(types.comma) || this.eat(types.semi);
  1283. if (this.match(types.braceR)) {
  1284. if (allowInexact) return null;
  1285. this.unexpected(null, "Explicit inexact syntax is only allowed inside inexact objects");
  1286. }
  1287. if (this.match(types.braceBarR)) {
  1288. this.unexpected(null, "Explicit inexact syntax cannot appear inside an explicit exact object type");
  1289. }
  1290. if (isInexactToken) {
  1291. this.unexpected(null, "Explicit inexact syntax must appear at the end of an inexact object");
  1292. }
  1293. node.argument = this.flowParseType();
  1294. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1295. } else {
  1296. node.key = this.flowParseObjectPropertyKey();
  1297. node.static = isStatic;
  1298. node.proto = protoStart != null;
  1299. node.kind = kind;
  1300. let optional = false;
  1301. if (this.isRelational("<") || this.match(types.parenL)) {
  1302. node.method = true;
  1303. if (protoStart != null) {
  1304. this.unexpected(protoStart);
  1305. }
  1306. if (variance) {
  1307. this.unexpected(variance.start);
  1308. }
  1309. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1310. if (kind === "get" || kind === "set") {
  1311. this.flowCheckGetterSetterParams(node);
  1312. }
  1313. } else {
  1314. if (kind !== "init") this.unexpected();
  1315. node.method = false;
  1316. if (this.eat(types.question)) {
  1317. optional = true;
  1318. }
  1319. node.value = this.flowParseTypeInitialiser();
  1320. node.variance = variance;
  1321. }
  1322. node.optional = optional;
  1323. return this.finishNode(node, "ObjectTypeProperty");
  1324. }
  1325. }
  1326. flowCheckGetterSetterParams(property) {
  1327. const paramCount = property.kind === "get" ? 0 : 1;
  1328. const start = property.start;
  1329. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1330. if (length !== paramCount) {
  1331. if (property.kind === "get") {
  1332. this.raise(start, "getter must not have any formal parameters");
  1333. } else {
  1334. this.raise(start, "setter must have exactly one formal parameter");
  1335. }
  1336. }
  1337. if (property.kind === "set" && property.value.rest) {
  1338. this.raise(start, "setter function argument must not be a rest parameter");
  1339. }
  1340. }
  1341. flowObjectTypeSemicolon() {
  1342. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1343. this.unexpected();
  1344. }
  1345. }
  1346. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1347. startPos = startPos || this.state.start;
  1348. startLoc = startLoc || this.state.startLoc;
  1349. let node = id || this.parseIdentifier();
  1350. while (this.eat(types.dot)) {
  1351. const node2 = this.startNodeAt(startPos, startLoc);
  1352. node2.qualification = node;
  1353. node2.id = this.parseIdentifier();
  1354. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1355. }
  1356. return node;
  1357. }
  1358. flowParseGenericType(startPos, startLoc, id) {
  1359. const node = this.startNodeAt(startPos, startLoc);
  1360. node.typeParameters = null;
  1361. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1362. if (this.isRelational("<")) {
  1363. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1364. }
  1365. return this.finishNode(node, "GenericTypeAnnotation");
  1366. }
  1367. flowParseTypeofType() {
  1368. const node = this.startNode();
  1369. this.expect(types._typeof);
  1370. node.argument = this.flowParsePrimaryType();
  1371. return this.finishNode(node, "TypeofTypeAnnotation");
  1372. }
  1373. flowParseTupleType() {
  1374. const node = this.startNode();
  1375. node.types = [];
  1376. this.expect(types.bracketL);
  1377. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1378. node.types.push(this.flowParseType());
  1379. if (this.match(types.bracketR)) break;
  1380. this.expect(types.comma);
  1381. }
  1382. this.expect(types.bracketR);
  1383. return this.finishNode(node, "TupleTypeAnnotation");
  1384. }
  1385. flowParseFunctionTypeParam() {
  1386. let name = null;
  1387. let optional = false;
  1388. let typeAnnotation = null;
  1389. const node = this.startNode();
  1390. const lh = this.lookahead();
  1391. if (lh.type === types.colon || lh.type === types.question) {
  1392. name = this.parseIdentifier();
  1393. if (this.eat(types.question)) {
  1394. optional = true;
  1395. }
  1396. typeAnnotation = this.flowParseTypeInitialiser();
  1397. } else {
  1398. typeAnnotation = this.flowParseType();
  1399. }
  1400. node.name = name;
  1401. node.optional = optional;
  1402. node.typeAnnotation = typeAnnotation;
  1403. return this.finishNode(node, "FunctionTypeParam");
  1404. }
  1405. reinterpretTypeAsFunctionTypeParam(type) {
  1406. const node = this.startNodeAt(type.start, type.loc.start);
  1407. node.name = null;
  1408. node.optional = false;
  1409. node.typeAnnotation = type;
  1410. return this.finishNode(node, "FunctionTypeParam");
  1411. }
  1412. flowParseFunctionTypeParams(params = []) {
  1413. let rest = null;
  1414. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1415. params.push(this.flowParseFunctionTypeParam());
  1416. if (!this.match(types.parenR)) {
  1417. this.expect(types.comma);
  1418. }
  1419. }
  1420. if (this.eat(types.ellipsis)) {
  1421. rest = this.flowParseFunctionTypeParam();
  1422. }
  1423. return {
  1424. params,
  1425. rest
  1426. };
  1427. }
  1428. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1429. switch (id.name) {
  1430. case "any":
  1431. return this.finishNode(node, "AnyTypeAnnotation");
  1432. case "bool":
  1433. case "boolean":
  1434. return this.finishNode(node, "BooleanTypeAnnotation");
  1435. case "mixed":
  1436. return this.finishNode(node, "MixedTypeAnnotation");
  1437. case "empty":
  1438. return this.finishNode(node, "EmptyTypeAnnotation");
  1439. case "number":
  1440. return this.finishNode(node, "NumberTypeAnnotation");
  1441. case "string":
  1442. return this.finishNode(node, "StringTypeAnnotation");
  1443. default:
  1444. this.checkNotUnderscore(id.name);
  1445. return this.flowParseGenericType(startPos, startLoc, id);
  1446. }
  1447. }
  1448. flowParsePrimaryType() {
  1449. const startPos = this.state.start;
  1450. const startLoc = this.state.startLoc;
  1451. const node = this.startNode();
  1452. let tmp;
  1453. let type;
  1454. let isGroupedType = false;
  1455. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1456. switch (this.state.type) {
  1457. case types.name:
  1458. if (this.isContextual("interface")) {
  1459. return this.flowParseInterfaceType();
  1460. }
  1461. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1462. case types.braceL:
  1463. return this.flowParseObjectType({
  1464. allowStatic: false,
  1465. allowExact: false,
  1466. allowSpread: true,
  1467. allowProto: false,
  1468. allowInexact: true
  1469. });
  1470. case types.braceBarL:
  1471. return this.flowParseObjectType({
  1472. allowStatic: false,
  1473. allowExact: true,
  1474. allowSpread: true,
  1475. allowProto: false,
  1476. allowInexact: false
  1477. });
  1478. case types.bracketL:
  1479. return this.flowParseTupleType();
  1480. case types.relational:
  1481. if (this.state.value === "<") {
  1482. node.typeParameters = this.flowParseTypeParameterDeclaration(false);
  1483. this.expect(types.parenL);
  1484. tmp = this.flowParseFunctionTypeParams();
  1485. node.params = tmp.params;
  1486. node.rest = tmp.rest;
  1487. this.expect(types.parenR);
  1488. this.expect(types.arrow);
  1489. node.returnType = this.flowParseType();
  1490. return this.finishNode(node, "FunctionTypeAnnotation");
  1491. }
  1492. break;
  1493. case types.parenL:
  1494. this.next();
  1495. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1496. if (this.match(types.name)) {
  1497. const token = this.lookahead().type;
  1498. isGroupedType = token !== types.question && token !== types.colon;
  1499. } else {
  1500. isGroupedType = true;
  1501. }
  1502. }
  1503. if (isGroupedType) {
  1504. this.state.noAnonFunctionType = false;
  1505. type = this.flowParseType();
  1506. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1507. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  1508. this.expect(types.parenR);
  1509. return type;
  1510. } else {
  1511. this.eat(types.comma);
  1512. }
  1513. }
  1514. if (type) {
  1515. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  1516. } else {
  1517. tmp = this.flowParseFunctionTypeParams();
  1518. }
  1519. node.params = tmp.params;
  1520. node.rest = tmp.rest;
  1521. this.expect(types.parenR);
  1522. this.expect(types.arrow);
  1523. node.returnType = this.flowParseType();
  1524. node.typeParameters = null;
  1525. return this.finishNode(node, "FunctionTypeAnnotation");
  1526. case types.string:
  1527. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  1528. case types._true:
  1529. case types._false:
  1530. node.value = this.match(types._true);
  1531. this.next();
  1532. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  1533. case types.plusMin:
  1534. if (this.state.value === "-") {
  1535. this.next();
  1536. if (!this.match(types.num)) {
  1537. this.unexpected(null, `Unexpected token, expected "number"`);
  1538. }
  1539. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  1540. }
  1541. this.unexpected();
  1542. case types.num:
  1543. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  1544. case types._void:
  1545. this.next();
  1546. return this.finishNode(node, "VoidTypeAnnotation");
  1547. case types._null:
  1548. this.next();
  1549. return this.finishNode(node, "NullLiteralTypeAnnotation");
  1550. case types._this:
  1551. this.next();
  1552. return this.finishNode(node, "ThisTypeAnnotation");
  1553. case types.star:
  1554. this.next();
  1555. return this.finishNode(node, "ExistsTypeAnnotation");
  1556. default:
  1557. if (this.state.type.keyword === "typeof") {
  1558. return this.flowParseTypeofType();
  1559. } else if (this.state.type.keyword) {
  1560. const label = this.state.type.label;
  1561. this.next();
  1562. return super.createIdentifier(node, label);
  1563. }
  1564. }
  1565. throw this.unexpected();
  1566. }
  1567. flowParsePostfixType() {
  1568. const startPos = this.state.start,
  1569. startLoc = this.state.startLoc;
  1570. let type = this.flowParsePrimaryType();
  1571. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  1572. const node = this.startNodeAt(startPos, startLoc);
  1573. node.elementType = type;
  1574. this.expect(types.bracketL);
  1575. this.expect(types.bracketR);
  1576. type = this.finishNode(node, "ArrayTypeAnnotation");
  1577. }
  1578. return type;
  1579. }
  1580. flowParsePrefixType() {
  1581. const node = this.startNode();
  1582. if (this.eat(types.question)) {
  1583. node.typeAnnotation = this.flowParsePrefixType();
  1584. return this.finishNode(node, "NullableTypeAnnotation");
  1585. } else {
  1586. return this.flowParsePostfixType();
  1587. }
  1588. }
  1589. flowParseAnonFunctionWithoutParens() {
  1590. const param = this.flowParsePrefixType();
  1591. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  1592. const node = this.startNodeAt(param.start, param.loc.start);
  1593. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  1594. node.rest = null;
  1595. node.returnType = this.flowParseType();
  1596. node.typeParameters = null;
  1597. return this.finishNode(node, "FunctionTypeAnnotation");
  1598. }
  1599. return param;
  1600. }
  1601. flowParseIntersectionType() {
  1602. const node = this.startNode();
  1603. this.eat(types.bitwiseAND);
  1604. const type = this.flowParseAnonFunctionWithoutParens();
  1605. node.types = [type];
  1606. while (this.eat(types.bitwiseAND)) {
  1607. node.types.push(this.flowParseAnonFunctionWithoutParens());
  1608. }
  1609. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  1610. }
  1611. flowParseUnionType() {
  1612. const node = this.startNode();
  1613. this.eat(types.bitwiseOR);
  1614. const type = this.flowParseIntersectionType();
  1615. node.types = [type];
  1616. while (this.eat(types.bitwiseOR)) {
  1617. node.types.push(this.flowParseIntersectionType());
  1618. }
  1619. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  1620. }
  1621. flowParseType() {
  1622. const oldInType = this.state.inType;
  1623. this.state.inType = true;
  1624. const type = this.flowParseUnionType();
  1625. this.state.inType = oldInType;
  1626. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  1627. return type;
  1628. }
  1629. flowParseTypeOrImplicitInstantiation() {
  1630. if (this.state.type === types.name && this.state.value === "_") {
  1631. const startPos = this.state.start;
  1632. const startLoc = this.state.startLoc;
  1633. const node = this.parseIdentifier();
  1634. return this.flowParseGenericType(startPos, startLoc, node);
  1635. } else {
  1636. return this.flowParseType();
  1637. }
  1638. }
  1639. flowParseTypeAnnotation() {
  1640. const node = this.startNode();
  1641. node.typeAnnotation = this.flowParseTypeInitialiser();
  1642. return this.finishNode(node, "TypeAnnotation");
  1643. }
  1644. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  1645. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  1646. if (this.match(types.colon)) {
  1647. ident.typeAnnotation = this.flowParseTypeAnnotation();
  1648. this.finishNode(ident, ident.type);
  1649. }
  1650. return ident;
  1651. }
  1652. typeCastToParameter(node) {
  1653. node.expression.typeAnnotation = node.typeAnnotation;
  1654. return this.finishNodeAt(node.expression, node.expression.type, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  1655. }
  1656. flowParseVariance() {
  1657. let variance = null;
  1658. if (this.match(types.plusMin)) {
  1659. variance = this.startNode();
  1660. if (this.state.value === "+") {
  1661. variance.kind = "plus";
  1662. } else {
  1663. variance.kind = "minus";
  1664. }
  1665. this.next();
  1666. this.finishNode(variance, "Variance");
  1667. }
  1668. return variance;
  1669. }
  1670. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  1671. if (allowExpressionBody) {
  1672. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  1673. }
  1674. return super.parseFunctionBody(node, false, isMethod);
  1675. }
  1676. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  1677. if (this.match(types.colon)) {
  1678. const typeNode = this.startNode();
  1679. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1680. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  1681. }
  1682. super.parseFunctionBodyAndFinish(node, type, isMethod);
  1683. }
  1684. parseStatement(context, topLevel) {
  1685. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  1686. const node = this.startNode();
  1687. this.next();
  1688. return this.flowParseInterface(node);
  1689. } else {
  1690. const stmt = super.parseStatement(context, topLevel);
  1691. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  1692. this.flowPragma = null;
  1693. }
  1694. return stmt;
  1695. }
  1696. }
  1697. parseExpressionStatement(node, expr) {
  1698. if (expr.type === "Identifier") {
  1699. if (expr.name === "declare") {
  1700. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  1701. return this.flowParseDeclare(node);
  1702. }
  1703. } else if (this.match(types.name)) {
  1704. if (expr.name === "interface") {
  1705. return this.flowParseInterface(node);
  1706. } else if (expr.name === "type") {
  1707. return this.flowParseTypeAlias(node);
  1708. } else if (expr.name === "opaque") {
  1709. return this.flowParseOpaqueType(node, false);
  1710. }
  1711. }
  1712. }
  1713. return super.parseExpressionStatement(node, expr);
  1714. }
  1715. shouldParseExportDeclaration() {
  1716. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || super.shouldParseExportDeclaration();
  1717. }
  1718. isExportDefaultSpecifier() {
  1719. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque")) {
  1720. return false;
  1721. }
  1722. return super.isExportDefaultSpecifier();
  1723. }
  1724. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  1725. if (!this.match(types.question)) return expr;
  1726. if (refNeedsArrowPos) {
  1727. const state = this.state.clone();
  1728. try {
  1729. return super.parseConditional(expr, noIn, startPos, startLoc);
  1730. } catch (err) {
  1731. if (err instanceof SyntaxError) {
  1732. this.state = state;
  1733. refNeedsArrowPos.start = err.pos || this.state.start;
  1734. return expr;
  1735. } else {
  1736. throw err;
  1737. }
  1738. }
  1739. }
  1740. this.expect(types.question);
  1741. const state = this.state.clone();
  1742. const originalNoArrowAt = this.state.noArrowAt;
  1743. const node = this.startNodeAt(startPos, startLoc);
  1744. let {
  1745. consequent,
  1746. failed
  1747. } = this.tryParseConditionalConsequent();
  1748. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1749. if (failed || invalid.length > 0) {
  1750. const noArrowAt = [...originalNoArrowAt];
  1751. if (invalid.length > 0) {
  1752. this.state = state;
  1753. this.state.noArrowAt = noArrowAt;
  1754. for (let i = 0; i < invalid.length; i++) {
  1755. noArrowAt.push(invalid[i].start);
  1756. }
  1757. ({
  1758. consequent,
  1759. failed
  1760. } = this.tryParseConditionalConsequent());
  1761. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  1762. }
  1763. if (failed && valid.length > 1) {
  1764. this.raise(state.start, "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.");
  1765. }
  1766. if (failed && valid.length === 1) {
  1767. this.state = state;
  1768. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  1769. ({
  1770. consequent,
  1771. failed
  1772. } = this.tryParseConditionalConsequent());
  1773. }
  1774. this.getArrowLikeExpressions(consequent, true);
  1775. }
  1776. this.state.noArrowAt = originalNoArrowAt;
  1777. this.expect(types.colon);
  1778. node.test = expr;
  1779. node.consequent = consequent;
  1780. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(noIn, undefined, undefined, undefined));
  1781. return this.finishNode(node, "ConditionalExpression");
  1782. }
  1783. tryParseConditionalConsequent() {
  1784. this.state.noArrowParamsConversionAt.push(this.state.start);
  1785. const consequent = this.parseMaybeAssign();
  1786. const failed = !this.match(types.colon);
  1787. this.state.noArrowParamsConversionAt.pop();
  1788. return {
  1789. consequent,
  1790. failed
  1791. };
  1792. }
  1793. getArrowLikeExpressions(node, disallowInvalid) {
  1794. const stack = [node];
  1795. const arrows = [];
  1796. while (stack.length !== 0) {
  1797. const node = stack.pop();
  1798. if (node.type === "ArrowFunctionExpression") {
  1799. if (node.typeParameters || !node.returnType) {
  1800. this.toAssignableList(node.params, true, "arrow function parameters");
  1801. this.scope.enter(functionFlags(false, false) | SCOPE_ARROW);
  1802. super.checkParams(node, false, true);
  1803. this.scope.exit();
  1804. } else {
  1805. arrows.push(node);
  1806. }
  1807. stack.push(node.body);
  1808. } else if (node.type === "ConditionalExpression") {
  1809. stack.push(node.consequent);
  1810. stack.push(node.alternate);
  1811. }
  1812. }
  1813. if (disallowInvalid) {
  1814. for (let i = 0; i < arrows.length; i++) {
  1815. this.toAssignableList(node.params, true, "arrow function parameters");
  1816. }
  1817. return [arrows, []];
  1818. }
  1819. return partition(arrows, node => {
  1820. try {
  1821. this.toAssignableList(node.params, true, "arrow function parameters");
  1822. return true;
  1823. } catch (err) {
  1824. return false;
  1825. }
  1826. });
  1827. }
  1828. forwardNoArrowParamsConversionAt(node, parse) {
  1829. let result;
  1830. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  1831. this.state.noArrowParamsConversionAt.push(this.state.start);
  1832. result = parse();
  1833. this.state.noArrowParamsConversionAt.pop();
  1834. } else {
  1835. result = parse();
  1836. }
  1837. return result;
  1838. }
  1839. parseParenItem(node, startPos, startLoc) {
  1840. node = super.parseParenItem(node, startPos, startLoc);
  1841. if (this.eat(types.question)) {
  1842. node.optional = true;
  1843. }
  1844. if (this.match(types.colon)) {
  1845. const typeCastNode = this.startNodeAt(startPos, startLoc);
  1846. typeCastNode.expression = node;
  1847. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  1848. return this.finishNode(typeCastNode, "TypeCastExpression");
  1849. }
  1850. return node;
  1851. }
  1852. assertModuleNodeAllowed(node) {
  1853. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  1854. return;
  1855. }
  1856. super.assertModuleNodeAllowed(node);
  1857. }
  1858. parseExport(node) {
  1859. const decl = super.parseExport(node);
  1860. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  1861. decl.exportKind = decl.exportKind || "value";
  1862. }
  1863. return decl;
  1864. }
  1865. parseExportDeclaration(node) {
  1866. if (this.isContextual("type")) {
  1867. node.exportKind = "type";
  1868. const declarationNode = this.startNode();
  1869. this.next();
  1870. if (this.match(types.braceL)) {
  1871. node.specifiers = this.parseExportSpecifiers();
  1872. this.parseExportFrom(node);
  1873. return null;
  1874. } else {
  1875. return this.flowParseTypeAlias(declarationNode);
  1876. }
  1877. } else if (this.isContextual("opaque")) {
  1878. node.exportKind = "type";
  1879. const declarationNode = this.startNode();
  1880. this.next();
  1881. return this.flowParseOpaqueType(declarationNode, false);
  1882. } else if (this.isContextual("interface")) {
  1883. node.exportKind = "type";
  1884. const declarationNode = this.startNode();
  1885. this.next();
  1886. return this.flowParseInterface(declarationNode);
  1887. } else {
  1888. return super.parseExportDeclaration(node);
  1889. }
  1890. }
  1891. eatExportStar(node) {
  1892. if (super.eatExportStar(...arguments)) return true;
  1893. if (this.isContextual("type") && this.lookahead().type === types.star) {
  1894. node.exportKind = "type";
  1895. this.next();
  1896. this.next();
  1897. return true;
  1898. }
  1899. return false;
  1900. }
  1901. maybeParseExportNamespaceSpecifier(node) {
  1902. const pos = this.state.start;
  1903. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  1904. if (hasNamespace && node.exportKind === "type") {
  1905. this.unexpected(pos);
  1906. }
  1907. return hasNamespace;
  1908. }
  1909. parseClassId(node, isStatement, optionalId) {
  1910. super.parseClassId(node, isStatement, optionalId);
  1911. if (this.isRelational("<")) {
  1912. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1913. }
  1914. }
  1915. getTokenFromCode(code) {
  1916. const next = this.input.charCodeAt(this.state.pos + 1);
  1917. if (code === 123 && next === 124) {
  1918. return this.finishOp(types.braceBarL, 2);
  1919. } else if (this.state.inType && (code === 62 || code === 60)) {
  1920. return this.finishOp(types.relational, 1);
  1921. } else if (isIteratorStart(code, next)) {
  1922. this.state.isIterator = true;
  1923. return super.readWord();
  1924. } else {
  1925. return super.getTokenFromCode(code);
  1926. }
  1927. }
  1928. toAssignable(node, isBinding, contextDescription) {
  1929. if (node.type === "TypeCastExpression") {
  1930. return super.toAssignable(this.typeCastToParameter(node), isBinding, contextDescription);
  1931. } else {
  1932. return super.toAssignable(node, isBinding, contextDescription);
  1933. }
  1934. }
  1935. toAssignableList(exprList, isBinding, contextDescription) {
  1936. for (let i = 0; i < exprList.length; i++) {
  1937. const expr = exprList[i];
  1938. if (expr && expr.type === "TypeCastExpression") {
  1939. exprList[i] = this.typeCastToParameter(expr);
  1940. }
  1941. }
  1942. return super.toAssignableList(exprList, isBinding, contextDescription);
  1943. }
  1944. toReferencedList(exprList, isParenthesizedExpr) {
  1945. for (let i = 0; i < exprList.length; i++) {
  1946. const expr = exprList[i];
  1947. if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  1948. this.raise(expr.typeAnnotation.start, "The type cast expression is expected to be wrapped with parenthesis");
  1949. }
  1950. }
  1951. return exprList;
  1952. }
  1953. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  1954. if (expr.type !== "TypeCastExpression") {
  1955. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  1956. }
  1957. }
  1958. parseClassProperty(node) {
  1959. if (this.match(types.colon)) {
  1960. node.typeAnnotation = this.flowParseTypeAnnotation();
  1961. }
  1962. return super.parseClassProperty(node);
  1963. }
  1964. parseClassPrivateProperty(node) {
  1965. if (this.match(types.colon)) {
  1966. node.typeAnnotation = this.flowParseTypeAnnotation();
  1967. }
  1968. return super.parseClassPrivateProperty(node);
  1969. }
  1970. isClassMethod() {
  1971. return this.isRelational("<") || super.isClassMethod();
  1972. }
  1973. isClassProperty() {
  1974. return this.match(types.colon) || super.isClassProperty();
  1975. }
  1976. isNonstaticConstructor(method) {
  1977. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  1978. }
  1979. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  1980. if (method.variance) {
  1981. this.unexpected(method.variance.start);
  1982. }
  1983. delete method.variance;
  1984. if (this.isRelational("<")) {
  1985. method.typeParameters = this.flowParseTypeParameterDeclaration(false);
  1986. }
  1987. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  1988. }
  1989. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  1990. if (method.variance) {
  1991. this.unexpected(method.variance.start);
  1992. }
  1993. delete method.variance;
  1994. if (this.isRelational("<")) {
  1995. method.typeParameters = this.flowParseTypeParameterDeclaration();
  1996. }
  1997. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  1998. }
  1999. parseClassSuper(node) {
  2000. super.parseClassSuper(node);
  2001. if (node.superClass && this.isRelational("<")) {
  2002. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2003. }
  2004. if (this.isContextual("implements")) {
  2005. this.next();
  2006. const implemented = node.implements = [];
  2007. do {
  2008. const node = this.startNode();
  2009. node.id = this.flowParseRestrictedIdentifier(true);
  2010. if (this.isRelational("<")) {
  2011. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2012. } else {
  2013. node.typeParameters = null;
  2014. }
  2015. implemented.push(this.finishNode(node, "ClassImplements"));
  2016. } while (this.eat(types.comma));
  2017. }
  2018. }
  2019. parsePropertyName(node) {
  2020. const variance = this.flowParseVariance();
  2021. const key = super.parsePropertyName(node);
  2022. node.variance = variance;
  2023. return key;
  2024. }
  2025. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) {
  2026. if (prop.variance) {
  2027. this.unexpected(prop.variance.start);
  2028. }
  2029. delete prop.variance;
  2030. let typeParameters;
  2031. if (this.isRelational("<")) {
  2032. typeParameters = this.flowParseTypeParameterDeclaration(false);
  2033. if (!this.match(types.parenL)) this.unexpected();
  2034. }
  2035. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc);
  2036. if (typeParameters) {
  2037. (prop.value || prop).typeParameters = typeParameters;
  2038. }
  2039. }
  2040. parseAssignableListItemTypes(param) {
  2041. if (this.eat(types.question)) {
  2042. if (param.type !== "Identifier") {
  2043. throw this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature.");
  2044. }
  2045. param.optional = true;
  2046. }
  2047. if (this.match(types.colon)) {
  2048. param.typeAnnotation = this.flowParseTypeAnnotation();
  2049. }
  2050. this.finishNode(param, param.type);
  2051. return param;
  2052. }
  2053. parseMaybeDefault(startPos, startLoc, left) {
  2054. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2055. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2056. this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`");
  2057. }
  2058. return node;
  2059. }
  2060. shouldParseDefaultImport(node) {
  2061. if (!hasTypeImportKind(node)) {
  2062. return super.shouldParseDefaultImport(node);
  2063. }
  2064. return isMaybeDefaultImport(this.state);
  2065. }
  2066. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2067. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true) : this.parseIdentifier();
  2068. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  2069. node.specifiers.push(this.finishNode(specifier, type));
  2070. }
  2071. maybeParseDefaultImportSpecifier(node) {
  2072. node.importKind = "value";
  2073. let kind = null;
  2074. if (this.match(types._typeof)) {
  2075. kind = "typeof";
  2076. } else if (this.isContextual("type")) {
  2077. kind = "type";
  2078. }
  2079. if (kind) {
  2080. const lh = this.lookahead();
  2081. if (kind === "type" && lh.type === types.star) {
  2082. this.unexpected(lh.start);
  2083. }
  2084. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2085. this.next();
  2086. node.importKind = kind;
  2087. }
  2088. }
  2089. return super.maybeParseDefaultImportSpecifier(node);
  2090. }
  2091. parseImportSpecifier(node) {
  2092. const specifier = this.startNode();
  2093. const firstIdentLoc = this.state.start;
  2094. const firstIdent = this.parseIdentifier(true);
  2095. let specifierTypeKind = null;
  2096. if (firstIdent.name === "type") {
  2097. specifierTypeKind = "type";
  2098. } else if (firstIdent.name === "typeof") {
  2099. specifierTypeKind = "typeof";
  2100. }
  2101. let isBinding = false;
  2102. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2103. const as_ident = this.parseIdentifier(true);
  2104. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2105. specifier.imported = as_ident;
  2106. specifier.importKind = specifierTypeKind;
  2107. specifier.local = as_ident.__clone();
  2108. } else {
  2109. specifier.imported = firstIdent;
  2110. specifier.importKind = null;
  2111. specifier.local = this.parseIdentifier();
  2112. }
  2113. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2114. specifier.imported = this.parseIdentifier(true);
  2115. specifier.importKind = specifierTypeKind;
  2116. if (this.eatContextual("as")) {
  2117. specifier.local = this.parseIdentifier();
  2118. } else {
  2119. isBinding = true;
  2120. specifier.local = specifier.imported.__clone();
  2121. }
  2122. } else {
  2123. isBinding = true;
  2124. specifier.imported = firstIdent;
  2125. specifier.importKind = null;
  2126. specifier.local = specifier.imported.__clone();
  2127. }
  2128. const nodeIsTypeImport = hasTypeImportKind(node);
  2129. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2130. if (nodeIsTypeImport && specifierIsTypeImport) {
  2131. this.raise(firstIdentLoc, "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");
  2132. }
  2133. if (nodeIsTypeImport || specifierIsTypeImport) {
  2134. this.checkReservedType(specifier.local.name, specifier.local.start);
  2135. }
  2136. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2137. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2138. }
  2139. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2140. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2141. }
  2142. parseFunctionParams(node, allowModifiers) {
  2143. const kind = node.kind;
  2144. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2145. node.typeParameters = this.flowParseTypeParameterDeclaration(false);
  2146. }
  2147. super.parseFunctionParams(node, allowModifiers);
  2148. }
  2149. parseVarId(decl, kind) {
  2150. super.parseVarId(decl, kind);
  2151. if (this.match(types.colon)) {
  2152. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2153. this.finishNode(decl.id, decl.id.type);
  2154. }
  2155. }
  2156. parseAsyncArrowFromCallExpression(node, call) {
  2157. if (this.match(types.colon)) {
  2158. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2159. this.state.noAnonFunctionType = true;
  2160. node.returnType = this.flowParseTypeAnnotation();
  2161. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2162. }
  2163. return super.parseAsyncArrowFromCallExpression(node, call);
  2164. }
  2165. shouldParseAsyncArrow() {
  2166. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2167. }
  2168. parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) {
  2169. let jsxError = null;
  2170. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2171. const state = this.state.clone();
  2172. try {
  2173. return super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos);
  2174. } catch (err) {
  2175. if (err instanceof SyntaxError) {
  2176. this.state = state;
  2177. const cLength = this.state.context.length;
  2178. if (this.state.context[cLength - 1] === types$1.j_oTag) {
  2179. this.state.context.length -= 2;
  2180. }
  2181. jsxError = err;
  2182. } else {
  2183. throw err;
  2184. }
  2185. }
  2186. }
  2187. if (jsxError != null || this.isRelational("<")) {
  2188. let arrowExpression;
  2189. let typeParameters;
  2190. try {
  2191. typeParameters = this.flowParseTypeParameterDeclaration();
  2192. arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos));
  2193. arrowExpression.typeParameters = typeParameters;
  2194. this.resetStartLocationFromNode(arrowExpression, typeParameters);
  2195. } catch (err) {
  2196. throw jsxError || err;
  2197. }
  2198. if (arrowExpression.type === "ArrowFunctionExpression") {
  2199. return arrowExpression;
  2200. } else if (jsxError != null) {
  2201. throw jsxError;
  2202. } else {
  2203. this.raise(typeParameters.start, "Expected an arrow function after this type parameter declaration");
  2204. }
  2205. }
  2206. return super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos);
  2207. }
  2208. parseArrow(node) {
  2209. if (this.match(types.colon)) {
  2210. const state = this.state.clone();
  2211. try {
  2212. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2213. this.state.noAnonFunctionType = true;
  2214. const typeNode = this.startNode();
  2215. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2216. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2217. if (this.canInsertSemicolon()) this.unexpected();
  2218. if (!this.match(types.arrow)) this.unexpected();
  2219. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2220. } catch (err) {
  2221. if (err instanceof SyntaxError) {
  2222. this.state = state;
  2223. } else {
  2224. throw err;
  2225. }
  2226. }
  2227. }
  2228. return super.parseArrow(node);
  2229. }
  2230. shouldParseArrow() {
  2231. return this.match(types.colon) || super.shouldParseArrow();
  2232. }
  2233. setArrowFunctionParameters(node, params) {
  2234. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2235. node.params = params;
  2236. } else {
  2237. super.setArrowFunctionParameters(node, params);
  2238. }
  2239. }
  2240. checkParams(node, allowDuplicates, isArrowFunction) {
  2241. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2242. return;
  2243. }
  2244. return super.checkParams(node, allowDuplicates, isArrowFunction);
  2245. }
  2246. parseParenAndDistinguishExpression(canBeArrow) {
  2247. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2248. }
  2249. parseSubscripts(base, startPos, startLoc, noCalls) {
  2250. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2251. this.next();
  2252. const node = this.startNodeAt(startPos, startLoc);
  2253. node.callee = base;
  2254. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2255. base = this.finishNode(node, "CallExpression");
  2256. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2257. const state = this.state.clone();
  2258. let error;
  2259. try {
  2260. const node = this.parseAsyncArrowWithTypeParameters(startPos, startLoc);
  2261. if (node) return node;
  2262. } catch (e) {
  2263. error = e;
  2264. }
  2265. this.state = state;
  2266. try {
  2267. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2268. } catch (e) {
  2269. throw error || e;
  2270. }
  2271. }
  2272. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2273. }
  2274. parseSubscript(base, startPos, startLoc, noCalls, subscriptState, maybeAsyncArrow) {
  2275. if (this.match(types.questionDot) && this.isLookaheadRelational("<")) {
  2276. this.expectPlugin("optionalChaining");
  2277. subscriptState.optionalChainMember = true;
  2278. if (noCalls) {
  2279. subscriptState.stop = true;
  2280. return base;
  2281. }
  2282. this.next();
  2283. const node = this.startNodeAt(startPos, startLoc);
  2284. node.callee = base;
  2285. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2286. this.expect(types.parenL);
  2287. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2288. node.optional = true;
  2289. return this.finishNode(node, "OptionalCallExpression");
  2290. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2291. const node = this.startNodeAt(startPos, startLoc);
  2292. node.callee = base;
  2293. const state = this.state.clone();
  2294. try {
  2295. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2296. this.expect(types.parenL);
  2297. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2298. if (subscriptState.optionalChainMember) {
  2299. node.optional = false;
  2300. return this.finishNode(node, "OptionalCallExpression");
  2301. }
  2302. return this.finishNode(node, "CallExpression");
  2303. } catch (e) {
  2304. if (e instanceof SyntaxError) {
  2305. this.state = state;
  2306. } else {
  2307. throw e;
  2308. }
  2309. }
  2310. }
  2311. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState, maybeAsyncArrow);
  2312. }
  2313. parseNewArguments(node) {
  2314. let targs = null;
  2315. if (this.shouldParseTypes() && this.isRelational("<")) {
  2316. const state = this.state.clone();
  2317. try {
  2318. targs = this.flowParseTypeParameterInstantiationCallOrNew();
  2319. } catch (e) {
  2320. if (e instanceof SyntaxError) {
  2321. this.state = state;
  2322. } else {
  2323. throw e;
  2324. }
  2325. }
  2326. }
  2327. node.typeArguments = targs;
  2328. super.parseNewArguments(node);
  2329. }
  2330. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2331. const node = this.startNodeAt(startPos, startLoc);
  2332. this.parseFunctionParams(node);
  2333. if (!this.parseArrow(node)) return;
  2334. return this.parseArrowExpression(node, undefined, true);
  2335. }
  2336. readToken_mult_modulo(code) {
  2337. const next = this.input.charCodeAt(this.state.pos + 1);
  2338. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2339. this.state.hasFlowComment = false;
  2340. this.state.pos += 2;
  2341. this.nextToken();
  2342. return;
  2343. }
  2344. super.readToken_mult_modulo(code);
  2345. }
  2346. readToken_pipe_amp(code) {
  2347. const next = this.input.charCodeAt(this.state.pos + 1);
  2348. if (code === 124 && next === 125) {
  2349. this.finishOp(types.braceBarR, 2);
  2350. return;
  2351. }
  2352. super.readToken_pipe_amp(code);
  2353. }
  2354. parseTopLevel(file, program) {
  2355. const fileNode = super.parseTopLevel(file, program);
  2356. if (this.state.hasFlowComment) {
  2357. this.unexpected(null, "Unterminated flow-comment");
  2358. }
  2359. return fileNode;
  2360. }
  2361. skipBlockComment() {
  2362. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2363. if (this.state.hasFlowComment) {
  2364. this.unexpected(null, "Cannot have a flow comment inside another flow comment");
  2365. }
  2366. this.hasFlowCommentCompletion();
  2367. this.state.pos += this.skipFlowComment();
  2368. this.state.hasFlowComment = true;
  2369. return;
  2370. }
  2371. if (this.state.hasFlowComment) {
  2372. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2373. if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment");
  2374. this.state.pos = end + 3;
  2375. return;
  2376. }
  2377. super.skipBlockComment();
  2378. }
  2379. skipFlowComment() {
  2380. const {
  2381. pos
  2382. } = this.state;
  2383. let shiftToFirstNonWhiteSpace = 2;
  2384. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2385. shiftToFirstNonWhiteSpace++;
  2386. }
  2387. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2388. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2389. if (ch2 === 58 && ch3 === 58) {
  2390. return shiftToFirstNonWhiteSpace + 2;
  2391. }
  2392. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2393. return shiftToFirstNonWhiteSpace + 12;
  2394. }
  2395. if (ch2 === 58 && ch3 !== 58) {
  2396. return shiftToFirstNonWhiteSpace;
  2397. }
  2398. return false;
  2399. }
  2400. hasFlowCommentCompletion() {
  2401. const end = this.input.indexOf("*/", this.state.pos);
  2402. if (end === -1) {
  2403. this.raise(this.state.pos, "Unterminated comment");
  2404. }
  2405. }
  2406. });
  2407. const entities = {
  2408. quot: "\u0022",
  2409. amp: "&",
  2410. apos: "\u0027",
  2411. lt: "<",
  2412. gt: ">",
  2413. nbsp: "\u00A0",
  2414. iexcl: "\u00A1",
  2415. cent: "\u00A2",
  2416. pound: "\u00A3",
  2417. curren: "\u00A4",
  2418. yen: "\u00A5",
  2419. brvbar: "\u00A6",
  2420. sect: "\u00A7",
  2421. uml: "\u00A8",
  2422. copy: "\u00A9",
  2423. ordf: "\u00AA",
  2424. laquo: "\u00AB",
  2425. not: "\u00AC",
  2426. shy: "\u00AD",
  2427. reg: "\u00AE",
  2428. macr: "\u00AF",
  2429. deg: "\u00B0",
  2430. plusmn: "\u00B1",
  2431. sup2: "\u00B2",
  2432. sup3: "\u00B3",
  2433. acute: "\u00B4",
  2434. micro: "\u00B5",
  2435. para: "\u00B6",
  2436. middot: "\u00B7",
  2437. cedil: "\u00B8",
  2438. sup1: "\u00B9",
  2439. ordm: "\u00BA",
  2440. raquo: "\u00BB",
  2441. frac14: "\u00BC",
  2442. frac12: "\u00BD",
  2443. frac34: "\u00BE",
  2444. iquest: "\u00BF",
  2445. Agrave: "\u00C0",
  2446. Aacute: "\u00C1",
  2447. Acirc: "\u00C2",
  2448. Atilde: "\u00C3",
  2449. Auml: "\u00C4",
  2450. Aring: "\u00C5",
  2451. AElig: "\u00C6",
  2452. Ccedil: "\u00C7",
  2453. Egrave: "\u00C8",
  2454. Eacute: "\u00C9",
  2455. Ecirc: "\u00CA",
  2456. Euml: "\u00CB",
  2457. Igrave: "\u00CC",
  2458. Iacute: "\u00CD",
  2459. Icirc: "\u00CE",
  2460. Iuml: "\u00CF",
  2461. ETH: "\u00D0",
  2462. Ntilde: "\u00D1",
  2463. Ograve: "\u00D2",
  2464. Oacute: "\u00D3",
  2465. Ocirc: "\u00D4",
  2466. Otilde: "\u00D5",
  2467. Ouml: "\u00D6",
  2468. times: "\u00D7",
  2469. Oslash: "\u00D8",
  2470. Ugrave: "\u00D9",
  2471. Uacute: "\u00DA",
  2472. Ucirc: "\u00DB",
  2473. Uuml: "\u00DC",
  2474. Yacute: "\u00DD",
  2475. THORN: "\u00DE",
  2476. szlig: "\u00DF",
  2477. agrave: "\u00E0",
  2478. aacute: "\u00E1",
  2479. acirc: "\u00E2",
  2480. atilde: "\u00E3",
  2481. auml: "\u00E4",
  2482. aring: "\u00E5",
  2483. aelig: "\u00E6",
  2484. ccedil: "\u00E7",
  2485. egrave: "\u00E8",
  2486. eacute: "\u00E9",
  2487. ecirc: "\u00EA",
  2488. euml: "\u00EB",
  2489. igrave: "\u00EC",
  2490. iacute: "\u00ED",
  2491. icirc: "\u00EE",
  2492. iuml: "\u00EF",
  2493. eth: "\u00F0",
  2494. ntilde: "\u00F1",
  2495. ograve: "\u00F2",
  2496. oacute: "\u00F3",
  2497. ocirc: "\u00F4",
  2498. otilde: "\u00F5",
  2499. ouml: "\u00F6",
  2500. divide: "\u00F7",
  2501. oslash: "\u00F8",
  2502. ugrave: "\u00F9",
  2503. uacute: "\u00FA",
  2504. ucirc: "\u00FB",
  2505. uuml: "\u00FC",
  2506. yacute: "\u00FD",
  2507. thorn: "\u00FE",
  2508. yuml: "\u00FF",
  2509. OElig: "\u0152",
  2510. oelig: "\u0153",
  2511. Scaron: "\u0160",
  2512. scaron: "\u0161",
  2513. Yuml: "\u0178",
  2514. fnof: "\u0192",
  2515. circ: "\u02C6",
  2516. tilde: "\u02DC",
  2517. Alpha: "\u0391",
  2518. Beta: "\u0392",
  2519. Gamma: "\u0393",
  2520. Delta: "\u0394",
  2521. Epsilon: "\u0395",
  2522. Zeta: "\u0396",
  2523. Eta: "\u0397",
  2524. Theta: "\u0398",
  2525. Iota: "\u0399",
  2526. Kappa: "\u039A",
  2527. Lambda: "\u039B",
  2528. Mu: "\u039C",
  2529. Nu: "\u039D",
  2530. Xi: "\u039E",
  2531. Omicron: "\u039F",
  2532. Pi: "\u03A0",
  2533. Rho: "\u03A1",
  2534. Sigma: "\u03A3",
  2535. Tau: "\u03A4",
  2536. Upsilon: "\u03A5",
  2537. Phi: "\u03A6",
  2538. Chi: "\u03A7",
  2539. Psi: "\u03A8",
  2540. Omega: "\u03A9",
  2541. alpha: "\u03B1",
  2542. beta: "\u03B2",
  2543. gamma: "\u03B3",
  2544. delta: "\u03B4",
  2545. epsilon: "\u03B5",
  2546. zeta: "\u03B6",
  2547. eta: "\u03B7",
  2548. theta: "\u03B8",
  2549. iota: "\u03B9",
  2550. kappa: "\u03BA",
  2551. lambda: "\u03BB",
  2552. mu: "\u03BC",
  2553. nu: "\u03BD",
  2554. xi: "\u03BE",
  2555. omicron: "\u03BF",
  2556. pi: "\u03C0",
  2557. rho: "\u03C1",
  2558. sigmaf: "\u03C2",
  2559. sigma: "\u03C3",
  2560. tau: "\u03C4",
  2561. upsilon: "\u03C5",
  2562. phi: "\u03C6",
  2563. chi: "\u03C7",
  2564. psi: "\u03C8",
  2565. omega: "\u03C9",
  2566. thetasym: "\u03D1",
  2567. upsih: "\u03D2",
  2568. piv: "\u03D6",
  2569. ensp: "\u2002",
  2570. emsp: "\u2003",
  2571. thinsp: "\u2009",
  2572. zwnj: "\u200C",
  2573. zwj: "\u200D",
  2574. lrm: "\u200E",
  2575. rlm: "\u200F",
  2576. ndash: "\u2013",
  2577. mdash: "\u2014",
  2578. lsquo: "\u2018",
  2579. rsquo: "\u2019",
  2580. sbquo: "\u201A",
  2581. ldquo: "\u201C",
  2582. rdquo: "\u201D",
  2583. bdquo: "\u201E",
  2584. dagger: "\u2020",
  2585. Dagger: "\u2021",
  2586. bull: "\u2022",
  2587. hellip: "\u2026",
  2588. permil: "\u2030",
  2589. prime: "\u2032",
  2590. Prime: "\u2033",
  2591. lsaquo: "\u2039",
  2592. rsaquo: "\u203A",
  2593. oline: "\u203E",
  2594. frasl: "\u2044",
  2595. euro: "\u20AC",
  2596. image: "\u2111",
  2597. weierp: "\u2118",
  2598. real: "\u211C",
  2599. trade: "\u2122",
  2600. alefsym: "\u2135",
  2601. larr: "\u2190",
  2602. uarr: "\u2191",
  2603. rarr: "\u2192",
  2604. darr: "\u2193",
  2605. harr: "\u2194",
  2606. crarr: "\u21B5",
  2607. lArr: "\u21D0",
  2608. uArr: "\u21D1",
  2609. rArr: "\u21D2",
  2610. dArr: "\u21D3",
  2611. hArr: "\u21D4",
  2612. forall: "\u2200",
  2613. part: "\u2202",
  2614. exist: "\u2203",
  2615. empty: "\u2205",
  2616. nabla: "\u2207",
  2617. isin: "\u2208",
  2618. notin: "\u2209",
  2619. ni: "\u220B",
  2620. prod: "\u220F",
  2621. sum: "\u2211",
  2622. minus: "\u2212",
  2623. lowast: "\u2217",
  2624. radic: "\u221A",
  2625. prop: "\u221D",
  2626. infin: "\u221E",
  2627. ang: "\u2220",
  2628. and: "\u2227",
  2629. or: "\u2228",
  2630. cap: "\u2229",
  2631. cup: "\u222A",
  2632. int: "\u222B",
  2633. there4: "\u2234",
  2634. sim: "\u223C",
  2635. cong: "\u2245",
  2636. asymp: "\u2248",
  2637. ne: "\u2260",
  2638. equiv: "\u2261",
  2639. le: "\u2264",
  2640. ge: "\u2265",
  2641. sub: "\u2282",
  2642. sup: "\u2283",
  2643. nsub: "\u2284",
  2644. sube: "\u2286",
  2645. supe: "\u2287",
  2646. oplus: "\u2295",
  2647. otimes: "\u2297",
  2648. perp: "\u22A5",
  2649. sdot: "\u22C5",
  2650. lceil: "\u2308",
  2651. rceil: "\u2309",
  2652. lfloor: "\u230A",
  2653. rfloor: "\u230B",
  2654. lang: "\u2329",
  2655. rang: "\u232A",
  2656. loz: "\u25CA",
  2657. spades: "\u2660",
  2658. clubs: "\u2663",
  2659. hearts: "\u2665",
  2660. diams: "\u2666"
  2661. };
  2662. const HEX_NUMBER = /^[\da-fA-F]+$/;
  2663. const DECIMAL_NUMBER = /^\d+$/;
  2664. types$1.j_oTag = new TokContext("<tag", false);
  2665. types$1.j_cTag = new TokContext("</tag", false);
  2666. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  2667. types.jsxName = new TokenType("jsxName");
  2668. types.jsxText = new TokenType("jsxText", {
  2669. beforeExpr: true
  2670. });
  2671. types.jsxTagStart = new TokenType("jsxTagStart", {
  2672. startsExpr: true
  2673. });
  2674. types.jsxTagEnd = new TokenType("jsxTagEnd");
  2675. types.jsxTagStart.updateContext = function () {
  2676. this.state.context.push(types$1.j_expr);
  2677. this.state.context.push(types$1.j_oTag);
  2678. this.state.exprAllowed = false;
  2679. };
  2680. types.jsxTagEnd.updateContext = function (prevType) {
  2681. const out = this.state.context.pop();
  2682. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  2683. this.state.context.pop();
  2684. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  2685. } else {
  2686. this.state.exprAllowed = true;
  2687. }
  2688. };
  2689. function isFragment(object) {
  2690. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  2691. }
  2692. function getQualifiedJSXName(object) {
  2693. if (object.type === "JSXIdentifier") {
  2694. return object.name;
  2695. }
  2696. if (object.type === "JSXNamespacedName") {
  2697. return object.namespace.name + ":" + object.name.name;
  2698. }
  2699. if (object.type === "JSXMemberExpression") {
  2700. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  2701. }
  2702. throw new Error("Node had unexpected type: " + object.type);
  2703. }
  2704. var jsx = (superClass => class extends superClass {
  2705. jsxReadToken() {
  2706. let out = "";
  2707. let chunkStart = this.state.pos;
  2708. for (;;) {
  2709. if (this.state.pos >= this.length) {
  2710. this.raise(this.state.start, "Unterminated JSX contents");
  2711. }
  2712. const ch = this.input.charCodeAt(this.state.pos);
  2713. switch (ch) {
  2714. case 60:
  2715. case 123:
  2716. if (this.state.pos === this.state.start) {
  2717. if (ch === 60 && this.state.exprAllowed) {
  2718. ++this.state.pos;
  2719. return this.finishToken(types.jsxTagStart);
  2720. }
  2721. return super.getTokenFromCode(ch);
  2722. }
  2723. out += this.input.slice(chunkStart, this.state.pos);
  2724. return this.finishToken(types.jsxText, out);
  2725. case 38:
  2726. out += this.input.slice(chunkStart, this.state.pos);
  2727. out += this.jsxReadEntity();
  2728. chunkStart = this.state.pos;
  2729. break;
  2730. default:
  2731. if (isNewLine(ch)) {
  2732. out += this.input.slice(chunkStart, this.state.pos);
  2733. out += this.jsxReadNewLine(true);
  2734. chunkStart = this.state.pos;
  2735. } else {
  2736. ++this.state.pos;
  2737. }
  2738. }
  2739. }
  2740. }
  2741. jsxReadNewLine(normalizeCRLF) {
  2742. const ch = this.input.charCodeAt(this.state.pos);
  2743. let out;
  2744. ++this.state.pos;
  2745. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  2746. ++this.state.pos;
  2747. out = normalizeCRLF ? "\n" : "\r\n";
  2748. } else {
  2749. out = String.fromCharCode(ch);
  2750. }
  2751. ++this.state.curLine;
  2752. this.state.lineStart = this.state.pos;
  2753. return out;
  2754. }
  2755. jsxReadString(quote) {
  2756. let out = "";
  2757. let chunkStart = ++this.state.pos;
  2758. for (;;) {
  2759. if (this.state.pos >= this.length) {
  2760. this.raise(this.state.start, "Unterminated string constant");
  2761. }
  2762. const ch = this.input.charCodeAt(this.state.pos);
  2763. if (ch === quote) break;
  2764. if (ch === 38) {
  2765. out += this.input.slice(chunkStart, this.state.pos);
  2766. out += this.jsxReadEntity();
  2767. chunkStart = this.state.pos;
  2768. } else if (isNewLine(ch)) {
  2769. out += this.input.slice(chunkStart, this.state.pos);
  2770. out += this.jsxReadNewLine(false);
  2771. chunkStart = this.state.pos;
  2772. } else {
  2773. ++this.state.pos;
  2774. }
  2775. }
  2776. out += this.input.slice(chunkStart, this.state.pos++);
  2777. return this.finishToken(types.string, out);
  2778. }
  2779. jsxReadEntity() {
  2780. let str = "";
  2781. let count = 0;
  2782. let entity;
  2783. let ch = this.input[this.state.pos];
  2784. const startPos = ++this.state.pos;
  2785. while (this.state.pos < this.length && count++ < 10) {
  2786. ch = this.input[this.state.pos++];
  2787. if (ch === ";") {
  2788. if (str[0] === "#") {
  2789. if (str[1] === "x") {
  2790. str = str.substr(2);
  2791. if (HEX_NUMBER.test(str)) {
  2792. entity = String.fromCodePoint(parseInt(str, 16));
  2793. }
  2794. } else {
  2795. str = str.substr(1);
  2796. if (DECIMAL_NUMBER.test(str)) {
  2797. entity = String.fromCodePoint(parseInt(str, 10));
  2798. }
  2799. }
  2800. } else {
  2801. entity = entities[str];
  2802. }
  2803. break;
  2804. }
  2805. str += ch;
  2806. }
  2807. if (!entity) {
  2808. this.state.pos = startPos;
  2809. return "&";
  2810. }
  2811. return entity;
  2812. }
  2813. jsxReadWord() {
  2814. let ch;
  2815. const start = this.state.pos;
  2816. do {
  2817. ch = this.input.charCodeAt(++this.state.pos);
  2818. } while (isIdentifierChar(ch) || ch === 45);
  2819. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  2820. }
  2821. jsxParseIdentifier() {
  2822. const node = this.startNode();
  2823. if (this.match(types.jsxName)) {
  2824. node.name = this.state.value;
  2825. } else if (this.state.type.keyword) {
  2826. node.name = this.state.type.keyword;
  2827. } else {
  2828. this.unexpected();
  2829. }
  2830. this.next();
  2831. return this.finishNode(node, "JSXIdentifier");
  2832. }
  2833. jsxParseNamespacedName() {
  2834. const startPos = this.state.start;
  2835. const startLoc = this.state.startLoc;
  2836. const name = this.jsxParseIdentifier();
  2837. if (!this.eat(types.colon)) return name;
  2838. const node = this.startNodeAt(startPos, startLoc);
  2839. node.namespace = name;
  2840. node.name = this.jsxParseIdentifier();
  2841. return this.finishNode(node, "JSXNamespacedName");
  2842. }
  2843. jsxParseElementName() {
  2844. const startPos = this.state.start;
  2845. const startLoc = this.state.startLoc;
  2846. let node = this.jsxParseNamespacedName();
  2847. while (this.eat(types.dot)) {
  2848. const newNode = this.startNodeAt(startPos, startLoc);
  2849. newNode.object = node;
  2850. newNode.property = this.jsxParseIdentifier();
  2851. node = this.finishNode(newNode, "JSXMemberExpression");
  2852. }
  2853. return node;
  2854. }
  2855. jsxParseAttributeValue() {
  2856. let node;
  2857. switch (this.state.type) {
  2858. case types.braceL:
  2859. node = this.jsxParseExpressionContainer();
  2860. if (node.expression.type === "JSXEmptyExpression") {
  2861. throw this.raise(node.start, "JSX attributes must only be assigned a non-empty expression");
  2862. } else {
  2863. return node;
  2864. }
  2865. case types.jsxTagStart:
  2866. case types.string:
  2867. return this.parseExprAtom();
  2868. default:
  2869. throw this.raise(this.state.start, "JSX value should be either an expression or a quoted JSX text");
  2870. }
  2871. }
  2872. jsxParseEmptyExpression() {
  2873. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  2874. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  2875. }
  2876. jsxParseSpreadChild() {
  2877. const node = this.startNode();
  2878. this.expect(types.braceL);
  2879. this.expect(types.ellipsis);
  2880. node.expression = this.parseExpression();
  2881. this.expect(types.braceR);
  2882. return this.finishNode(node, "JSXSpreadChild");
  2883. }
  2884. jsxParseExpressionContainer() {
  2885. const node = this.startNode();
  2886. this.next();
  2887. if (this.match(types.braceR)) {
  2888. node.expression = this.jsxParseEmptyExpression();
  2889. } else {
  2890. node.expression = this.parseExpression();
  2891. }
  2892. this.expect(types.braceR);
  2893. return this.finishNode(node, "JSXExpressionContainer");
  2894. }
  2895. jsxParseAttribute() {
  2896. const node = this.startNode();
  2897. if (this.eat(types.braceL)) {
  2898. this.expect(types.ellipsis);
  2899. node.argument = this.parseMaybeAssign();
  2900. this.expect(types.braceR);
  2901. return this.finishNode(node, "JSXSpreadAttribute");
  2902. }
  2903. node.name = this.jsxParseNamespacedName();
  2904. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  2905. return this.finishNode(node, "JSXAttribute");
  2906. }
  2907. jsxParseOpeningElementAt(startPos, startLoc) {
  2908. const node = this.startNodeAt(startPos, startLoc);
  2909. if (this.match(types.jsxTagEnd)) {
  2910. this.expect(types.jsxTagEnd);
  2911. return this.finishNode(node, "JSXOpeningFragment");
  2912. }
  2913. node.name = this.jsxParseElementName();
  2914. return this.jsxParseOpeningElementAfterName(node);
  2915. }
  2916. jsxParseOpeningElementAfterName(node) {
  2917. const attributes = [];
  2918. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  2919. attributes.push(this.jsxParseAttribute());
  2920. }
  2921. node.attributes = attributes;
  2922. node.selfClosing = this.eat(types.slash);
  2923. this.expect(types.jsxTagEnd);
  2924. return this.finishNode(node, "JSXOpeningElement");
  2925. }
  2926. jsxParseClosingElementAt(startPos, startLoc) {
  2927. const node = this.startNodeAt(startPos, startLoc);
  2928. if (this.match(types.jsxTagEnd)) {
  2929. this.expect(types.jsxTagEnd);
  2930. return this.finishNode(node, "JSXClosingFragment");
  2931. }
  2932. node.name = this.jsxParseElementName();
  2933. this.expect(types.jsxTagEnd);
  2934. return this.finishNode(node, "JSXClosingElement");
  2935. }
  2936. jsxParseElementAt(startPos, startLoc) {
  2937. const node = this.startNodeAt(startPos, startLoc);
  2938. const children = [];
  2939. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  2940. let closingElement = null;
  2941. if (!openingElement.selfClosing) {
  2942. contents: for (;;) {
  2943. switch (this.state.type) {
  2944. case types.jsxTagStart:
  2945. startPos = this.state.start;
  2946. startLoc = this.state.startLoc;
  2947. this.next();
  2948. if (this.eat(types.slash)) {
  2949. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  2950. break contents;
  2951. }
  2952. children.push(this.jsxParseElementAt(startPos, startLoc));
  2953. break;
  2954. case types.jsxText:
  2955. children.push(this.parseExprAtom());
  2956. break;
  2957. case types.braceL:
  2958. if (this.lookahead().type === types.ellipsis) {
  2959. children.push(this.jsxParseSpreadChild());
  2960. } else {
  2961. children.push(this.jsxParseExpressionContainer());
  2962. }
  2963. break;
  2964. default:
  2965. throw this.unexpected();
  2966. }
  2967. }
  2968. if (isFragment(openingElement) && !isFragment(closingElement)) {
  2969. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <>");
  2970. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  2971. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
  2972. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  2973. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  2974. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
  2975. }
  2976. }
  2977. }
  2978. if (isFragment(openingElement)) {
  2979. node.openingFragment = openingElement;
  2980. node.closingFragment = closingElement;
  2981. } else {
  2982. node.openingElement = openingElement;
  2983. node.closingElement = closingElement;
  2984. }
  2985. node.children = children;
  2986. if (this.match(types.relational) && this.state.value === "<") {
  2987. this.raise(this.state.start, "Adjacent JSX elements must be wrapped in an enclosing tag. " + "Did you want a JSX fragment <>...</>?");
  2988. }
  2989. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  2990. }
  2991. jsxParseElement() {
  2992. const startPos = this.state.start;
  2993. const startLoc = this.state.startLoc;
  2994. this.next();
  2995. return this.jsxParseElementAt(startPos, startLoc);
  2996. }
  2997. parseExprAtom(refShortHandDefaultPos) {
  2998. if (this.match(types.jsxText)) {
  2999. return this.parseLiteral(this.state.value, "JSXText");
  3000. } else if (this.match(types.jsxTagStart)) {
  3001. return this.jsxParseElement();
  3002. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3003. this.finishToken(types.jsxTagStart);
  3004. return this.jsxParseElement();
  3005. } else {
  3006. return super.parseExprAtom(refShortHandDefaultPos);
  3007. }
  3008. }
  3009. getTokenFromCode(code) {
  3010. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  3011. const context = this.curContext();
  3012. if (context === types$1.j_expr) {
  3013. return this.jsxReadToken();
  3014. }
  3015. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  3016. if (isIdentifierStart(code)) {
  3017. return this.jsxReadWord();
  3018. }
  3019. if (code === 62) {
  3020. ++this.state.pos;
  3021. return this.finishToken(types.jsxTagEnd);
  3022. }
  3023. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  3024. return this.jsxReadString(code);
  3025. }
  3026. }
  3027. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  3028. ++this.state.pos;
  3029. return this.finishToken(types.jsxTagStart);
  3030. }
  3031. return super.getTokenFromCode(code);
  3032. }
  3033. updateContext(prevType) {
  3034. if (this.match(types.braceL)) {
  3035. const curContext = this.curContext();
  3036. if (curContext === types$1.j_oTag) {
  3037. this.state.context.push(types$1.braceExpression);
  3038. } else if (curContext === types$1.j_expr) {
  3039. this.state.context.push(types$1.templateQuasi);
  3040. } else {
  3041. super.updateContext(prevType);
  3042. }
  3043. this.state.exprAllowed = true;
  3044. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  3045. this.state.context.length -= 2;
  3046. this.state.context.push(types$1.j_cTag);
  3047. this.state.exprAllowed = false;
  3048. } else {
  3049. return super.updateContext(prevType);
  3050. }
  3051. }
  3052. });
  3053. class Scope {
  3054. constructor(flags) {
  3055. this.var = [];
  3056. this.lexical = [];
  3057. this.functions = [];
  3058. this.flags = flags;
  3059. }
  3060. }
  3061. class ScopeHandler {
  3062. constructor(raise, inModule) {
  3063. this.scopeStack = [];
  3064. this.undefinedExports = new Map();
  3065. this.raise = raise;
  3066. this.inModule = inModule;
  3067. }
  3068. get inFunction() {
  3069. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  3070. }
  3071. get inGenerator() {
  3072. return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
  3073. }
  3074. get inAsync() {
  3075. return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;
  3076. }
  3077. get allowSuper() {
  3078. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  3079. }
  3080. get allowDirectSuper() {
  3081. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  3082. }
  3083. get inNonArrowFunction() {
  3084. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  3085. }
  3086. get treatFunctionsAsVar() {
  3087. return this.treatFunctionsAsVarInScope(this.currentScope());
  3088. }
  3089. createScope(flags) {
  3090. return new Scope(flags);
  3091. }
  3092. enter(flags) {
  3093. this.scopeStack.push(this.createScope(flags));
  3094. }
  3095. exit() {
  3096. this.scopeStack.pop();
  3097. }
  3098. treatFunctionsAsVarInScope(scope) {
  3099. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  3100. }
  3101. declareName(name, bindingType, pos) {
  3102. let scope = this.currentScope();
  3103. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  3104. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3105. if (bindingType & BIND_SCOPE_FUNCTION) {
  3106. scope.functions.push(name);
  3107. } else {
  3108. scope.lexical.push(name);
  3109. }
  3110. if (bindingType & BIND_SCOPE_LEXICAL) {
  3111. this.maybeExportDefined(scope, name);
  3112. }
  3113. } else if (bindingType & BIND_SCOPE_VAR) {
  3114. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  3115. scope = this.scopeStack[i];
  3116. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3117. scope.var.push(name);
  3118. this.maybeExportDefined(scope, name);
  3119. if (scope.flags & SCOPE_VAR) break;
  3120. }
  3121. }
  3122. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  3123. this.undefinedExports.delete(name);
  3124. }
  3125. }
  3126. maybeExportDefined(scope, name) {
  3127. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  3128. this.undefinedExports.delete(name);
  3129. }
  3130. }
  3131. checkRedeclarationInScope(scope, name, bindingType, pos) {
  3132. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  3133. this.raise(pos, `Identifier '${name}' has already been declared`);
  3134. }
  3135. }
  3136. isRedeclaredInScope(scope, name, bindingType) {
  3137. if (!(bindingType & BIND_KIND_VALUE)) return false;
  3138. if (bindingType & BIND_SCOPE_LEXICAL) {
  3139. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  3140. }
  3141. if (bindingType & BIND_SCOPE_FUNCTION) {
  3142. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  3143. }
  3144. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  3145. }
  3146. checkLocalExport(id) {
  3147. 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) {
  3148. this.undefinedExports.set(id.name, id.start);
  3149. }
  3150. }
  3151. currentScope() {
  3152. return this.scopeStack[this.scopeStack.length - 1];
  3153. }
  3154. currentVarScope() {
  3155. for (let i = this.scopeStack.length - 1;; i--) {
  3156. const scope = this.scopeStack[i];
  3157. if (scope.flags & SCOPE_VAR) {
  3158. return scope;
  3159. }
  3160. }
  3161. }
  3162. currentThisScope() {
  3163. for (let i = this.scopeStack.length - 1;; i--) {
  3164. const scope = this.scopeStack[i];
  3165. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  3166. return scope;
  3167. }
  3168. }
  3169. }
  3170. }
  3171. class TypeScriptScope extends Scope {
  3172. constructor(...args) {
  3173. super(...args);
  3174. this.types = [];
  3175. this.enums = [];
  3176. this.constEnums = [];
  3177. this.classes = [];
  3178. this.exportOnlyBindings = [];
  3179. }
  3180. }
  3181. class TypeScriptScopeHandler extends ScopeHandler {
  3182. createScope(flags) {
  3183. return new TypeScriptScope(flags);
  3184. }
  3185. declareName(name, bindingType, pos) {
  3186. const scope = this.currentScope();
  3187. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  3188. this.maybeExportDefined(scope, name);
  3189. scope.exportOnlyBindings.push(name);
  3190. return;
  3191. }
  3192. super.declareName(...arguments);
  3193. if (bindingType & BIND_KIND_TYPE) {
  3194. if (!(bindingType & BIND_KIND_VALUE)) {
  3195. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3196. this.maybeExportDefined(scope, name);
  3197. }
  3198. scope.types.push(name);
  3199. }
  3200. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  3201. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  3202. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  3203. }
  3204. isRedeclaredInScope(scope, name, bindingType) {
  3205. if (scope.enums.indexOf(name) > -1) {
  3206. if (bindingType & BIND_FLAGS_TS_ENUM) {
  3207. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  3208. const wasConst = scope.constEnums.indexOf(name) > -1;
  3209. return isConst !== wasConst;
  3210. }
  3211. return true;
  3212. }
  3213. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  3214. if (scope.lexical.indexOf(name) > -1) {
  3215. return !!(bindingType & BIND_KIND_VALUE);
  3216. } else {
  3217. return false;
  3218. }
  3219. }
  3220. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  3221. return true;
  3222. }
  3223. return super.isRedeclaredInScope(...arguments);
  3224. }
  3225. checkLocalExport(id) {
  3226. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  3227. super.checkLocalExport(id);
  3228. }
  3229. }
  3230. }
  3231. function nonNull(x) {
  3232. if (x == null) {
  3233. throw new Error(`Unexpected ${x} value.`);
  3234. }
  3235. return x;
  3236. }
  3237. function assert(x) {
  3238. if (!x) {
  3239. throw new Error("Assert fail");
  3240. }
  3241. }
  3242. function keywordTypeFromName(value) {
  3243. switch (value) {
  3244. case "any":
  3245. return "TSAnyKeyword";
  3246. case "boolean":
  3247. return "TSBooleanKeyword";
  3248. case "bigint":
  3249. return "TSBigIntKeyword";
  3250. case "never":
  3251. return "TSNeverKeyword";
  3252. case "number":
  3253. return "TSNumberKeyword";
  3254. case "object":
  3255. return "TSObjectKeyword";
  3256. case "string":
  3257. return "TSStringKeyword";
  3258. case "symbol":
  3259. return "TSSymbolKeyword";
  3260. case "undefined":
  3261. return "TSUndefinedKeyword";
  3262. case "unknown":
  3263. return "TSUnknownKeyword";
  3264. default:
  3265. return undefined;
  3266. }
  3267. }
  3268. var typescript = (superClass => class extends superClass {
  3269. getScopeHandler() {
  3270. return TypeScriptScopeHandler;
  3271. }
  3272. tsIsIdentifier() {
  3273. return this.match(types.name);
  3274. }
  3275. tsNextTokenCanFollowModifier() {
  3276. this.next();
  3277. 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);
  3278. }
  3279. tsParseModifier(allowedModifiers) {
  3280. if (!this.match(types.name)) {
  3281. return undefined;
  3282. }
  3283. const modifier = this.state.value;
  3284. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  3285. return modifier;
  3286. }
  3287. return undefined;
  3288. }
  3289. tsIsListTerminator(kind) {
  3290. switch (kind) {
  3291. case "EnumMembers":
  3292. case "TypeMembers":
  3293. return this.match(types.braceR);
  3294. case "HeritageClauseElement":
  3295. return this.match(types.braceL);
  3296. case "TupleElementTypes":
  3297. return this.match(types.bracketR);
  3298. case "TypeParametersOrArguments":
  3299. return this.isRelational(">");
  3300. }
  3301. throw new Error("Unreachable");
  3302. }
  3303. tsParseList(kind, parseElement) {
  3304. const result = [];
  3305. while (!this.tsIsListTerminator(kind)) {
  3306. result.push(parseElement());
  3307. }
  3308. return result;
  3309. }
  3310. tsParseDelimitedList(kind, parseElement) {
  3311. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  3312. }
  3313. tsTryParseDelimitedList(kind, parseElement) {
  3314. return this.tsParseDelimitedListWorker(kind, parseElement, false);
  3315. }
  3316. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  3317. const result = [];
  3318. while (true) {
  3319. if (this.tsIsListTerminator(kind)) {
  3320. break;
  3321. }
  3322. const element = parseElement();
  3323. if (element == null) {
  3324. return undefined;
  3325. }
  3326. result.push(element);
  3327. if (this.eat(types.comma)) {
  3328. continue;
  3329. }
  3330. if (this.tsIsListTerminator(kind)) {
  3331. break;
  3332. }
  3333. if (expectSuccess) {
  3334. this.expect(types.comma);
  3335. }
  3336. return undefined;
  3337. }
  3338. return result;
  3339. }
  3340. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  3341. if (!skipFirstToken) {
  3342. if (bracket) {
  3343. this.expect(types.bracketL);
  3344. } else {
  3345. this.expectRelational("<");
  3346. }
  3347. }
  3348. const result = this.tsParseDelimitedList(kind, parseElement);
  3349. if (bracket) {
  3350. this.expect(types.bracketR);
  3351. } else {
  3352. this.expectRelational(">");
  3353. }
  3354. return result;
  3355. }
  3356. tsParseImportType() {
  3357. const node = this.startNode();
  3358. this.expect(types._import);
  3359. this.expect(types.parenL);
  3360. if (!this.match(types.string)) {
  3361. throw this.unexpected(null, "Argument in a type import must be a string literal");
  3362. }
  3363. node.argument = this.parseExprAtom();
  3364. this.expect(types.parenR);
  3365. if (this.eat(types.dot)) {
  3366. node.qualifier = this.tsParseEntityName(true);
  3367. }
  3368. if (this.isRelational("<")) {
  3369. node.typeParameters = this.tsParseTypeArguments();
  3370. }
  3371. return this.finishNode(node, "TSImportType");
  3372. }
  3373. tsParseEntityName(allowReservedWords) {
  3374. let entity = this.parseIdentifier();
  3375. while (this.eat(types.dot)) {
  3376. const node = this.startNodeAtNode(entity);
  3377. node.left = entity;
  3378. node.right = this.parseIdentifier(allowReservedWords);
  3379. entity = this.finishNode(node, "TSQualifiedName");
  3380. }
  3381. return entity;
  3382. }
  3383. tsParseTypeReference() {
  3384. const node = this.startNode();
  3385. node.typeName = this.tsParseEntityName(false);
  3386. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  3387. node.typeParameters = this.tsParseTypeArguments();
  3388. }
  3389. return this.finishNode(node, "TSTypeReference");
  3390. }
  3391. tsParseThisTypePredicate(lhs) {
  3392. this.next();
  3393. const node = this.startNodeAtNode(lhs);
  3394. node.parameterName = lhs;
  3395. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  3396. return this.finishNode(node, "TSTypePredicate");
  3397. }
  3398. tsParseThisTypeNode() {
  3399. const node = this.startNode();
  3400. this.next();
  3401. return this.finishNode(node, "TSThisType");
  3402. }
  3403. tsParseTypeQuery() {
  3404. const node = this.startNode();
  3405. this.expect(types._typeof);
  3406. if (this.match(types._import)) {
  3407. node.exprName = this.tsParseImportType();
  3408. } else {
  3409. node.exprName = this.tsParseEntityName(true);
  3410. }
  3411. return this.finishNode(node, "TSTypeQuery");
  3412. }
  3413. tsParseTypeParameter() {
  3414. const node = this.startNode();
  3415. node.name = this.parseIdentifierName(node.start);
  3416. node.constraint = this.tsEatThenParseType(types._extends);
  3417. node.default = this.tsEatThenParseType(types.eq);
  3418. return this.finishNode(node, "TSTypeParameter");
  3419. }
  3420. tsTryParseTypeParameters() {
  3421. if (this.isRelational("<")) {
  3422. return this.tsParseTypeParameters();
  3423. }
  3424. }
  3425. tsParseTypeParameters() {
  3426. const node = this.startNode();
  3427. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  3428. this.next();
  3429. } else {
  3430. this.unexpected();
  3431. }
  3432. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  3433. return this.finishNode(node, "TSTypeParameterDeclaration");
  3434. }
  3435. tsTryNextParseConstantContext() {
  3436. if (this.lookahead().type === types._const) {
  3437. this.next();
  3438. return this.tsParseTypeReference();
  3439. }
  3440. return null;
  3441. }
  3442. tsFillSignature(returnToken, signature) {
  3443. const returnTokenRequired = returnToken === types.arrow;
  3444. signature.typeParameters = this.tsTryParseTypeParameters();
  3445. this.expect(types.parenL);
  3446. signature.parameters = this.tsParseBindingListForSignature();
  3447. if (returnTokenRequired) {
  3448. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  3449. } else if (this.match(returnToken)) {
  3450. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  3451. }
  3452. }
  3453. tsParseBindingListForSignature() {
  3454. return this.parseBindingList(types.parenR).map(pattern => {
  3455. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  3456. throw this.unexpected(pattern.start, `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${pattern.type}`);
  3457. }
  3458. return pattern;
  3459. });
  3460. }
  3461. tsParseTypeMemberSemicolon() {
  3462. if (!this.eat(types.comma)) {
  3463. this.semicolon();
  3464. }
  3465. }
  3466. tsParseSignatureMember(kind) {
  3467. const node = this.startNode();
  3468. if (kind === "TSConstructSignatureDeclaration") {
  3469. this.expect(types._new);
  3470. }
  3471. this.tsFillSignature(types.colon, node);
  3472. this.tsParseTypeMemberSemicolon();
  3473. return this.finishNode(node, kind);
  3474. }
  3475. tsIsUnambiguouslyIndexSignature() {
  3476. this.next();
  3477. return this.eat(types.name) && this.match(types.colon);
  3478. }
  3479. tsTryParseIndexSignature(node) {
  3480. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  3481. return undefined;
  3482. }
  3483. this.expect(types.bracketL);
  3484. const id = this.parseIdentifier();
  3485. id.typeAnnotation = this.tsParseTypeAnnotation();
  3486. this.finishNode(id, "Identifier");
  3487. this.expect(types.bracketR);
  3488. node.parameters = [id];
  3489. const type = this.tsTryParseTypeAnnotation();
  3490. if (type) node.typeAnnotation = type;
  3491. this.tsParseTypeMemberSemicolon();
  3492. return this.finishNode(node, "TSIndexSignature");
  3493. }
  3494. tsParsePropertyOrMethodSignature(node, readonly) {
  3495. this.parsePropertyName(node);
  3496. if (this.eat(types.question)) node.optional = true;
  3497. const nodeAny = node;
  3498. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  3499. const method = nodeAny;
  3500. this.tsFillSignature(types.colon, method);
  3501. this.tsParseTypeMemberSemicolon();
  3502. return this.finishNode(method, "TSMethodSignature");
  3503. } else {
  3504. const property = nodeAny;
  3505. if (readonly) property.readonly = true;
  3506. const type = this.tsTryParseTypeAnnotation();
  3507. if (type) property.typeAnnotation = type;
  3508. this.tsParseTypeMemberSemicolon();
  3509. return this.finishNode(property, "TSPropertySignature");
  3510. }
  3511. }
  3512. tsParseTypeMember() {
  3513. if (this.match(types.parenL) || this.isRelational("<")) {
  3514. return this.tsParseSignatureMember("TSCallSignatureDeclaration");
  3515. }
  3516. if (this.match(types._new) && this.tsLookAhead(this.tsIsStartOfConstructSignature.bind(this))) {
  3517. return this.tsParseSignatureMember("TSConstructSignatureDeclaration");
  3518. }
  3519. const node = this.startNode();
  3520. const readonly = !!this.tsParseModifier(["readonly"]);
  3521. const idx = this.tsTryParseIndexSignature(node);
  3522. if (idx) {
  3523. if (readonly) node.readonly = true;
  3524. return idx;
  3525. }
  3526. return this.tsParsePropertyOrMethodSignature(node, readonly);
  3527. }
  3528. tsIsStartOfConstructSignature() {
  3529. this.next();
  3530. return this.match(types.parenL) || this.isRelational("<");
  3531. }
  3532. tsParseTypeLiteral() {
  3533. const node = this.startNode();
  3534. node.members = this.tsParseObjectTypeMembers();
  3535. return this.finishNode(node, "TSTypeLiteral");
  3536. }
  3537. tsParseObjectTypeMembers() {
  3538. this.expect(types.braceL);
  3539. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  3540. this.expect(types.braceR);
  3541. return members;
  3542. }
  3543. tsIsStartOfMappedType() {
  3544. this.next();
  3545. if (this.eat(types.plusMin)) {
  3546. return this.isContextual("readonly");
  3547. }
  3548. if (this.isContextual("readonly")) {
  3549. this.next();
  3550. }
  3551. if (!this.match(types.bracketL)) {
  3552. return false;
  3553. }
  3554. this.next();
  3555. if (!this.tsIsIdentifier()) {
  3556. return false;
  3557. }
  3558. this.next();
  3559. return this.match(types._in);
  3560. }
  3561. tsParseMappedTypeParameter() {
  3562. const node = this.startNode();
  3563. node.name = this.parseIdentifierName(node.start);
  3564. node.constraint = this.tsExpectThenParseType(types._in);
  3565. return this.finishNode(node, "TSTypeParameter");
  3566. }
  3567. tsParseMappedType() {
  3568. const node = this.startNode();
  3569. this.expect(types.braceL);
  3570. if (this.match(types.plusMin)) {
  3571. node.readonly = this.state.value;
  3572. this.next();
  3573. this.expectContextual("readonly");
  3574. } else if (this.eatContextual("readonly")) {
  3575. node.readonly = true;
  3576. }
  3577. this.expect(types.bracketL);
  3578. node.typeParameter = this.tsParseMappedTypeParameter();
  3579. this.expect(types.bracketR);
  3580. if (this.match(types.plusMin)) {
  3581. node.optional = this.state.value;
  3582. this.next();
  3583. this.expect(types.question);
  3584. } else if (this.eat(types.question)) {
  3585. node.optional = true;
  3586. }
  3587. node.typeAnnotation = this.tsTryParseType();
  3588. this.semicolon();
  3589. this.expect(types.braceR);
  3590. return this.finishNode(node, "TSMappedType");
  3591. }
  3592. tsParseTupleType() {
  3593. const node = this.startNode();
  3594. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  3595. let seenOptionalElement = false;
  3596. node.elementTypes.forEach(elementNode => {
  3597. if (elementNode.type === "TSOptionalType") {
  3598. seenOptionalElement = true;
  3599. } else if (seenOptionalElement && elementNode.type !== "TSRestType") {
  3600. this.raise(elementNode.start, "A required element cannot follow an optional element.");
  3601. }
  3602. });
  3603. return this.finishNode(node, "TSTupleType");
  3604. }
  3605. tsParseTupleElementType() {
  3606. if (this.match(types.ellipsis)) {
  3607. const restNode = this.startNode();
  3608. this.next();
  3609. restNode.typeAnnotation = this.tsParseType();
  3610. this.checkCommaAfterRest();
  3611. return this.finishNode(restNode, "TSRestType");
  3612. }
  3613. const type = this.tsParseType();
  3614. if (this.eat(types.question)) {
  3615. const optionalTypeNode = this.startNodeAtNode(type);
  3616. optionalTypeNode.typeAnnotation = type;
  3617. return this.finishNode(optionalTypeNode, "TSOptionalType");
  3618. }
  3619. return type;
  3620. }
  3621. tsParseParenthesizedType() {
  3622. const node = this.startNode();
  3623. this.expect(types.parenL);
  3624. node.typeAnnotation = this.tsParseType();
  3625. this.expect(types.parenR);
  3626. return this.finishNode(node, "TSParenthesizedType");
  3627. }
  3628. tsParseFunctionOrConstructorType(type) {
  3629. const node = this.startNode();
  3630. if (type === "TSConstructorType") {
  3631. this.expect(types._new);
  3632. }
  3633. this.tsFillSignature(types.arrow, node);
  3634. return this.finishNode(node, type);
  3635. }
  3636. tsParseLiteralTypeNode() {
  3637. const node = this.startNode();
  3638. node.literal = (() => {
  3639. switch (this.state.type) {
  3640. case types.num:
  3641. case types.string:
  3642. case types._true:
  3643. case types._false:
  3644. return this.parseExprAtom();
  3645. default:
  3646. throw this.unexpected();
  3647. }
  3648. })();
  3649. return this.finishNode(node, "TSLiteralType");
  3650. }
  3651. tsParseTemplateLiteralType() {
  3652. const node = this.startNode();
  3653. const templateNode = this.parseTemplate(false);
  3654. if (templateNode.expressions.length > 0) {
  3655. throw this.raise(templateNode.expressions[0].start, "Template literal types cannot have any substitution");
  3656. }
  3657. node.literal = templateNode;
  3658. return this.finishNode(node, "TSLiteralType");
  3659. }
  3660. tsParseNonArrayType() {
  3661. switch (this.state.type) {
  3662. case types.name:
  3663. case types._void:
  3664. case types._null:
  3665. {
  3666. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  3667. if (type !== undefined && this.lookahead().type !== types.dot) {
  3668. const node = this.startNode();
  3669. this.next();
  3670. return this.finishNode(node, type);
  3671. }
  3672. return this.tsParseTypeReference();
  3673. }
  3674. case types.string:
  3675. case types.num:
  3676. case types._true:
  3677. case types._false:
  3678. return this.tsParseLiteralTypeNode();
  3679. case types.plusMin:
  3680. if (this.state.value === "-") {
  3681. const node = this.startNode();
  3682. if (this.lookahead().type !== types.num) {
  3683. throw this.unexpected();
  3684. }
  3685. node.literal = this.parseMaybeUnary();
  3686. return this.finishNode(node, "TSLiteralType");
  3687. }
  3688. break;
  3689. case types._this:
  3690. {
  3691. const thisKeyword = this.tsParseThisTypeNode();
  3692. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  3693. return this.tsParseThisTypePredicate(thisKeyword);
  3694. } else {
  3695. return thisKeyword;
  3696. }
  3697. }
  3698. case types._typeof:
  3699. return this.tsParseTypeQuery();
  3700. case types._import:
  3701. return this.tsParseImportType();
  3702. case types.braceL:
  3703. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  3704. case types.bracketL:
  3705. return this.tsParseTupleType();
  3706. case types.parenL:
  3707. return this.tsParseParenthesizedType();
  3708. case types.backQuote:
  3709. return this.tsParseTemplateLiteralType();
  3710. }
  3711. throw this.unexpected();
  3712. }
  3713. tsParseArrayTypeOrHigher() {
  3714. let type = this.tsParseNonArrayType();
  3715. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  3716. if (this.match(types.bracketR)) {
  3717. const node = this.startNodeAtNode(type);
  3718. node.elementType = type;
  3719. this.expect(types.bracketR);
  3720. type = this.finishNode(node, "TSArrayType");
  3721. } else {
  3722. const node = this.startNodeAtNode(type);
  3723. node.objectType = type;
  3724. node.indexType = this.tsParseType();
  3725. this.expect(types.bracketR);
  3726. type = this.finishNode(node, "TSIndexedAccessType");
  3727. }
  3728. }
  3729. return type;
  3730. }
  3731. tsParseTypeOperator(operator) {
  3732. const node = this.startNode();
  3733. this.expectContextual(operator);
  3734. node.operator = operator;
  3735. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  3736. if (operator === "readonly") {
  3737. this.tsCheckTypeAnnotationForReadOnly(node);
  3738. }
  3739. return this.finishNode(node, "TSTypeOperator");
  3740. }
  3741. tsCheckTypeAnnotationForReadOnly(node) {
  3742. switch (node.typeAnnotation.type) {
  3743. case "TSTupleType":
  3744. case "TSArrayType":
  3745. return;
  3746. default:
  3747. this.raise(node.start, "'readonly' type modifier is only permitted on array and tuple literal types.");
  3748. }
  3749. }
  3750. tsParseInferType() {
  3751. const node = this.startNode();
  3752. this.expectContextual("infer");
  3753. const typeParameter = this.startNode();
  3754. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  3755. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  3756. return this.finishNode(node, "TSInferType");
  3757. }
  3758. tsParseTypeOperatorOrHigher() {
  3759. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  3760. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  3761. }
  3762. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  3763. this.eat(operator);
  3764. let type = parseConstituentType();
  3765. if (this.match(operator)) {
  3766. const types = [type];
  3767. while (this.eat(operator)) {
  3768. types.push(parseConstituentType());
  3769. }
  3770. const node = this.startNodeAtNode(type);
  3771. node.types = types;
  3772. type = this.finishNode(node, kind);
  3773. }
  3774. return type;
  3775. }
  3776. tsParseIntersectionTypeOrHigher() {
  3777. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  3778. }
  3779. tsParseUnionTypeOrHigher() {
  3780. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  3781. }
  3782. tsIsStartOfFunctionType() {
  3783. if (this.isRelational("<")) {
  3784. return true;
  3785. }
  3786. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  3787. }
  3788. tsSkipParameterStart() {
  3789. if (this.match(types.name) || this.match(types._this)) {
  3790. this.next();
  3791. return true;
  3792. }
  3793. if (this.match(types.braceL)) {
  3794. let braceStackCounter = 1;
  3795. this.next();
  3796. while (braceStackCounter > 0) {
  3797. if (this.match(types.braceL)) {
  3798. ++braceStackCounter;
  3799. } else if (this.match(types.braceR)) {
  3800. --braceStackCounter;
  3801. }
  3802. this.next();
  3803. }
  3804. return true;
  3805. }
  3806. if (this.match(types.bracketL)) {
  3807. let braceStackCounter = 1;
  3808. this.next();
  3809. while (braceStackCounter > 0) {
  3810. if (this.match(types.bracketL)) {
  3811. ++braceStackCounter;
  3812. } else if (this.match(types.bracketR)) {
  3813. --braceStackCounter;
  3814. }
  3815. this.next();
  3816. }
  3817. return true;
  3818. }
  3819. return false;
  3820. }
  3821. tsIsUnambiguouslyStartOfFunctionType() {
  3822. this.next();
  3823. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  3824. return true;
  3825. }
  3826. if (this.tsSkipParameterStart()) {
  3827. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  3828. return true;
  3829. }
  3830. if (this.match(types.parenR)) {
  3831. this.next();
  3832. if (this.match(types.arrow)) {
  3833. return true;
  3834. }
  3835. }
  3836. }
  3837. return false;
  3838. }
  3839. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  3840. return this.tsInType(() => {
  3841. const t = this.startNode();
  3842. this.expect(returnToken);
  3843. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  3844. if (!typePredicateVariable) {
  3845. return this.tsParseTypeAnnotation(false, t);
  3846. }
  3847. const type = this.tsParseTypeAnnotation(false);
  3848. const node = this.startNodeAtNode(typePredicateVariable);
  3849. node.parameterName = typePredicateVariable;
  3850. node.typeAnnotation = type;
  3851. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  3852. return this.finishNode(t, "TSTypeAnnotation");
  3853. });
  3854. }
  3855. tsTryParseTypeOrTypePredicateAnnotation() {
  3856. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  3857. }
  3858. tsTryParseTypeAnnotation() {
  3859. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  3860. }
  3861. tsTryParseType() {
  3862. return this.tsEatThenParseType(types.colon);
  3863. }
  3864. tsParseTypePredicatePrefix() {
  3865. const id = this.parseIdentifier();
  3866. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  3867. this.next();
  3868. return id;
  3869. }
  3870. }
  3871. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  3872. this.tsInType(() => {
  3873. if (eatColon) this.expect(types.colon);
  3874. t.typeAnnotation = this.tsParseType();
  3875. });
  3876. return this.finishNode(t, "TSTypeAnnotation");
  3877. }
  3878. tsParseType() {
  3879. assert(this.state.inType);
  3880. const type = this.tsParseNonConditionalType();
  3881. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  3882. return type;
  3883. }
  3884. const node = this.startNodeAtNode(type);
  3885. node.checkType = type;
  3886. node.extendsType = this.tsParseNonConditionalType();
  3887. this.expect(types.question);
  3888. node.trueType = this.tsParseType();
  3889. this.expect(types.colon);
  3890. node.falseType = this.tsParseType();
  3891. return this.finishNode(node, "TSConditionalType");
  3892. }
  3893. tsParseNonConditionalType() {
  3894. if (this.tsIsStartOfFunctionType()) {
  3895. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  3896. }
  3897. if (this.match(types._new)) {
  3898. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  3899. }
  3900. return this.tsParseUnionTypeOrHigher();
  3901. }
  3902. tsParseTypeAssertion() {
  3903. const node = this.startNode();
  3904. const _const = this.tsTryNextParseConstantContext();
  3905. node.typeAnnotation = _const || this.tsNextThenParseType();
  3906. this.expectRelational(">");
  3907. node.expression = this.parseMaybeUnary();
  3908. return this.finishNode(node, "TSTypeAssertion");
  3909. }
  3910. tsParseHeritageClause(descriptor) {
  3911. const originalStart = this.state.start;
  3912. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  3913. if (!delimitedList.length) {
  3914. this.raise(originalStart, `'${descriptor}' list cannot be empty.`);
  3915. }
  3916. return delimitedList;
  3917. }
  3918. tsParseExpressionWithTypeArguments() {
  3919. const node = this.startNode();
  3920. node.expression = this.tsParseEntityName(false);
  3921. if (this.isRelational("<")) {
  3922. node.typeParameters = this.tsParseTypeArguments();
  3923. }
  3924. return this.finishNode(node, "TSExpressionWithTypeArguments");
  3925. }
  3926. tsParseInterfaceDeclaration(node) {
  3927. node.id = this.parseIdentifier();
  3928. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  3929. node.typeParameters = this.tsTryParseTypeParameters();
  3930. if (this.eat(types._extends)) {
  3931. node.extends = this.tsParseHeritageClause("extends");
  3932. }
  3933. const body = this.startNode();
  3934. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  3935. node.body = this.finishNode(body, "TSInterfaceBody");
  3936. return this.finishNode(node, "TSInterfaceDeclaration");
  3937. }
  3938. tsParseTypeAliasDeclaration(node) {
  3939. node.id = this.parseIdentifier();
  3940. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  3941. node.typeParameters = this.tsTryParseTypeParameters();
  3942. node.typeAnnotation = this.tsExpectThenParseType(types.eq);
  3943. this.semicolon();
  3944. return this.finishNode(node, "TSTypeAliasDeclaration");
  3945. }
  3946. tsInNoContext(cb) {
  3947. const oldContext = this.state.context;
  3948. this.state.context = [oldContext[0]];
  3949. try {
  3950. return cb();
  3951. } finally {
  3952. this.state.context = oldContext;
  3953. }
  3954. }
  3955. tsInType(cb) {
  3956. const oldInType = this.state.inType;
  3957. this.state.inType = true;
  3958. try {
  3959. return cb();
  3960. } finally {
  3961. this.state.inType = oldInType;
  3962. }
  3963. }
  3964. tsEatThenParseType(token) {
  3965. return !this.match(token) ? undefined : this.tsNextThenParseType();
  3966. }
  3967. tsExpectThenParseType(token) {
  3968. return this.tsDoThenParseType(() => this.expect(token));
  3969. }
  3970. tsNextThenParseType() {
  3971. return this.tsDoThenParseType(() => this.next());
  3972. }
  3973. tsDoThenParseType(cb) {
  3974. return this.tsInType(() => {
  3975. cb();
  3976. return this.tsParseType();
  3977. });
  3978. }
  3979. tsParseEnumMember() {
  3980. const node = this.startNode();
  3981. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  3982. if (this.eat(types.eq)) {
  3983. node.initializer = this.parseMaybeAssign();
  3984. }
  3985. return this.finishNode(node, "TSEnumMember");
  3986. }
  3987. tsParseEnumDeclaration(node, isConst) {
  3988. if (isConst) node.const = true;
  3989. node.id = this.parseIdentifier();
  3990. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  3991. this.expect(types.braceL);
  3992. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  3993. this.expect(types.braceR);
  3994. return this.finishNode(node, "TSEnumDeclaration");
  3995. }
  3996. tsParseModuleBlock() {
  3997. const node = this.startNode();
  3998. this.scope.enter(SCOPE_OTHER);
  3999. this.expect(types.braceL);
  4000. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  4001. this.scope.exit();
  4002. return this.finishNode(node, "TSModuleBlock");
  4003. }
  4004. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  4005. node.id = this.parseIdentifier();
  4006. if (!nested) {
  4007. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  4008. }
  4009. if (this.eat(types.dot)) {
  4010. const inner = this.startNode();
  4011. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  4012. node.body = inner;
  4013. } else {
  4014. node.body = this.tsParseModuleBlock();
  4015. }
  4016. return this.finishNode(node, "TSModuleDeclaration");
  4017. }
  4018. tsParseAmbientExternalModuleDeclaration(node) {
  4019. if (this.isContextual("global")) {
  4020. node.global = true;
  4021. node.id = this.parseIdentifier();
  4022. } else if (this.match(types.string)) {
  4023. node.id = this.parseExprAtom();
  4024. } else {
  4025. this.unexpected();
  4026. }
  4027. if (this.match(types.braceL)) {
  4028. node.body = this.tsParseModuleBlock();
  4029. } else {
  4030. this.semicolon();
  4031. }
  4032. return this.finishNode(node, "TSModuleDeclaration");
  4033. }
  4034. tsParseImportEqualsDeclaration(node, isExport) {
  4035. node.isExport = isExport || false;
  4036. node.id = this.parseIdentifier();
  4037. this.expect(types.eq);
  4038. node.moduleReference = this.tsParseModuleReference();
  4039. this.semicolon();
  4040. return this.finishNode(node, "TSImportEqualsDeclaration");
  4041. }
  4042. tsIsExternalModuleReference() {
  4043. return this.isContextual("require") && this.lookahead().type === types.parenL;
  4044. }
  4045. tsParseModuleReference() {
  4046. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  4047. }
  4048. tsParseExternalModuleReference() {
  4049. const node = this.startNode();
  4050. this.expectContextual("require");
  4051. this.expect(types.parenL);
  4052. if (!this.match(types.string)) {
  4053. throw this.unexpected();
  4054. }
  4055. node.expression = this.parseExprAtom();
  4056. this.expect(types.parenR);
  4057. return this.finishNode(node, "TSExternalModuleReference");
  4058. }
  4059. tsLookAhead(f) {
  4060. const state = this.state.clone();
  4061. const res = f();
  4062. this.state = state;
  4063. return res;
  4064. }
  4065. tsTryParseAndCatch(f) {
  4066. const state = this.state.clone();
  4067. try {
  4068. return f();
  4069. } catch (e) {
  4070. if (e instanceof SyntaxError) {
  4071. this.state = state;
  4072. return undefined;
  4073. }
  4074. throw e;
  4075. }
  4076. }
  4077. tsTryParse(f) {
  4078. const state = this.state.clone();
  4079. const result = f();
  4080. if (result !== undefined && result !== false) {
  4081. return result;
  4082. } else {
  4083. this.state = state;
  4084. return undefined;
  4085. }
  4086. }
  4087. nodeWithSamePosition(original, type) {
  4088. const node = this.startNodeAtNode(original);
  4089. node.type = type;
  4090. node.end = original.end;
  4091. node.loc.end = original.loc.end;
  4092. if (original.leadingComments) {
  4093. node.leadingComments = original.leadingComments;
  4094. }
  4095. if (original.trailingComments) {
  4096. node.trailingComments = original.trailingComments;
  4097. }
  4098. if (original.innerComments) node.innerComments = original.innerComments;
  4099. return node;
  4100. }
  4101. tsTryParseDeclare(nany) {
  4102. if (this.isLineTerminator()) {
  4103. return;
  4104. }
  4105. let starttype = this.state.type;
  4106. let kind;
  4107. if (this.isContextual("let")) {
  4108. starttype = types._var;
  4109. kind = "let";
  4110. }
  4111. switch (starttype) {
  4112. case types._function:
  4113. return this.parseFunctionStatement(nany, false, true);
  4114. case types._class:
  4115. return this.parseClass(nany, true, false);
  4116. case types._const:
  4117. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  4118. this.expect(types._const);
  4119. this.expectContextual("enum");
  4120. return this.tsParseEnumDeclaration(nany, true);
  4121. }
  4122. case types._var:
  4123. kind = kind || this.state.value;
  4124. return this.parseVarStatement(nany, kind);
  4125. case types.name:
  4126. {
  4127. const value = this.state.value;
  4128. if (value === "global") {
  4129. return this.tsParseAmbientExternalModuleDeclaration(nany);
  4130. } else {
  4131. return this.tsParseDeclaration(nany, value, true);
  4132. }
  4133. }
  4134. }
  4135. }
  4136. tsTryParseExportDeclaration() {
  4137. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  4138. }
  4139. tsParseExpressionStatement(node, expr) {
  4140. switch (expr.name) {
  4141. case "declare":
  4142. {
  4143. const declaration = this.tsTryParseDeclare(node);
  4144. if (declaration) {
  4145. declaration.declare = true;
  4146. return declaration;
  4147. }
  4148. break;
  4149. }
  4150. case "global":
  4151. if (this.match(types.braceL)) {
  4152. const mod = node;
  4153. mod.global = true;
  4154. mod.id = expr;
  4155. mod.body = this.tsParseModuleBlock();
  4156. return this.finishNode(mod, "TSModuleDeclaration");
  4157. }
  4158. break;
  4159. default:
  4160. return this.tsParseDeclaration(node, expr.name, false);
  4161. }
  4162. }
  4163. tsParseDeclaration(node, value, next) {
  4164. switch (value) {
  4165. case "abstract":
  4166. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  4167. const cls = node;
  4168. cls.abstract = true;
  4169. if (next) {
  4170. this.next();
  4171. if (!this.match(types._class)) {
  4172. this.unexpected(null, types._class);
  4173. }
  4174. }
  4175. return this.parseClass(cls, true, false);
  4176. }
  4177. break;
  4178. case "enum":
  4179. if (next || this.match(types.name)) {
  4180. if (next) this.next();
  4181. return this.tsParseEnumDeclaration(node, false);
  4182. }
  4183. break;
  4184. case "interface":
  4185. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4186. if (next) this.next();
  4187. return this.tsParseInterfaceDeclaration(node);
  4188. }
  4189. break;
  4190. case "module":
  4191. if (next) this.next();
  4192. if (this.match(types.string)) {
  4193. return this.tsParseAmbientExternalModuleDeclaration(node);
  4194. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4195. return this.tsParseModuleOrNamespaceDeclaration(node);
  4196. }
  4197. break;
  4198. case "namespace":
  4199. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4200. if (next) this.next();
  4201. return this.tsParseModuleOrNamespaceDeclaration(node);
  4202. }
  4203. break;
  4204. case "type":
  4205. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  4206. if (next) this.next();
  4207. return this.tsParseTypeAliasDeclaration(node);
  4208. }
  4209. break;
  4210. }
  4211. }
  4212. tsCheckLineTerminatorAndMatch(tokenType, next) {
  4213. return (next || this.match(tokenType)) && !this.isLineTerminator();
  4214. }
  4215. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  4216. const res = this.tsTryParseAndCatch(() => {
  4217. const node = this.startNodeAt(startPos, startLoc);
  4218. node.typeParameters = this.tsParseTypeParameters();
  4219. super.parseFunctionParams(node);
  4220. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  4221. this.expect(types.arrow);
  4222. return node;
  4223. });
  4224. if (!res) {
  4225. return undefined;
  4226. }
  4227. return this.parseArrowExpression(res, null, true);
  4228. }
  4229. tsParseTypeArguments() {
  4230. const node = this.startNode();
  4231. node.params = this.tsInType(() => this.tsInNoContext(() => {
  4232. this.expectRelational("<");
  4233. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  4234. }));
  4235. this.state.exprAllowed = false;
  4236. this.expectRelational(">");
  4237. return this.finishNode(node, "TSTypeParameterInstantiation");
  4238. }
  4239. tsIsDeclarationStart() {
  4240. if (this.match(types.name)) {
  4241. switch (this.state.value) {
  4242. case "abstract":
  4243. case "declare":
  4244. case "enum":
  4245. case "interface":
  4246. case "module":
  4247. case "namespace":
  4248. case "type":
  4249. return true;
  4250. }
  4251. }
  4252. return false;
  4253. }
  4254. isExportDefaultSpecifier() {
  4255. if (this.tsIsDeclarationStart()) return false;
  4256. return super.isExportDefaultSpecifier();
  4257. }
  4258. parseAssignableListItem(allowModifiers, decorators) {
  4259. const startPos = this.state.start;
  4260. const startLoc = this.state.startLoc;
  4261. let accessibility;
  4262. let readonly = false;
  4263. if (allowModifiers) {
  4264. accessibility = this.parseAccessModifier();
  4265. readonly = !!this.tsParseModifier(["readonly"]);
  4266. }
  4267. const left = this.parseMaybeDefault();
  4268. this.parseAssignableListItemTypes(left);
  4269. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  4270. if (accessibility || readonly) {
  4271. const pp = this.startNodeAt(startPos, startLoc);
  4272. if (decorators.length) {
  4273. pp.decorators = decorators;
  4274. }
  4275. if (accessibility) pp.accessibility = accessibility;
  4276. if (readonly) pp.readonly = readonly;
  4277. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  4278. throw this.raise(pp.start, "A parameter property may not be declared using a binding pattern.");
  4279. }
  4280. pp.parameter = elt;
  4281. return this.finishNode(pp, "TSParameterProperty");
  4282. }
  4283. if (decorators.length) {
  4284. left.decorators = decorators;
  4285. }
  4286. return elt;
  4287. }
  4288. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  4289. if (this.match(types.colon)) {
  4290. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  4291. }
  4292. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  4293. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  4294. this.finishNode(node, bodilessType);
  4295. return;
  4296. }
  4297. super.parseFunctionBodyAndFinish(node, type, isMethod);
  4298. }
  4299. checkFunctionStatementId(node) {
  4300. if (!node.body && node.id) {
  4301. this.checkLVal(node.id, BIND_TS_FN_TYPE, null, "function name");
  4302. } else {
  4303. super.checkFunctionStatementId(...arguments);
  4304. }
  4305. }
  4306. parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow) {
  4307. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  4308. this.state.exprAllowed = false;
  4309. this.next();
  4310. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  4311. nonNullExpression.expression = base;
  4312. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  4313. }
  4314. if (this.isRelational("<")) {
  4315. const result = this.tsTryParseAndCatch(() => {
  4316. if (!noCalls && this.atPossibleAsync(base)) {
  4317. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  4318. if (asyncArrowFn) {
  4319. return asyncArrowFn;
  4320. }
  4321. }
  4322. const node = this.startNodeAt(startPos, startLoc);
  4323. node.callee = base;
  4324. const typeArguments = this.tsParseTypeArguments();
  4325. if (typeArguments) {
  4326. if (!noCalls && this.eat(types.parenL)) {
  4327. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  4328. node.typeParameters = typeArguments;
  4329. return this.finishCallExpression(node);
  4330. } else if (this.match(types.backQuote)) {
  4331. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments);
  4332. }
  4333. }
  4334. this.unexpected();
  4335. });
  4336. if (result) return result;
  4337. }
  4338. return super.parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow);
  4339. }
  4340. parseNewArguments(node) {
  4341. if (this.isRelational("<")) {
  4342. const typeParameters = this.tsTryParseAndCatch(() => {
  4343. const args = this.tsParseTypeArguments();
  4344. if (!this.match(types.parenL)) this.unexpected();
  4345. return args;
  4346. });
  4347. if (typeParameters) {
  4348. node.typeParameters = typeParameters;
  4349. }
  4350. }
  4351. super.parseNewArguments(node);
  4352. }
  4353. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  4354. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  4355. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  4356. node.expression = left;
  4357. const _const = this.tsTryNextParseConstantContext();
  4358. if (_const) {
  4359. node.typeAnnotation = _const;
  4360. } else {
  4361. node.typeAnnotation = this.tsNextThenParseType();
  4362. }
  4363. this.finishNode(node, "TSAsExpression");
  4364. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  4365. }
  4366. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn);
  4367. }
  4368. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  4369. checkDuplicateExports() {}
  4370. parseImport(node) {
  4371. if (this.match(types.name) && this.lookahead().type === types.eq) {
  4372. return this.tsParseImportEqualsDeclaration(node);
  4373. }
  4374. return super.parseImport(node);
  4375. }
  4376. parseExport(node) {
  4377. if (this.match(types._import)) {
  4378. this.expect(types._import);
  4379. return this.tsParseImportEqualsDeclaration(node, true);
  4380. } else if (this.eat(types.eq)) {
  4381. const assign = node;
  4382. assign.expression = this.parseExpression();
  4383. this.semicolon();
  4384. return this.finishNode(assign, "TSExportAssignment");
  4385. } else if (this.eatContextual("as")) {
  4386. const decl = node;
  4387. this.expectContextual("namespace");
  4388. decl.id = this.parseIdentifier();
  4389. this.semicolon();
  4390. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  4391. } else {
  4392. return super.parseExport(node);
  4393. }
  4394. }
  4395. isAbstractClass() {
  4396. return this.isContextual("abstract") && this.lookahead().type === types._class;
  4397. }
  4398. parseExportDefaultExpression() {
  4399. if (this.isAbstractClass()) {
  4400. const cls = this.startNode();
  4401. this.next();
  4402. this.parseClass(cls, true, true);
  4403. cls.abstract = true;
  4404. return cls;
  4405. }
  4406. if (this.state.value === "interface") {
  4407. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  4408. if (result) return result;
  4409. }
  4410. return super.parseExportDefaultExpression();
  4411. }
  4412. parseStatementContent(context, topLevel) {
  4413. if (this.state.type === types._const) {
  4414. const ahead = this.lookahead();
  4415. if (ahead.type === types.name && ahead.value === "enum") {
  4416. const node = this.startNode();
  4417. this.expect(types._const);
  4418. this.expectContextual("enum");
  4419. return this.tsParseEnumDeclaration(node, true);
  4420. }
  4421. }
  4422. return super.parseStatementContent(context, topLevel);
  4423. }
  4424. parseAccessModifier() {
  4425. return this.tsParseModifier(["public", "protected", "private"]);
  4426. }
  4427. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  4428. const accessibility = this.parseAccessModifier();
  4429. if (accessibility) member.accessibility = accessibility;
  4430. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  4431. }
  4432. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  4433. const methodOrProp = member;
  4434. const prop = member;
  4435. const propOrIdx = member;
  4436. let abstract = false,
  4437. readonly = false;
  4438. const mod = this.tsParseModifier(["abstract", "readonly"]);
  4439. switch (mod) {
  4440. case "readonly":
  4441. readonly = true;
  4442. abstract = !!this.tsParseModifier(["abstract"]);
  4443. break;
  4444. case "abstract":
  4445. abstract = true;
  4446. readonly = !!this.tsParseModifier(["readonly"]);
  4447. break;
  4448. }
  4449. if (abstract) methodOrProp.abstract = true;
  4450. if (readonly) propOrIdx.readonly = true;
  4451. if (!abstract && !isStatic && !methodOrProp.accessibility) {
  4452. const idx = this.tsTryParseIndexSignature(member);
  4453. if (idx) {
  4454. classBody.body.push(idx);
  4455. return;
  4456. }
  4457. }
  4458. if (readonly) {
  4459. methodOrProp.static = isStatic;
  4460. this.parseClassPropertyName(prop);
  4461. this.parsePostMemberNameModifiers(methodOrProp);
  4462. this.pushClassProperty(classBody, prop);
  4463. return;
  4464. }
  4465. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  4466. }
  4467. parsePostMemberNameModifiers(methodOrProp) {
  4468. const optional = this.eat(types.question);
  4469. if (optional) methodOrProp.optional = true;
  4470. }
  4471. parseExpressionStatement(node, expr) {
  4472. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  4473. return decl || super.parseExpressionStatement(node, expr);
  4474. }
  4475. shouldParseExportDeclaration() {
  4476. if (this.tsIsDeclarationStart()) return true;
  4477. return super.shouldParseExportDeclaration();
  4478. }
  4479. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  4480. if (!refNeedsArrowPos || !this.match(types.question)) {
  4481. return super.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  4482. }
  4483. const state = this.state.clone();
  4484. try {
  4485. return super.parseConditional(expr, noIn, startPos, startLoc);
  4486. } catch (err) {
  4487. if (!(err instanceof SyntaxError)) {
  4488. throw err;
  4489. }
  4490. this.state = state;
  4491. refNeedsArrowPos.start = err.pos || this.state.start;
  4492. return expr;
  4493. }
  4494. }
  4495. parseParenItem(node, startPos, startLoc) {
  4496. node = super.parseParenItem(node, startPos, startLoc);
  4497. if (this.eat(types.question)) {
  4498. node.optional = true;
  4499. }
  4500. if (this.match(types.colon)) {
  4501. const typeCastNode = this.startNodeAt(startPos, startLoc);
  4502. typeCastNode.expression = node;
  4503. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  4504. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  4505. }
  4506. return this.finishNode(node, node.type);
  4507. }
  4508. parseExportDeclaration(node) {
  4509. const startPos = this.state.start;
  4510. const startLoc = this.state.startLoc;
  4511. const isDeclare = this.eatContextual("declare");
  4512. let declaration;
  4513. if (this.match(types.name)) {
  4514. declaration = this.tsTryParseExportDeclaration();
  4515. }
  4516. if (!declaration) {
  4517. declaration = super.parseExportDeclaration(node);
  4518. }
  4519. if (declaration && isDeclare) {
  4520. this.resetStartLocation(declaration, startPos, startLoc);
  4521. declaration.declare = true;
  4522. }
  4523. return declaration;
  4524. }
  4525. parseClassId(node, isStatement, optionalId) {
  4526. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  4527. return;
  4528. }
  4529. super.parseClassId(...arguments);
  4530. const typeParameters = this.tsTryParseTypeParameters();
  4531. if (typeParameters) node.typeParameters = typeParameters;
  4532. }
  4533. parseClassProperty(node) {
  4534. if (!node.optional && this.eat(types.bang)) {
  4535. node.definite = true;
  4536. }
  4537. const type = this.tsTryParseTypeAnnotation();
  4538. if (type) node.typeAnnotation = type;
  4539. return super.parseClassProperty(node);
  4540. }
  4541. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  4542. const typeParameters = this.tsTryParseTypeParameters();
  4543. if (typeParameters) method.typeParameters = typeParameters;
  4544. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  4545. }
  4546. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  4547. const typeParameters = this.tsTryParseTypeParameters();
  4548. if (typeParameters) method.typeParameters = typeParameters;
  4549. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  4550. }
  4551. parseClassSuper(node) {
  4552. super.parseClassSuper(node);
  4553. if (node.superClass && this.isRelational("<")) {
  4554. node.superTypeParameters = this.tsParseTypeArguments();
  4555. }
  4556. if (this.eatContextual("implements")) {
  4557. node.implements = this.tsParseHeritageClause("implements");
  4558. }
  4559. }
  4560. parseObjPropValue(prop, ...args) {
  4561. const typeParameters = this.tsTryParseTypeParameters();
  4562. if (typeParameters) prop.typeParameters = typeParameters;
  4563. super.parseObjPropValue(prop, ...args);
  4564. }
  4565. parseFunctionParams(node, allowModifiers) {
  4566. const typeParameters = this.tsTryParseTypeParameters();
  4567. if (typeParameters) node.typeParameters = typeParameters;
  4568. super.parseFunctionParams(node, allowModifiers);
  4569. }
  4570. parseVarId(decl, kind) {
  4571. super.parseVarId(decl, kind);
  4572. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  4573. decl.definite = true;
  4574. }
  4575. const type = this.tsTryParseTypeAnnotation();
  4576. if (type) {
  4577. decl.id.typeAnnotation = type;
  4578. this.finishNode(decl.id, decl.id.type);
  4579. }
  4580. }
  4581. parseAsyncArrowFromCallExpression(node, call) {
  4582. if (this.match(types.colon)) {
  4583. node.returnType = this.tsParseTypeAnnotation();
  4584. }
  4585. return super.parseAsyncArrowFromCallExpression(node, call);
  4586. }
  4587. parseMaybeAssign(...args) {
  4588. let jsxError;
  4589. if (this.match(types.jsxTagStart)) {
  4590. const context = this.curContext();
  4591. assert(context === types$1.j_oTag);
  4592. assert(this.state.context[this.state.context.length - 2] === types$1.j_expr);
  4593. const state = this.state.clone();
  4594. try {
  4595. return super.parseMaybeAssign(...args);
  4596. } catch (err) {
  4597. if (!(err instanceof SyntaxError)) {
  4598. throw err;
  4599. }
  4600. this.state = state;
  4601. assert(this.curContext() === types$1.j_oTag);
  4602. this.state.context.pop();
  4603. assert(this.curContext() === types$1.j_expr);
  4604. this.state.context.pop();
  4605. jsxError = err;
  4606. }
  4607. }
  4608. if (jsxError === undefined && !this.isRelational("<")) {
  4609. return super.parseMaybeAssign(...args);
  4610. }
  4611. let arrowExpression;
  4612. let typeParameters;
  4613. const state = this.state.clone();
  4614. try {
  4615. typeParameters = this.tsParseTypeParameters();
  4616. arrowExpression = super.parseMaybeAssign(...args);
  4617. if (arrowExpression.type !== "ArrowFunctionExpression" || arrowExpression.extra && arrowExpression.extra.parenthesized) {
  4618. this.unexpected();
  4619. }
  4620. } catch (err) {
  4621. if (!(err instanceof SyntaxError)) {
  4622. throw err;
  4623. }
  4624. if (jsxError) {
  4625. throw jsxError;
  4626. }
  4627. assert(!this.hasPlugin("jsx"));
  4628. this.state = state;
  4629. return super.parseMaybeAssign(...args);
  4630. }
  4631. if (typeParameters && typeParameters.params.length !== 0) {
  4632. this.resetStartLocationFromNode(arrowExpression, typeParameters);
  4633. }
  4634. arrowExpression.typeParameters = typeParameters;
  4635. return arrowExpression;
  4636. }
  4637. parseMaybeUnary(refShorthandDefaultPos) {
  4638. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  4639. return this.tsParseTypeAssertion();
  4640. } else {
  4641. return super.parseMaybeUnary(refShorthandDefaultPos);
  4642. }
  4643. }
  4644. parseArrow(node) {
  4645. if (this.match(types.colon)) {
  4646. const state = this.state.clone();
  4647. try {
  4648. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  4649. if (this.canInsertSemicolon()) this.unexpected();
  4650. if (!this.match(types.arrow)) this.unexpected();
  4651. node.returnType = returnType;
  4652. } catch (err) {
  4653. if (err instanceof SyntaxError) {
  4654. this.state = state;
  4655. } else {
  4656. throw err;
  4657. }
  4658. }
  4659. }
  4660. return super.parseArrow(node);
  4661. }
  4662. parseAssignableListItemTypes(param) {
  4663. if (this.eat(types.question)) {
  4664. if (param.type !== "Identifier") {
  4665. throw this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature.");
  4666. }
  4667. param.optional = true;
  4668. }
  4669. const type = this.tsTryParseTypeAnnotation();
  4670. if (type) param.typeAnnotation = type;
  4671. return this.finishNode(param, param.type);
  4672. }
  4673. toAssignable(node, isBinding, contextDescription) {
  4674. switch (node.type) {
  4675. case "TSTypeCastExpression":
  4676. return super.toAssignable(this.typeCastToParameter(node), isBinding, contextDescription);
  4677. case "TSParameterProperty":
  4678. return super.toAssignable(node, isBinding, contextDescription);
  4679. case "TSAsExpression":
  4680. case "TSNonNullExpression":
  4681. case "TSTypeAssertion":
  4682. node.expression = this.toAssignable(node.expression, isBinding, contextDescription);
  4683. return node;
  4684. default:
  4685. return super.toAssignable(node, isBinding, contextDescription);
  4686. }
  4687. }
  4688. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  4689. switch (expr.type) {
  4690. case "TSTypeCastExpression":
  4691. return;
  4692. case "TSParameterProperty":
  4693. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  4694. return;
  4695. case "TSAsExpression":
  4696. case "TSNonNullExpression":
  4697. case "TSTypeAssertion":
  4698. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  4699. return;
  4700. default:
  4701. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  4702. return;
  4703. }
  4704. }
  4705. parseBindingAtom() {
  4706. switch (this.state.type) {
  4707. case types._this:
  4708. return this.parseIdentifier(true);
  4709. default:
  4710. return super.parseBindingAtom();
  4711. }
  4712. }
  4713. parseMaybeDecoratorArguments(expr) {
  4714. if (this.isRelational("<")) {
  4715. const typeArguments = this.tsParseTypeArguments();
  4716. if (this.match(types.parenL)) {
  4717. const call = super.parseMaybeDecoratorArguments(expr);
  4718. call.typeParameters = typeArguments;
  4719. return call;
  4720. }
  4721. this.unexpected(this.state.start, types.parenL);
  4722. }
  4723. return super.parseMaybeDecoratorArguments(expr);
  4724. }
  4725. isClassMethod() {
  4726. return this.isRelational("<") || super.isClassMethod();
  4727. }
  4728. isClassProperty() {
  4729. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  4730. }
  4731. parseMaybeDefault(...args) {
  4732. const node = super.parseMaybeDefault(...args);
  4733. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  4734. this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`");
  4735. }
  4736. return node;
  4737. }
  4738. getTokenFromCode(code) {
  4739. if (this.state.inType && (code === 62 || code === 60)) {
  4740. return this.finishOp(types.relational, 1);
  4741. } else {
  4742. return super.getTokenFromCode(code);
  4743. }
  4744. }
  4745. toAssignableList(exprList, isBinding, contextDescription) {
  4746. for (let i = 0; i < exprList.length; i++) {
  4747. const expr = exprList[i];
  4748. if (!expr) continue;
  4749. switch (expr.type) {
  4750. case "TSTypeCastExpression":
  4751. exprList[i] = this.typeCastToParameter(expr);
  4752. break;
  4753. case "TSAsExpression":
  4754. case "TSTypeAssertion":
  4755. this.raise(expr.start, "Unexpected type cast in parameter position.");
  4756. break;
  4757. }
  4758. }
  4759. return super.toAssignableList(exprList, isBinding, contextDescription);
  4760. }
  4761. typeCastToParameter(node) {
  4762. node.expression.typeAnnotation = node.typeAnnotation;
  4763. return this.finishNodeAt(node.expression, node.expression.type, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  4764. }
  4765. toReferencedList(exprList, isInParens) {
  4766. for (let i = 0; i < exprList.length; i++) {
  4767. const expr = exprList[i];
  4768. if (expr && expr._exprListItem && expr.type === "TsTypeCastExpression") {
  4769. this.raise(expr.start, "Did not expect a type annotation here.");
  4770. }
  4771. }
  4772. return exprList;
  4773. }
  4774. shouldParseArrow() {
  4775. return this.match(types.colon) || super.shouldParseArrow();
  4776. }
  4777. shouldParseAsyncArrow() {
  4778. return this.match(types.colon) || super.shouldParseAsyncArrow();
  4779. }
  4780. canHaveLeadingDecorator() {
  4781. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  4782. }
  4783. jsxParseOpeningElementAfterName(node) {
  4784. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  4785. if (typeArguments) node.typeParameters = typeArguments;
  4786. return super.jsxParseOpeningElementAfterName(node);
  4787. }
  4788. getGetterSetterExpectedParamCount(method) {
  4789. const baseCount = super.getGetterSetterExpectedParamCount(method);
  4790. const firstParam = method.params[0];
  4791. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  4792. return hasContextParam ? baseCount + 1 : baseCount;
  4793. }
  4794. });
  4795. types.placeholder = new TokenType("%%", {
  4796. startsExpr: true
  4797. });
  4798. var placeholders = (superClass => class extends superClass {
  4799. parsePlaceholder(expectedNode) {
  4800. if (this.match(types.placeholder)) {
  4801. const node = this.startNode();
  4802. this.next();
  4803. this.assertNoSpace("Unexpected space in placeholder.");
  4804. node.name = super.parseIdentifier(true);
  4805. this.assertNoSpace("Unexpected space in placeholder.");
  4806. this.expect(types.placeholder);
  4807. return this.finishPlaceholder(node, expectedNode);
  4808. }
  4809. }
  4810. finishPlaceholder(node, expectedNode) {
  4811. node.expectedNode = expectedNode;
  4812. return this.finishNode(node, "Placeholder");
  4813. }
  4814. getTokenFromCode(code) {
  4815. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  4816. return this.finishOp(types.placeholder, 2);
  4817. }
  4818. return super.getTokenFromCode(...arguments);
  4819. }
  4820. parseExprAtom() {
  4821. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  4822. }
  4823. parseIdentifier() {
  4824. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  4825. }
  4826. checkReservedWord(word) {
  4827. if (word !== undefined) super.checkReservedWord(...arguments);
  4828. }
  4829. parseBindingAtom() {
  4830. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  4831. }
  4832. checkLVal(expr) {
  4833. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  4834. }
  4835. toAssignable(node) {
  4836. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  4837. node.expectedNode = "Pattern";
  4838. return node;
  4839. }
  4840. return super.toAssignable(...arguments);
  4841. }
  4842. verifyBreakContinue(node) {
  4843. if (node.label && node.label.type === "Placeholder") return;
  4844. super.verifyBreakContinue(...arguments);
  4845. }
  4846. parseExpressionStatement(node, expr) {
  4847. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  4848. return super.parseExpressionStatement(...arguments);
  4849. }
  4850. if (this.match(types.colon)) {
  4851. const stmt = node;
  4852. stmt.label = this.finishPlaceholder(expr, "Identifier");
  4853. this.next();
  4854. stmt.body = this.parseStatement("label");
  4855. return this.finishNode(stmt, "LabeledStatement");
  4856. }
  4857. this.semicolon();
  4858. node.name = expr.name;
  4859. return this.finishPlaceholder(node, "Statement");
  4860. }
  4861. parseBlock() {
  4862. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  4863. }
  4864. parseFunctionId() {
  4865. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  4866. }
  4867. parseClass(node, isStatement, optionalId) {
  4868. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  4869. this.next();
  4870. this.takeDecorators(node);
  4871. const placeholder = this.parsePlaceholder("Identifier");
  4872. if (placeholder) {
  4873. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  4874. node.id = placeholder;
  4875. } else if (optionalId || !isStatement) {
  4876. node.id = null;
  4877. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  4878. return this.finishNode(node, type);
  4879. } else {
  4880. this.unexpected(null, "A class name is required");
  4881. }
  4882. } else {
  4883. this.parseClassId(node, isStatement, optionalId);
  4884. }
  4885. this.parseClassSuper(node);
  4886. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass);
  4887. return this.finishNode(node, type);
  4888. }
  4889. parseExport(node) {
  4890. const placeholder = this.parsePlaceholder("Identifier");
  4891. if (!placeholder) return super.parseExport(...arguments);
  4892. if (!this.isContextual("from") && !this.match(types.comma)) {
  4893. node.specifiers = [];
  4894. node.source = null;
  4895. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  4896. return this.finishNode(node, "ExportNamedDeclaration");
  4897. }
  4898. this.expectPlugin("exportDefaultFrom");
  4899. const specifier = this.startNode();
  4900. specifier.exported = placeholder;
  4901. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  4902. return super.parseExport(node);
  4903. }
  4904. maybeParseExportDefaultSpecifier(node) {
  4905. if (node.specifiers && node.specifiers.length > 0) {
  4906. return true;
  4907. }
  4908. return super.maybeParseExportDefaultSpecifier(...arguments);
  4909. }
  4910. checkExport(node) {
  4911. const {
  4912. specifiers
  4913. } = node;
  4914. if (specifiers && specifiers.length) {
  4915. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  4916. }
  4917. super.checkExport(node);
  4918. node.specifiers = specifiers;
  4919. }
  4920. parseImport(node) {
  4921. const placeholder = this.parsePlaceholder("Identifier");
  4922. if (!placeholder) return super.parseImport(...arguments);
  4923. node.specifiers = [];
  4924. if (!this.isContextual("from") && !this.match(types.comma)) {
  4925. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  4926. this.semicolon();
  4927. return this.finishNode(node, "ImportDeclaration");
  4928. }
  4929. const specifier = this.startNodeAtNode(placeholder);
  4930. specifier.local = placeholder;
  4931. this.finishNode(specifier, "ImportDefaultSpecifier");
  4932. node.specifiers.push(specifier);
  4933. if (this.eat(types.comma)) {
  4934. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  4935. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  4936. }
  4937. this.expectContextual("from");
  4938. node.source = this.parseImportSource();
  4939. this.semicolon();
  4940. return this.finishNode(node, "ImportDeclaration");
  4941. }
  4942. parseImportSource() {
  4943. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  4944. }
  4945. });
  4946. function hasPlugin(plugins, name) {
  4947. return plugins.some(plugin => {
  4948. if (Array.isArray(plugin)) {
  4949. return plugin[0] === name;
  4950. } else {
  4951. return plugin === name;
  4952. }
  4953. });
  4954. }
  4955. function getPluginOption(plugins, name, option) {
  4956. const plugin = plugins.find(plugin => {
  4957. if (Array.isArray(plugin)) {
  4958. return plugin[0] === name;
  4959. } else {
  4960. return plugin === name;
  4961. }
  4962. });
  4963. if (plugin && Array.isArray(plugin)) {
  4964. return plugin[1][option];
  4965. }
  4966. return null;
  4967. }
  4968. const PIPELINE_PROPOSALS = ["minimal", "smart"];
  4969. function validatePlugins(plugins) {
  4970. if (hasPlugin(plugins, "decorators")) {
  4971. if (hasPlugin(plugins, "decorators-legacy")) {
  4972. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  4973. }
  4974. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  4975. if (decoratorsBeforeExport == null) {
  4976. 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'.");
  4977. } else if (typeof decoratorsBeforeExport !== "boolean") {
  4978. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  4979. }
  4980. }
  4981. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  4982. throw new Error("Cannot combine flow and typescript plugins.");
  4983. }
  4984. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  4985. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  4986. }
  4987. }
  4988. const mixinPlugins = {
  4989. estree,
  4990. jsx,
  4991. flow,
  4992. typescript,
  4993. placeholders
  4994. };
  4995. const mixinPluginNames = Object.keys(mixinPlugins);
  4996. const defaultOptions = {
  4997. sourceType: "script",
  4998. sourceFilename: undefined,
  4999. startLine: 1,
  5000. allowAwaitOutsideFunction: false,
  5001. allowReturnOutsideFunction: false,
  5002. allowImportExportEverywhere: false,
  5003. allowSuperOutsideMethod: false,
  5004. plugins: [],
  5005. strictMode: null,
  5006. ranges: false,
  5007. tokens: false,
  5008. createParenthesizedExpressions: false
  5009. };
  5010. function getOptions(opts) {
  5011. const options = {};
  5012. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  5013. const key = _Object$keys[_i];
  5014. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  5015. }
  5016. return options;
  5017. }
  5018. class Position {
  5019. constructor(line, col) {
  5020. this.line = line;
  5021. this.column = col;
  5022. }
  5023. }
  5024. class SourceLocation {
  5025. constructor(start, end) {
  5026. this.start = start;
  5027. this.end = end;
  5028. }
  5029. }
  5030. function getLineInfo(input, offset) {
  5031. let line = 1;
  5032. let lineStart = 0;
  5033. let match;
  5034. lineBreakG.lastIndex = 0;
  5035. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  5036. line++;
  5037. lineStart = lineBreakG.lastIndex;
  5038. }
  5039. return new Position(line, offset - lineStart);
  5040. }
  5041. class BaseParser {
  5042. constructor() {
  5043. this.sawUnambiguousESM = false;
  5044. }
  5045. hasPlugin(name) {
  5046. return this.plugins.has(name);
  5047. }
  5048. getPluginOption(plugin, name) {
  5049. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  5050. }
  5051. }
  5052. function last(stack) {
  5053. return stack[stack.length - 1];
  5054. }
  5055. class CommentsParser extends BaseParser {
  5056. addComment(comment) {
  5057. if (this.filename) comment.loc.filename = this.filename;
  5058. this.state.trailingComments.push(comment);
  5059. this.state.leadingComments.push(comment);
  5060. }
  5061. processComment(node) {
  5062. if (node.type === "Program" && node.body.length > 0) return;
  5063. const stack = this.state.commentStack;
  5064. let firstChild, lastChild, trailingComments, i, j;
  5065. if (this.state.trailingComments.length > 0) {
  5066. if (this.state.trailingComments[0].start >= node.end) {
  5067. trailingComments = this.state.trailingComments;
  5068. this.state.trailingComments = [];
  5069. } else {
  5070. this.state.trailingComments.length = 0;
  5071. }
  5072. } else if (stack.length > 0) {
  5073. const lastInStack = last(stack);
  5074. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  5075. trailingComments = lastInStack.trailingComments;
  5076. delete lastInStack.trailingComments;
  5077. }
  5078. }
  5079. if (stack.length > 0 && last(stack).start >= node.start) {
  5080. firstChild = stack.pop();
  5081. }
  5082. while (stack.length > 0 && last(stack).start >= node.start) {
  5083. lastChild = stack.pop();
  5084. }
  5085. if (!lastChild && firstChild) lastChild = firstChild;
  5086. if (firstChild && this.state.leadingComments.length > 0) {
  5087. const lastComment = last(this.state.leadingComments);
  5088. if (firstChild.type === "ObjectProperty") {
  5089. if (lastComment.start >= node.start) {
  5090. if (this.state.commentPreviousNode) {
  5091. for (j = 0; j < this.state.leadingComments.length; j++) {
  5092. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  5093. this.state.leadingComments.splice(j, 1);
  5094. j--;
  5095. }
  5096. }
  5097. if (this.state.leadingComments.length > 0) {
  5098. firstChild.trailingComments = this.state.leadingComments;
  5099. this.state.leadingComments = [];
  5100. }
  5101. }
  5102. }
  5103. } else if (node.type === "CallExpression" && node.arguments && node.arguments.length) {
  5104. const lastArg = last(node.arguments);
  5105. if (lastArg && lastComment.start >= lastArg.start && lastComment.end <= node.end) {
  5106. if (this.state.commentPreviousNode) {
  5107. for (j = 0; j < this.state.leadingComments.length; j++) {
  5108. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  5109. this.state.leadingComments.splice(j, 1);
  5110. j--;
  5111. }
  5112. }
  5113. if (this.state.leadingComments.length > 0) {
  5114. lastArg.trailingComments = this.state.leadingComments;
  5115. this.state.leadingComments = [];
  5116. }
  5117. }
  5118. }
  5119. }
  5120. }
  5121. if (lastChild) {
  5122. if (lastChild.leadingComments) {
  5123. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  5124. node.leadingComments = lastChild.leadingComments;
  5125. delete lastChild.leadingComments;
  5126. } else {
  5127. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  5128. if (lastChild.leadingComments[i].end <= node.start) {
  5129. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  5130. break;
  5131. }
  5132. }
  5133. }
  5134. }
  5135. } else if (this.state.leadingComments.length > 0) {
  5136. if (last(this.state.leadingComments).end <= node.start) {
  5137. if (this.state.commentPreviousNode) {
  5138. for (j = 0; j < this.state.leadingComments.length; j++) {
  5139. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  5140. this.state.leadingComments.splice(j, 1);
  5141. j--;
  5142. }
  5143. }
  5144. }
  5145. if (this.state.leadingComments.length > 0) {
  5146. node.leadingComments = this.state.leadingComments;
  5147. this.state.leadingComments = [];
  5148. }
  5149. } else {
  5150. for (i = 0; i < this.state.leadingComments.length; i++) {
  5151. if (this.state.leadingComments[i].end > node.start) {
  5152. break;
  5153. }
  5154. }
  5155. const leadingComments = this.state.leadingComments.slice(0, i);
  5156. if (leadingComments.length) {
  5157. node.leadingComments = leadingComments;
  5158. }
  5159. trailingComments = this.state.leadingComments.slice(i);
  5160. if (trailingComments.length === 0) {
  5161. trailingComments = null;
  5162. }
  5163. }
  5164. }
  5165. this.state.commentPreviousNode = node;
  5166. if (trailingComments) {
  5167. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  5168. node.innerComments = trailingComments;
  5169. } else {
  5170. node.trailingComments = trailingComments;
  5171. }
  5172. }
  5173. stack.push(node);
  5174. }
  5175. }
  5176. class LocationParser extends CommentsParser {
  5177. raise(pos, message, {
  5178. missingPluginNames,
  5179. code
  5180. } = {}) {
  5181. const loc = getLineInfo(this.input, pos);
  5182. message += ` (${loc.line}:${loc.column})`;
  5183. const err = new SyntaxError(message);
  5184. err.pos = pos;
  5185. err.loc = loc;
  5186. if (missingPluginNames) {
  5187. err.missingPlugin = missingPluginNames;
  5188. }
  5189. if (code !== undefined) {
  5190. err.code = code;
  5191. }
  5192. throw err;
  5193. }
  5194. }
  5195. class State {
  5196. constructor() {
  5197. this.potentialArrowAt = -1;
  5198. this.noArrowAt = [];
  5199. this.noArrowParamsConversionAt = [];
  5200. this.commaAfterSpreadAt = -1;
  5201. this.inParameters = false;
  5202. this.maybeInArrowParameters = false;
  5203. this.inPipeline = false;
  5204. this.inType = false;
  5205. this.noAnonFunctionType = false;
  5206. this.inPropertyName = false;
  5207. this.inClassProperty = false;
  5208. this.hasFlowComment = false;
  5209. this.isIterator = false;
  5210. this.topicContext = {
  5211. maxNumOfResolvableTopics: 0,
  5212. maxTopicIndex: null
  5213. };
  5214. this.classLevel = 0;
  5215. this.labels = [];
  5216. this.decoratorStack = [[]];
  5217. this.yieldPos = 0;
  5218. this.awaitPos = 0;
  5219. this.tokens = [];
  5220. this.comments = [];
  5221. this.trailingComments = [];
  5222. this.leadingComments = [];
  5223. this.commentStack = [];
  5224. this.commentPreviousNode = null;
  5225. this.pos = 0;
  5226. this.lineStart = 0;
  5227. this.type = types.eof;
  5228. this.value = null;
  5229. this.start = 0;
  5230. this.end = 0;
  5231. this.lastTokEndLoc = null;
  5232. this.lastTokStartLoc = null;
  5233. this.lastTokStart = 0;
  5234. this.lastTokEnd = 0;
  5235. this.context = [types$1.braceStatement];
  5236. this.exprAllowed = true;
  5237. this.containsEsc = false;
  5238. this.containsOctal = false;
  5239. this.octalPosition = null;
  5240. this.exportedIdentifiers = [];
  5241. this.invalidTemplateEscapePosition = null;
  5242. }
  5243. init(options) {
  5244. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  5245. this.curLine = options.startLine;
  5246. this.startLoc = this.endLoc = this.curPosition();
  5247. }
  5248. curPosition() {
  5249. return new Position(this.curLine, this.pos - this.lineStart);
  5250. }
  5251. clone(skipArrays) {
  5252. const state = new State();
  5253. const keys = Object.keys(this);
  5254. for (let i = 0, length = keys.length; i < length; i++) {
  5255. const key = keys[i];
  5256. let val = this[key];
  5257. if ((!skipArrays || key === "context") && Array.isArray(val)) {
  5258. val = val.slice();
  5259. }
  5260. state[key] = val;
  5261. }
  5262. return state;
  5263. }
  5264. }
  5265. var _isDigit = function isDigit(code) {
  5266. return code >= 48 && code <= 57;
  5267. };
  5268. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  5269. const forbiddenNumericSeparatorSiblings = {
  5270. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  5271. hex: [46, 88, 95, 120]
  5272. };
  5273. const allowedNumericSeparatorSiblings = {};
  5274. allowedNumericSeparatorSiblings.bin = [48, 49];
  5275. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  5276. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  5277. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  5278. class Token {
  5279. constructor(state) {
  5280. this.type = state.type;
  5281. this.value = state.value;
  5282. this.start = state.start;
  5283. this.end = state.end;
  5284. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  5285. }
  5286. }
  5287. class Tokenizer extends LocationParser {
  5288. constructor(options, input) {
  5289. super();
  5290. this.state = new State();
  5291. this.state.init(options);
  5292. this.input = input;
  5293. this.length = input.length;
  5294. this.isLookahead = false;
  5295. }
  5296. next() {
  5297. if (this.options.tokens && !this.isLookahead) {
  5298. this.state.tokens.push(new Token(this.state));
  5299. }
  5300. this.state.lastTokEnd = this.state.end;
  5301. this.state.lastTokStart = this.state.start;
  5302. this.state.lastTokEndLoc = this.state.endLoc;
  5303. this.state.lastTokStartLoc = this.state.startLoc;
  5304. this.nextToken();
  5305. }
  5306. eat(type) {
  5307. if (this.match(type)) {
  5308. this.next();
  5309. return true;
  5310. } else {
  5311. return false;
  5312. }
  5313. }
  5314. match(type) {
  5315. return this.state.type === type;
  5316. }
  5317. lookahead() {
  5318. const old = this.state;
  5319. this.state = old.clone(true);
  5320. this.isLookahead = true;
  5321. this.next();
  5322. this.isLookahead = false;
  5323. const curr = this.state;
  5324. this.state = old;
  5325. return curr;
  5326. }
  5327. setStrict(strict) {
  5328. this.state.strict = strict;
  5329. if (!this.match(types.num) && !this.match(types.string)) return;
  5330. this.state.pos = this.state.start;
  5331. while (this.state.pos < this.state.lineStart) {
  5332. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  5333. --this.state.curLine;
  5334. }
  5335. this.nextToken();
  5336. }
  5337. curContext() {
  5338. return this.state.context[this.state.context.length - 1];
  5339. }
  5340. nextToken() {
  5341. const curContext = this.curContext();
  5342. if (!curContext || !curContext.preserveSpace) this.skipSpace();
  5343. this.state.containsOctal = false;
  5344. this.state.octalPosition = null;
  5345. this.state.start = this.state.pos;
  5346. this.state.startLoc = this.state.curPosition();
  5347. if (this.state.pos >= this.length) {
  5348. this.finishToken(types.eof);
  5349. return;
  5350. }
  5351. if (curContext.override) {
  5352. curContext.override(this);
  5353. } else {
  5354. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  5355. }
  5356. }
  5357. pushComment(block, text, start, end, startLoc, endLoc) {
  5358. const comment = {
  5359. type: block ? "CommentBlock" : "CommentLine",
  5360. value: text,
  5361. start: start,
  5362. end: end,
  5363. loc: new SourceLocation(startLoc, endLoc)
  5364. };
  5365. if (!this.isLookahead) {
  5366. if (this.options.tokens) this.state.tokens.push(comment);
  5367. this.state.comments.push(comment);
  5368. this.addComment(comment);
  5369. }
  5370. }
  5371. skipBlockComment() {
  5372. const startLoc = this.state.curPosition();
  5373. const start = this.state.pos;
  5374. const end = this.input.indexOf("*/", this.state.pos += 2);
  5375. if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment");
  5376. this.state.pos = end + 2;
  5377. lineBreakG.lastIndex = start;
  5378. let match;
  5379. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  5380. ++this.state.curLine;
  5381. this.state.lineStart = match.index + match[0].length;
  5382. }
  5383. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  5384. }
  5385. skipLineComment(startSkip) {
  5386. const start = this.state.pos;
  5387. const startLoc = this.state.curPosition();
  5388. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  5389. if (this.state.pos < this.length) {
  5390. while (ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233 && ++this.state.pos < this.length) {
  5391. ch = this.input.charCodeAt(this.state.pos);
  5392. }
  5393. }
  5394. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  5395. }
  5396. skipSpace() {
  5397. loop: while (this.state.pos < this.length) {
  5398. const ch = this.input.charCodeAt(this.state.pos);
  5399. switch (ch) {
  5400. case 32:
  5401. case 160:
  5402. case 9:
  5403. ++this.state.pos;
  5404. break;
  5405. case 13:
  5406. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  5407. ++this.state.pos;
  5408. }
  5409. case 10:
  5410. case 8232:
  5411. case 8233:
  5412. ++this.state.pos;
  5413. ++this.state.curLine;
  5414. this.state.lineStart = this.state.pos;
  5415. break;
  5416. case 47:
  5417. switch (this.input.charCodeAt(this.state.pos + 1)) {
  5418. case 42:
  5419. this.skipBlockComment();
  5420. break;
  5421. case 47:
  5422. this.skipLineComment(2);
  5423. break;
  5424. default:
  5425. break loop;
  5426. }
  5427. break;
  5428. default:
  5429. if (isWhitespace(ch)) {
  5430. ++this.state.pos;
  5431. } else {
  5432. break loop;
  5433. }
  5434. }
  5435. }
  5436. }
  5437. finishToken(type, val) {
  5438. this.state.end = this.state.pos;
  5439. this.state.endLoc = this.state.curPosition();
  5440. const prevType = this.state.type;
  5441. this.state.type = type;
  5442. this.state.value = val;
  5443. this.updateContext(prevType);
  5444. }
  5445. readToken_numberSign() {
  5446. if (this.state.pos === 0 && this.readToken_interpreter()) {
  5447. return;
  5448. }
  5449. const nextPos = this.state.pos + 1;
  5450. const next = this.input.charCodeAt(nextPos);
  5451. if (next >= 48 && next <= 57) {
  5452. this.raise(this.state.pos, "Unexpected digit after hash token");
  5453. }
  5454. if ((this.hasPlugin("classPrivateProperties") || this.hasPlugin("classPrivateMethods")) && this.state.classLevel > 0) {
  5455. ++this.state.pos;
  5456. this.finishToken(types.hash);
  5457. return;
  5458. } else if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  5459. this.finishOp(types.hash, 1);
  5460. } else {
  5461. this.raise(this.state.pos, "Unexpected character '#'");
  5462. }
  5463. }
  5464. readToken_dot() {
  5465. const next = this.input.charCodeAt(this.state.pos + 1);
  5466. if (next >= 48 && next <= 57) {
  5467. this.readNumber(true);
  5468. return;
  5469. }
  5470. const next2 = this.input.charCodeAt(this.state.pos + 2);
  5471. if (next === 46 && next2 === 46) {
  5472. this.state.pos += 3;
  5473. this.finishToken(types.ellipsis);
  5474. } else {
  5475. ++this.state.pos;
  5476. this.finishToken(types.dot);
  5477. }
  5478. }
  5479. readToken_slash() {
  5480. if (this.state.exprAllowed && !this.state.inType) {
  5481. ++this.state.pos;
  5482. this.readRegexp();
  5483. return;
  5484. }
  5485. const next = this.input.charCodeAt(this.state.pos + 1);
  5486. if (next === 61) {
  5487. this.finishOp(types.assign, 2);
  5488. } else {
  5489. this.finishOp(types.slash, 1);
  5490. }
  5491. }
  5492. readToken_interpreter() {
  5493. if (this.state.pos !== 0 || this.length < 2) return false;
  5494. const start = this.state.pos;
  5495. this.state.pos += 1;
  5496. let ch = this.input.charCodeAt(this.state.pos);
  5497. if (ch !== 33) return false;
  5498. while (ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233 && ++this.state.pos < this.length) {
  5499. ch = this.input.charCodeAt(this.state.pos);
  5500. }
  5501. const value = this.input.slice(start + 2, this.state.pos);
  5502. this.finishToken(types.interpreterDirective, value);
  5503. return true;
  5504. }
  5505. readToken_mult_modulo(code) {
  5506. let type = code === 42 ? types.star : types.modulo;
  5507. let width = 1;
  5508. let next = this.input.charCodeAt(this.state.pos + 1);
  5509. const exprAllowed = this.state.exprAllowed;
  5510. if (code === 42 && next === 42) {
  5511. width++;
  5512. next = this.input.charCodeAt(this.state.pos + 2);
  5513. type = types.exponent;
  5514. }
  5515. if (next === 61 && !exprAllowed) {
  5516. width++;
  5517. type = types.assign;
  5518. }
  5519. this.finishOp(type, width);
  5520. }
  5521. readToken_pipe_amp(code) {
  5522. const next = this.input.charCodeAt(this.state.pos + 1);
  5523. if (next === code) {
  5524. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  5525. this.finishOp(types.assign, 3);
  5526. } else {
  5527. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  5528. }
  5529. return;
  5530. }
  5531. if (code === 124) {
  5532. if (next === 62) {
  5533. this.finishOp(types.pipeline, 2);
  5534. return;
  5535. }
  5536. }
  5537. if (next === 61) {
  5538. this.finishOp(types.assign, 2);
  5539. return;
  5540. }
  5541. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  5542. }
  5543. readToken_caret() {
  5544. const next = this.input.charCodeAt(this.state.pos + 1);
  5545. if (next === 61) {
  5546. this.finishOp(types.assign, 2);
  5547. } else {
  5548. this.finishOp(types.bitwiseXOR, 1);
  5549. }
  5550. }
  5551. readToken_plus_min(code) {
  5552. const next = this.input.charCodeAt(this.state.pos + 1);
  5553. if (next === code) {
  5554. 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)))) {
  5555. this.skipLineComment(3);
  5556. this.skipSpace();
  5557. this.nextToken();
  5558. return;
  5559. }
  5560. this.finishOp(types.incDec, 2);
  5561. return;
  5562. }
  5563. if (next === 61) {
  5564. this.finishOp(types.assign, 2);
  5565. } else {
  5566. this.finishOp(types.plusMin, 1);
  5567. }
  5568. }
  5569. readToken_lt_gt(code) {
  5570. const next = this.input.charCodeAt(this.state.pos + 1);
  5571. let size = 1;
  5572. if (next === code) {
  5573. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  5574. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  5575. this.finishOp(types.assign, size + 1);
  5576. return;
  5577. }
  5578. this.finishOp(types.bitShift, size);
  5579. return;
  5580. }
  5581. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  5582. this.skipLineComment(4);
  5583. this.skipSpace();
  5584. this.nextToken();
  5585. return;
  5586. }
  5587. if (next === 61) {
  5588. size = 2;
  5589. }
  5590. this.finishOp(types.relational, size);
  5591. }
  5592. readToken_eq_excl(code) {
  5593. const next = this.input.charCodeAt(this.state.pos + 1);
  5594. if (next === 61) {
  5595. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  5596. return;
  5597. }
  5598. if (code === 61 && next === 62) {
  5599. this.state.pos += 2;
  5600. this.finishToken(types.arrow);
  5601. return;
  5602. }
  5603. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  5604. }
  5605. readToken_question() {
  5606. const next = this.input.charCodeAt(this.state.pos + 1);
  5607. const next2 = this.input.charCodeAt(this.state.pos + 2);
  5608. if (next === 63 && !this.state.inType) {
  5609. if (next2 === 61) {
  5610. this.finishOp(types.assign, 3);
  5611. } else {
  5612. this.finishOp(types.nullishCoalescing, 2);
  5613. }
  5614. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  5615. this.state.pos += 2;
  5616. this.finishToken(types.questionDot);
  5617. } else {
  5618. ++this.state.pos;
  5619. this.finishToken(types.question);
  5620. }
  5621. }
  5622. getTokenFromCode(code) {
  5623. switch (code) {
  5624. case 46:
  5625. this.readToken_dot();
  5626. return;
  5627. case 40:
  5628. ++this.state.pos;
  5629. this.finishToken(types.parenL);
  5630. return;
  5631. case 41:
  5632. ++this.state.pos;
  5633. this.finishToken(types.parenR);
  5634. return;
  5635. case 59:
  5636. ++this.state.pos;
  5637. this.finishToken(types.semi);
  5638. return;
  5639. case 44:
  5640. ++this.state.pos;
  5641. this.finishToken(types.comma);
  5642. return;
  5643. case 91:
  5644. ++this.state.pos;
  5645. this.finishToken(types.bracketL);
  5646. return;
  5647. case 93:
  5648. ++this.state.pos;
  5649. this.finishToken(types.bracketR);
  5650. return;
  5651. case 123:
  5652. ++this.state.pos;
  5653. this.finishToken(types.braceL);
  5654. return;
  5655. case 125:
  5656. ++this.state.pos;
  5657. this.finishToken(types.braceR);
  5658. return;
  5659. case 58:
  5660. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  5661. this.finishOp(types.doubleColon, 2);
  5662. } else {
  5663. ++this.state.pos;
  5664. this.finishToken(types.colon);
  5665. }
  5666. return;
  5667. case 63:
  5668. this.readToken_question();
  5669. return;
  5670. case 96:
  5671. ++this.state.pos;
  5672. this.finishToken(types.backQuote);
  5673. return;
  5674. case 48:
  5675. {
  5676. const next = this.input.charCodeAt(this.state.pos + 1);
  5677. if (next === 120 || next === 88) {
  5678. this.readRadixNumber(16);
  5679. return;
  5680. }
  5681. if (next === 111 || next === 79) {
  5682. this.readRadixNumber(8);
  5683. return;
  5684. }
  5685. if (next === 98 || next === 66) {
  5686. this.readRadixNumber(2);
  5687. return;
  5688. }
  5689. }
  5690. case 49:
  5691. case 50:
  5692. case 51:
  5693. case 52:
  5694. case 53:
  5695. case 54:
  5696. case 55:
  5697. case 56:
  5698. case 57:
  5699. this.readNumber(false);
  5700. return;
  5701. case 34:
  5702. case 39:
  5703. this.readString(code);
  5704. return;
  5705. case 47:
  5706. this.readToken_slash();
  5707. return;
  5708. case 37:
  5709. case 42:
  5710. this.readToken_mult_modulo(code);
  5711. return;
  5712. case 124:
  5713. case 38:
  5714. this.readToken_pipe_amp(code);
  5715. return;
  5716. case 94:
  5717. this.readToken_caret();
  5718. return;
  5719. case 43:
  5720. case 45:
  5721. this.readToken_plus_min(code);
  5722. return;
  5723. case 60:
  5724. case 62:
  5725. this.readToken_lt_gt(code);
  5726. return;
  5727. case 61:
  5728. case 33:
  5729. this.readToken_eq_excl(code);
  5730. return;
  5731. case 126:
  5732. this.finishOp(types.tilde, 1);
  5733. return;
  5734. case 64:
  5735. ++this.state.pos;
  5736. this.finishToken(types.at);
  5737. return;
  5738. case 35:
  5739. this.readToken_numberSign();
  5740. return;
  5741. case 92:
  5742. this.readWord();
  5743. return;
  5744. default:
  5745. if (isIdentifierStart(code)) {
  5746. this.readWord();
  5747. return;
  5748. }
  5749. }
  5750. this.raise(this.state.pos, `Unexpected character '${String.fromCodePoint(code)}'`);
  5751. }
  5752. finishOp(type, size) {
  5753. const str = this.input.slice(this.state.pos, this.state.pos + size);
  5754. this.state.pos += size;
  5755. this.finishToken(type, str);
  5756. }
  5757. readRegexp() {
  5758. const start = this.state.pos;
  5759. let escaped, inClass;
  5760. for (;;) {
  5761. if (this.state.pos >= this.length) {
  5762. this.raise(start, "Unterminated regular expression");
  5763. }
  5764. const ch = this.input.charAt(this.state.pos);
  5765. if (lineBreak.test(ch)) {
  5766. this.raise(start, "Unterminated regular expression");
  5767. }
  5768. if (escaped) {
  5769. escaped = false;
  5770. } else {
  5771. if (ch === "[") {
  5772. inClass = true;
  5773. } else if (ch === "]" && inClass) {
  5774. inClass = false;
  5775. } else if (ch === "/" && !inClass) {
  5776. break;
  5777. }
  5778. escaped = ch === "\\";
  5779. }
  5780. ++this.state.pos;
  5781. }
  5782. const content = this.input.slice(start, this.state.pos);
  5783. ++this.state.pos;
  5784. let mods = "";
  5785. while (this.state.pos < this.length) {
  5786. const char = this.input[this.state.pos];
  5787. const charCode = this.input.codePointAt(this.state.pos);
  5788. if (VALID_REGEX_FLAGS.has(char)) {
  5789. if (mods.indexOf(char) > -1) {
  5790. this.raise(this.state.pos + 1, "Duplicate regular expression flag");
  5791. }
  5792. ++this.state.pos;
  5793. mods += char;
  5794. } else if (isIdentifierChar(charCode) || charCode === 92) {
  5795. this.raise(this.state.pos + 1, "Invalid regular expression flag");
  5796. } else {
  5797. break;
  5798. }
  5799. }
  5800. this.finishToken(types.regexp, {
  5801. pattern: content,
  5802. flags: mods
  5803. });
  5804. }
  5805. readInt(radix, len) {
  5806. const start = this.state.pos;
  5807. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  5808. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  5809. let total = 0;
  5810. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  5811. const code = this.input.charCodeAt(this.state.pos);
  5812. let val;
  5813. if (this.hasPlugin("numericSeparator")) {
  5814. const prev = this.input.charCodeAt(this.state.pos - 1);
  5815. const next = this.input.charCodeAt(this.state.pos + 1);
  5816. if (code === 95) {
  5817. if (allowedSiblings.indexOf(next) === -1) {
  5818. this.raise(this.state.pos, "Invalid or unexpected token");
  5819. }
  5820. if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  5821. this.raise(this.state.pos, "Invalid or unexpected token");
  5822. }
  5823. ++this.state.pos;
  5824. continue;
  5825. }
  5826. }
  5827. if (code >= 97) {
  5828. val = code - 97 + 10;
  5829. } else if (code >= 65) {
  5830. val = code - 65 + 10;
  5831. } else if (_isDigit(code)) {
  5832. val = code - 48;
  5833. } else {
  5834. val = Infinity;
  5835. }
  5836. if (val >= radix) break;
  5837. ++this.state.pos;
  5838. total = total * radix + val;
  5839. }
  5840. if (this.state.pos === start || len != null && this.state.pos - start !== len) {
  5841. return null;
  5842. }
  5843. return total;
  5844. }
  5845. readRadixNumber(radix) {
  5846. const start = this.state.pos;
  5847. let isBigInt = false;
  5848. this.state.pos += 2;
  5849. const val = this.readInt(radix);
  5850. if (val == null) {
  5851. this.raise(this.state.start + 2, "Expected number in radix " + radix);
  5852. }
  5853. if (this.hasPlugin("bigInt")) {
  5854. if (this.input.charCodeAt(this.state.pos) === 110) {
  5855. ++this.state.pos;
  5856. isBigInt = true;
  5857. }
  5858. }
  5859. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  5860. this.raise(this.state.pos, "Identifier directly after number");
  5861. }
  5862. if (isBigInt) {
  5863. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  5864. this.finishToken(types.bigint, str);
  5865. return;
  5866. }
  5867. this.finishToken(types.num, val);
  5868. }
  5869. readNumber(startsWithDot) {
  5870. const start = this.state.pos;
  5871. let isFloat = false;
  5872. let isBigInt = false;
  5873. if (!startsWithDot && this.readInt(10) === null) {
  5874. this.raise(start, "Invalid number");
  5875. }
  5876. let octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  5877. if (octal) {
  5878. if (this.state.strict) {
  5879. this.raise(start, "Legacy octal literals are not allowed in strict mode");
  5880. }
  5881. if (/[89]/.test(this.input.slice(start, this.state.pos))) {
  5882. octal = false;
  5883. }
  5884. }
  5885. let next = this.input.charCodeAt(this.state.pos);
  5886. if (next === 46 && !octal) {
  5887. ++this.state.pos;
  5888. this.readInt(10);
  5889. isFloat = true;
  5890. next = this.input.charCodeAt(this.state.pos);
  5891. }
  5892. if ((next === 69 || next === 101) && !octal) {
  5893. next = this.input.charCodeAt(++this.state.pos);
  5894. if (next === 43 || next === 45) {
  5895. ++this.state.pos;
  5896. }
  5897. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  5898. isFloat = true;
  5899. next = this.input.charCodeAt(this.state.pos);
  5900. }
  5901. if (this.hasPlugin("bigInt")) {
  5902. if (next === 110) {
  5903. if (isFloat || octal) this.raise(start, "Invalid BigIntLiteral");
  5904. ++this.state.pos;
  5905. isBigInt = true;
  5906. }
  5907. }
  5908. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  5909. this.raise(this.state.pos, "Identifier directly after number");
  5910. }
  5911. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  5912. if (isBigInt) {
  5913. this.finishToken(types.bigint, str);
  5914. return;
  5915. }
  5916. const val = octal ? parseInt(str, 8) : parseFloat(str);
  5917. this.finishToken(types.num, val);
  5918. }
  5919. readCodePoint(throwOnInvalid) {
  5920. const ch = this.input.charCodeAt(this.state.pos);
  5921. let code;
  5922. if (ch === 123) {
  5923. const codePos = ++this.state.pos;
  5924. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, throwOnInvalid);
  5925. ++this.state.pos;
  5926. if (code === null) {
  5927. --this.state.invalidTemplateEscapePosition;
  5928. } else if (code > 0x10ffff) {
  5929. if (throwOnInvalid) {
  5930. this.raise(codePos, "Code point out of bounds");
  5931. } else {
  5932. this.state.invalidTemplateEscapePosition = codePos - 2;
  5933. return null;
  5934. }
  5935. }
  5936. } else {
  5937. code = this.readHexChar(4, throwOnInvalid);
  5938. }
  5939. return code;
  5940. }
  5941. readString(quote) {
  5942. let out = "",
  5943. chunkStart = ++this.state.pos;
  5944. for (;;) {
  5945. if (this.state.pos >= this.length) {
  5946. this.raise(this.state.start, "Unterminated string constant");
  5947. }
  5948. const ch = this.input.charCodeAt(this.state.pos);
  5949. if (ch === quote) break;
  5950. if (ch === 92) {
  5951. out += this.input.slice(chunkStart, this.state.pos);
  5952. out += this.readEscapedChar(false);
  5953. chunkStart = this.state.pos;
  5954. } else if (ch === 8232 || ch === 8233) {
  5955. ++this.state.pos;
  5956. ++this.state.curLine;
  5957. } else if (isNewLine(ch)) {
  5958. this.raise(this.state.start, "Unterminated string constant");
  5959. } else {
  5960. ++this.state.pos;
  5961. }
  5962. }
  5963. out += this.input.slice(chunkStart, this.state.pos++);
  5964. this.finishToken(types.string, out);
  5965. }
  5966. readTmplToken() {
  5967. let out = "",
  5968. chunkStart = this.state.pos,
  5969. containsInvalid = false;
  5970. for (;;) {
  5971. if (this.state.pos >= this.length) {
  5972. this.raise(this.state.start, "Unterminated template");
  5973. }
  5974. const ch = this.input.charCodeAt(this.state.pos);
  5975. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  5976. if (this.state.pos === this.state.start && this.match(types.template)) {
  5977. if (ch === 36) {
  5978. this.state.pos += 2;
  5979. this.finishToken(types.dollarBraceL);
  5980. return;
  5981. } else {
  5982. ++this.state.pos;
  5983. this.finishToken(types.backQuote);
  5984. return;
  5985. }
  5986. }
  5987. out += this.input.slice(chunkStart, this.state.pos);
  5988. this.finishToken(types.template, containsInvalid ? null : out);
  5989. return;
  5990. }
  5991. if (ch === 92) {
  5992. out += this.input.slice(chunkStart, this.state.pos);
  5993. const escaped = this.readEscapedChar(true);
  5994. if (escaped === null) {
  5995. containsInvalid = true;
  5996. } else {
  5997. out += escaped;
  5998. }
  5999. chunkStart = this.state.pos;
  6000. } else if (isNewLine(ch)) {
  6001. out += this.input.slice(chunkStart, this.state.pos);
  6002. ++this.state.pos;
  6003. switch (ch) {
  6004. case 13:
  6005. if (this.input.charCodeAt(this.state.pos) === 10) {
  6006. ++this.state.pos;
  6007. }
  6008. case 10:
  6009. out += "\n";
  6010. break;
  6011. default:
  6012. out += String.fromCharCode(ch);
  6013. break;
  6014. }
  6015. ++this.state.curLine;
  6016. this.state.lineStart = this.state.pos;
  6017. chunkStart = this.state.pos;
  6018. } else {
  6019. ++this.state.pos;
  6020. }
  6021. }
  6022. }
  6023. readEscapedChar(inTemplate) {
  6024. const throwOnInvalid = !inTemplate;
  6025. const ch = this.input.charCodeAt(++this.state.pos);
  6026. ++this.state.pos;
  6027. switch (ch) {
  6028. case 110:
  6029. return "\n";
  6030. case 114:
  6031. return "\r";
  6032. case 120:
  6033. {
  6034. const code = this.readHexChar(2, throwOnInvalid);
  6035. return code === null ? null : String.fromCharCode(code);
  6036. }
  6037. case 117:
  6038. {
  6039. const code = this.readCodePoint(throwOnInvalid);
  6040. return code === null ? null : String.fromCodePoint(code);
  6041. }
  6042. case 116:
  6043. return "\t";
  6044. case 98:
  6045. return "\b";
  6046. case 118:
  6047. return "\u000b";
  6048. case 102:
  6049. return "\f";
  6050. case 13:
  6051. if (this.input.charCodeAt(this.state.pos) === 10) {
  6052. ++this.state.pos;
  6053. }
  6054. case 10:
  6055. this.state.lineStart = this.state.pos;
  6056. ++this.state.curLine;
  6057. case 8232:
  6058. case 8233:
  6059. return "";
  6060. default:
  6061. if (ch >= 48 && ch <= 55) {
  6062. const codePos = this.state.pos - 1;
  6063. let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
  6064. let octal = parseInt(octalStr, 8);
  6065. if (octal > 255) {
  6066. octalStr = octalStr.slice(0, -1);
  6067. octal = parseInt(octalStr, 8);
  6068. }
  6069. this.state.pos += octalStr.length - 1;
  6070. const next = this.input.charCodeAt(this.state.pos);
  6071. if (octalStr !== "0" || next === 56 || next === 57) {
  6072. if (inTemplate) {
  6073. this.state.invalidTemplateEscapePosition = codePos;
  6074. return null;
  6075. } else if (this.state.strict) {
  6076. this.raise(codePos, "Octal literal in strict mode");
  6077. } else if (!this.state.containsOctal) {
  6078. this.state.containsOctal = true;
  6079. this.state.octalPosition = codePos;
  6080. }
  6081. }
  6082. return String.fromCharCode(octal);
  6083. }
  6084. return String.fromCharCode(ch);
  6085. }
  6086. }
  6087. readHexChar(len, throwOnInvalid) {
  6088. const codePos = this.state.pos;
  6089. const n = this.readInt(16, len);
  6090. if (n === null) {
  6091. if (throwOnInvalid) {
  6092. this.raise(codePos, "Bad character escape sequence");
  6093. } else {
  6094. this.state.pos = codePos - 1;
  6095. this.state.invalidTemplateEscapePosition = codePos - 1;
  6096. }
  6097. }
  6098. return n;
  6099. }
  6100. readWord1() {
  6101. let word = "";
  6102. this.state.containsEsc = false;
  6103. const start = this.state.pos;
  6104. let chunkStart = this.state.pos;
  6105. while (this.state.pos < this.length) {
  6106. const ch = this.input.codePointAt(this.state.pos);
  6107. if (isIdentifierChar(ch)) {
  6108. this.state.pos += ch <= 0xffff ? 1 : 2;
  6109. } else if (this.state.isIterator && ch === 64) {
  6110. ++this.state.pos;
  6111. } else if (ch === 92) {
  6112. this.state.containsEsc = true;
  6113. word += this.input.slice(chunkStart, this.state.pos);
  6114. const escStart = this.state.pos;
  6115. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  6116. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  6117. this.raise(this.state.pos, "Expecting Unicode escape sequence \\uXXXX");
  6118. }
  6119. ++this.state.pos;
  6120. const esc = this.readCodePoint(true);
  6121. if (!identifierCheck(esc, true)) {
  6122. this.raise(escStart, "Invalid Unicode escape");
  6123. }
  6124. word += String.fromCodePoint(esc);
  6125. chunkStart = this.state.pos;
  6126. } else {
  6127. break;
  6128. }
  6129. }
  6130. return word + this.input.slice(chunkStart, this.state.pos);
  6131. }
  6132. isIterator(word) {
  6133. return word === "@@iterator" || word === "@@asyncIterator";
  6134. }
  6135. readWord() {
  6136. const word = this.readWord1();
  6137. const type = keywords.get(word) || types.name;
  6138. if (type.keyword && this.state.containsEsc) {
  6139. this.raise(this.state.pos, `Escape sequence in keyword ${word}`);
  6140. }
  6141. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  6142. this.raise(this.state.pos, `Invalid identifier ${word}`);
  6143. }
  6144. this.finishToken(type, word);
  6145. }
  6146. braceIsBlock(prevType) {
  6147. const parent = this.curContext();
  6148. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  6149. return true;
  6150. }
  6151. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  6152. return !parent.isExpr;
  6153. }
  6154. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  6155. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  6156. }
  6157. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  6158. return true;
  6159. }
  6160. if (prevType === types.braceL) {
  6161. return parent === types$1.braceStatement;
  6162. }
  6163. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  6164. return false;
  6165. }
  6166. if (prevType === types.relational) {
  6167. return true;
  6168. }
  6169. return !this.state.exprAllowed;
  6170. }
  6171. updateContext(prevType) {
  6172. const type = this.state.type;
  6173. let update;
  6174. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  6175. this.state.exprAllowed = false;
  6176. } else if (update = type.updateContext) {
  6177. update.call(this, prevType);
  6178. } else {
  6179. this.state.exprAllowed = type.beforeExpr;
  6180. }
  6181. }
  6182. }
  6183. const literal = /^('|")((?:\\?.)*?)\1/;
  6184. class UtilParser extends Tokenizer {
  6185. addExtra(node, key, val) {
  6186. if (!node) return;
  6187. const extra = node.extra = node.extra || {};
  6188. extra[key] = val;
  6189. }
  6190. isRelational(op) {
  6191. return this.match(types.relational) && this.state.value === op;
  6192. }
  6193. isLookaheadRelational(op) {
  6194. const l = this.lookahead();
  6195. return l.type === types.relational && l.value === op;
  6196. }
  6197. expectRelational(op) {
  6198. if (this.isRelational(op)) {
  6199. this.next();
  6200. } else {
  6201. this.unexpected(null, types.relational);
  6202. }
  6203. }
  6204. eatRelational(op) {
  6205. if (this.isRelational(op)) {
  6206. this.next();
  6207. return true;
  6208. }
  6209. return false;
  6210. }
  6211. isContextual(name) {
  6212. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  6213. }
  6214. isLookaheadContextual(name) {
  6215. const l = this.lookahead();
  6216. return l.type === types.name && l.value === name;
  6217. }
  6218. eatContextual(name) {
  6219. return this.isContextual(name) && this.eat(types.name);
  6220. }
  6221. expectContextual(name, message) {
  6222. if (!this.eatContextual(name)) this.unexpected(null, message);
  6223. }
  6224. canInsertSemicolon() {
  6225. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  6226. }
  6227. hasPrecedingLineBreak() {
  6228. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  6229. }
  6230. isLineTerminator() {
  6231. return this.eat(types.semi) || this.canInsertSemicolon();
  6232. }
  6233. semicolon() {
  6234. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  6235. }
  6236. expect(type, pos) {
  6237. this.eat(type) || this.unexpected(pos, type);
  6238. }
  6239. assertNoSpace(message = "Unexpected space.") {
  6240. if (this.state.start > this.state.lastTokEnd) {
  6241. this.raise(this.state.lastTokEnd, message);
  6242. }
  6243. }
  6244. unexpected(pos, messageOrType = "Unexpected token") {
  6245. if (typeof messageOrType !== "string") {
  6246. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  6247. }
  6248. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  6249. }
  6250. expectPlugin(name, pos) {
  6251. if (!this.hasPlugin(name)) {
  6252. throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling the parser plugin: '${name}'`, {
  6253. missingPluginNames: [name]
  6254. });
  6255. }
  6256. return true;
  6257. }
  6258. expectOnePlugin(names, pos) {
  6259. if (!names.some(n => this.hasPlugin(n))) {
  6260. throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`, {
  6261. missingPluginNames: names
  6262. });
  6263. }
  6264. }
  6265. checkYieldAwaitInDefaultParams() {
  6266. if (this.state.yieldPos && (!this.state.awaitPos || this.state.yieldPos < this.state.awaitPos)) {
  6267. this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function");
  6268. }
  6269. if (this.state.awaitPos) {
  6270. this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function");
  6271. }
  6272. }
  6273. strictDirective(start) {
  6274. for (;;) {
  6275. skipWhiteSpace.lastIndex = start;
  6276. start += skipWhiteSpace.exec(this.input)[0].length;
  6277. const match = literal.exec(this.input.slice(start));
  6278. if (!match) break;
  6279. if (match[2] === "use strict") return true;
  6280. start += match[0].length;
  6281. skipWhiteSpace.lastIndex = start;
  6282. start += skipWhiteSpace.exec(this.input)[0].length;
  6283. if (this.input[start] === ";") {
  6284. start++;
  6285. }
  6286. }
  6287. return false;
  6288. }
  6289. }
  6290. class Node {
  6291. constructor(parser, pos, loc) {
  6292. this.type = "";
  6293. this.start = pos;
  6294. this.end = 0;
  6295. this.loc = new SourceLocation(loc);
  6296. if (parser && parser.options.ranges) this.range = [pos, 0];
  6297. if (parser && parser.filename) this.loc.filename = parser.filename;
  6298. }
  6299. __clone() {
  6300. const newNode = new Node();
  6301. const keys = Object.keys(this);
  6302. for (let i = 0, length = keys.length; i < length; i++) {
  6303. const key = keys[i];
  6304. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  6305. newNode[key] = this[key];
  6306. }
  6307. }
  6308. return newNode;
  6309. }
  6310. }
  6311. class NodeUtils extends UtilParser {
  6312. startNode() {
  6313. return new Node(this, this.state.start, this.state.startLoc);
  6314. }
  6315. startNodeAt(pos, loc) {
  6316. return new Node(this, pos, loc);
  6317. }
  6318. startNodeAtNode(type) {
  6319. return this.startNodeAt(type.start, type.loc.start);
  6320. }
  6321. finishNode(node, type) {
  6322. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  6323. }
  6324. finishNodeAt(node, type, pos, loc) {
  6325. node.type = type;
  6326. node.end = pos;
  6327. node.loc.end = loc;
  6328. if (this.options.ranges) node.range[1] = pos;
  6329. this.processComment(node);
  6330. return node;
  6331. }
  6332. resetStartLocation(node, start, startLoc) {
  6333. node.start = start;
  6334. node.loc.start = startLoc;
  6335. if (this.options.ranges) node.range[0] = start;
  6336. }
  6337. resetStartLocationFromNode(node, locationNode) {
  6338. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  6339. }
  6340. }
  6341. class LValParser extends NodeUtils {
  6342. toAssignable(node, isBinding, contextDescription) {
  6343. if (node) {
  6344. switch (node.type) {
  6345. case "Identifier":
  6346. case "ObjectPattern":
  6347. case "ArrayPattern":
  6348. case "AssignmentPattern":
  6349. break;
  6350. case "ObjectExpression":
  6351. node.type = "ObjectPattern";
  6352. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  6353. const prop = node.properties[i];
  6354. const isLast = i === last;
  6355. this.toAssignableObjectExpressionProp(prop, isBinding, isLast);
  6356. }
  6357. break;
  6358. case "ObjectProperty":
  6359. this.toAssignable(node.value, isBinding, contextDescription);
  6360. break;
  6361. case "SpreadElement":
  6362. {
  6363. this.checkToRestConversion(node);
  6364. node.type = "RestElement";
  6365. const arg = node.argument;
  6366. this.toAssignable(arg, isBinding, contextDescription);
  6367. break;
  6368. }
  6369. case "ArrayExpression":
  6370. node.type = "ArrayPattern";
  6371. this.toAssignableList(node.elements, isBinding, contextDescription);
  6372. break;
  6373. case "AssignmentExpression":
  6374. if (node.operator === "=") {
  6375. node.type = "AssignmentPattern";
  6376. delete node.operator;
  6377. } else {
  6378. this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
  6379. }
  6380. break;
  6381. case "ParenthesizedExpression":
  6382. node.expression = this.toAssignable(node.expression, isBinding, contextDescription);
  6383. break;
  6384. case "MemberExpression":
  6385. if (!isBinding) break;
  6386. default:
  6387. {
  6388. const message = "Invalid left-hand side" + (contextDescription ? " in " + contextDescription : "expression");
  6389. this.raise(node.start, message);
  6390. }
  6391. }
  6392. }
  6393. return node;
  6394. }
  6395. toAssignableObjectExpressionProp(prop, isBinding, isLast) {
  6396. if (prop.type === "ObjectMethod") {
  6397. const error = prop.kind === "get" || prop.kind === "set" ? "Object pattern can't contain getter or setter" : "Object pattern can't contain methods";
  6398. this.raise(prop.key.start, error);
  6399. } else if (prop.type === "SpreadElement" && !isLast) {
  6400. this.raiseRestNotLast(prop.start);
  6401. } else {
  6402. this.toAssignable(prop, isBinding, "object destructuring pattern");
  6403. }
  6404. }
  6405. toAssignableList(exprList, isBinding, contextDescription) {
  6406. let end = exprList.length;
  6407. if (end) {
  6408. const last = exprList[end - 1];
  6409. if (last && last.type === "RestElement") {
  6410. --end;
  6411. } else if (last && last.type === "SpreadElement") {
  6412. last.type = "RestElement";
  6413. const arg = last.argument;
  6414. this.toAssignable(arg, isBinding, contextDescription);
  6415. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  6416. this.unexpected(arg.start);
  6417. }
  6418. --end;
  6419. }
  6420. }
  6421. for (let i = 0; i < end; i++) {
  6422. const elt = exprList[i];
  6423. if (elt) {
  6424. this.toAssignable(elt, isBinding, contextDescription);
  6425. if (elt.type === "RestElement") {
  6426. this.raiseRestNotLast(elt.start);
  6427. }
  6428. }
  6429. }
  6430. return exprList;
  6431. }
  6432. toReferencedList(exprList, isParenthesizedExpr) {
  6433. return exprList;
  6434. }
  6435. toReferencedListDeep(exprList, isParenthesizedExpr) {
  6436. this.toReferencedList(exprList, isParenthesizedExpr);
  6437. for (let _i = 0; _i < exprList.length; _i++) {
  6438. const expr = exprList[_i];
  6439. if (expr && expr.type === "ArrayExpression") {
  6440. this.toReferencedListDeep(expr.elements);
  6441. }
  6442. }
  6443. return exprList;
  6444. }
  6445. parseSpread(refShorthandDefaultPos, refNeedsArrowPos) {
  6446. const node = this.startNode();
  6447. this.next();
  6448. node.argument = this.parseMaybeAssign(false, refShorthandDefaultPos, undefined, refNeedsArrowPos);
  6449. if (this.state.commaAfterSpreadAt === -1 && this.match(types.comma)) {
  6450. this.state.commaAfterSpreadAt = this.state.start;
  6451. }
  6452. return this.finishNode(node, "SpreadElement");
  6453. }
  6454. parseRestBinding() {
  6455. const node = this.startNode();
  6456. this.next();
  6457. node.argument = this.parseBindingAtom();
  6458. return this.finishNode(node, "RestElement");
  6459. }
  6460. parseBindingAtom() {
  6461. switch (this.state.type) {
  6462. case types.bracketL:
  6463. {
  6464. const node = this.startNode();
  6465. this.next();
  6466. node.elements = this.parseBindingList(types.bracketR, true);
  6467. return this.finishNode(node, "ArrayPattern");
  6468. }
  6469. case types.braceL:
  6470. return this.parseObj(true);
  6471. }
  6472. return this.parseIdentifier();
  6473. }
  6474. parseBindingList(close, allowEmpty, allowModifiers) {
  6475. const elts = [];
  6476. let first = true;
  6477. while (!this.eat(close)) {
  6478. if (first) {
  6479. first = false;
  6480. } else {
  6481. this.expect(types.comma);
  6482. }
  6483. if (allowEmpty && this.match(types.comma)) {
  6484. elts.push(null);
  6485. } else if (this.eat(close)) {
  6486. break;
  6487. } else if (this.match(types.ellipsis)) {
  6488. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  6489. this.checkCommaAfterRest();
  6490. this.expect(close);
  6491. break;
  6492. } else {
  6493. const decorators = [];
  6494. if (this.match(types.at) && this.hasPlugin("decorators")) {
  6495. this.raise(this.state.start, "Stage 2 decorators cannot be used to decorate parameters");
  6496. }
  6497. while (this.match(types.at)) {
  6498. decorators.push(this.parseDecorator());
  6499. }
  6500. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  6501. }
  6502. }
  6503. return elts;
  6504. }
  6505. parseAssignableListItem(allowModifiers, decorators) {
  6506. const left = this.parseMaybeDefault();
  6507. this.parseAssignableListItemTypes(left);
  6508. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  6509. if (decorators.length) {
  6510. left.decorators = decorators;
  6511. }
  6512. return elt;
  6513. }
  6514. parseAssignableListItemTypes(param) {
  6515. return param;
  6516. }
  6517. parseMaybeDefault(startPos, startLoc, left) {
  6518. startLoc = startLoc || this.state.startLoc;
  6519. startPos = startPos || this.state.start;
  6520. left = left || this.parseBindingAtom();
  6521. if (!this.eat(types.eq)) return left;
  6522. const node = this.startNodeAt(startPos, startLoc);
  6523. node.left = left;
  6524. node.right = this.parseMaybeAssign();
  6525. return this.finishNode(node, "AssignmentPattern");
  6526. }
  6527. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  6528. switch (expr.type) {
  6529. case "Identifier":
  6530. if (this.state.strict && isStrictBindReservedWord(expr.name, this.inModule)) {
  6531. this.raise(expr.start, `${bindingType === BIND_NONE ? "Assigning to" : "Binding"} '${expr.name}' in strict mode`);
  6532. }
  6533. if (checkClashes) {
  6534. const key = `_${expr.name}`;
  6535. if (checkClashes[key]) {
  6536. this.raise(expr.start, "Argument name clash");
  6537. } else {
  6538. checkClashes[key] = true;
  6539. }
  6540. }
  6541. if (!(bindingType & BIND_NONE)) {
  6542. this.scope.declareName(expr.name, bindingType, expr.start);
  6543. }
  6544. break;
  6545. case "MemberExpression":
  6546. if (bindingType !== BIND_NONE) {
  6547. this.raise(expr.start, "Binding member expression");
  6548. }
  6549. break;
  6550. case "ObjectPattern":
  6551. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  6552. let prop = _expr$properties[_i2];
  6553. if (prop.type === "ObjectProperty") prop = prop.value;
  6554. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern");
  6555. }
  6556. break;
  6557. case "ArrayPattern":
  6558. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  6559. const elem = _expr$elements[_i3];
  6560. if (elem) {
  6561. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern");
  6562. }
  6563. }
  6564. break;
  6565. case "AssignmentPattern":
  6566. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  6567. break;
  6568. case "RestElement":
  6569. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  6570. break;
  6571. case "ParenthesizedExpression":
  6572. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  6573. break;
  6574. default:
  6575. {
  6576. const message = (bindingType === BIND_NONE ? "Invalid" : "Binding invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : "expression");
  6577. this.raise(expr.start, message);
  6578. }
  6579. }
  6580. }
  6581. checkToRestConversion(node) {
  6582. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  6583. this.raise(node.argument.start, "Invalid rest operator's argument");
  6584. }
  6585. }
  6586. checkCommaAfterRest() {
  6587. if (this.match(types.comma)) {
  6588. this.raiseRestNotLast(this.state.start);
  6589. }
  6590. }
  6591. checkCommaAfterRestFromSpread() {
  6592. if (this.state.commaAfterSpreadAt > -1) {
  6593. this.raiseRestNotLast(this.state.commaAfterSpreadAt);
  6594. }
  6595. }
  6596. raiseRestNotLast(pos) {
  6597. this.raise(pos, `Rest element must be last element`);
  6598. }
  6599. }
  6600. const unwrapParenthesizedExpression = node => {
  6601. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  6602. };
  6603. class ExpressionParser extends LValParser {
  6604. checkPropClash(prop, propHash) {
  6605. if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) {
  6606. return;
  6607. }
  6608. const key = prop.key;
  6609. const name = key.type === "Identifier" ? key.name : String(key.value);
  6610. if (name === "__proto__") {
  6611. if (propHash.proto) {
  6612. this.raise(key.start, "Redefinition of __proto__ property");
  6613. }
  6614. propHash.proto = true;
  6615. }
  6616. }
  6617. getExpression() {
  6618. this.scope.enter(SCOPE_PROGRAM);
  6619. this.nextToken();
  6620. const expr = this.parseExpression();
  6621. if (!this.match(types.eof)) {
  6622. this.unexpected();
  6623. }
  6624. expr.comments = this.state.comments;
  6625. return expr;
  6626. }
  6627. parseExpression(noIn, refShorthandDefaultPos) {
  6628. const startPos = this.state.start;
  6629. const startLoc = this.state.startLoc;
  6630. const expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
  6631. if (this.match(types.comma)) {
  6632. const node = this.startNodeAt(startPos, startLoc);
  6633. node.expressions = [expr];
  6634. while (this.eat(types.comma)) {
  6635. node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
  6636. }
  6637. this.toReferencedList(node.expressions);
  6638. return this.finishNode(node, "SequenceExpression");
  6639. }
  6640. return expr;
  6641. }
  6642. parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) {
  6643. const startPos = this.state.start;
  6644. const startLoc = this.state.startLoc;
  6645. if (this.isContextual("yield")) {
  6646. if (this.scope.inGenerator) {
  6647. let left = this.parseYield(noIn);
  6648. if (afterLeftParse) {
  6649. left = afterLeftParse.call(this, left, startPos, startLoc);
  6650. }
  6651. return left;
  6652. } else {
  6653. this.state.exprAllowed = false;
  6654. }
  6655. }
  6656. const oldCommaAfterSpreadAt = this.state.commaAfterSpreadAt;
  6657. this.state.commaAfterSpreadAt = -1;
  6658. let failOnShorthandAssign;
  6659. if (refShorthandDefaultPos) {
  6660. failOnShorthandAssign = false;
  6661. } else {
  6662. refShorthandDefaultPos = {
  6663. start: 0
  6664. };
  6665. failOnShorthandAssign = true;
  6666. }
  6667. if (this.match(types.parenL) || this.match(types.name)) {
  6668. this.state.potentialArrowAt = this.state.start;
  6669. }
  6670. let left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos);
  6671. if (afterLeftParse) {
  6672. left = afterLeftParse.call(this, left, startPos, startLoc);
  6673. }
  6674. if (this.state.type.isAssign) {
  6675. const node = this.startNodeAt(startPos, startLoc);
  6676. const operator = this.state.value;
  6677. node.operator = operator;
  6678. if (operator === "??=") {
  6679. this.expectPlugin("nullishCoalescingOperator");
  6680. this.expectPlugin("logicalAssignment");
  6681. }
  6682. if (operator === "||=" || operator === "&&=") {
  6683. this.expectPlugin("logicalAssignment");
  6684. }
  6685. node.left = this.match(types.eq) ? this.toAssignable(left, undefined, "assignment expression") : left;
  6686. refShorthandDefaultPos.start = 0;
  6687. this.checkLVal(left, undefined, undefined, "assignment expression");
  6688. const maybePattern = unwrapParenthesizedExpression(left);
  6689. let patternErrorMsg;
  6690. if (maybePattern.type === "ObjectPattern") {
  6691. patternErrorMsg = "`({a}) = 0` use `({a} = 0)`";
  6692. } else if (maybePattern.type === "ArrayPattern") {
  6693. patternErrorMsg = "`([a]) = 0` use `([a] = 0)`";
  6694. }
  6695. if (patternErrorMsg && (left.extra && left.extra.parenthesized || left.type === "ParenthesizedExpression")) {
  6696. this.raise(maybePattern.start, `You're trying to assign to a parenthesized expression, eg. instead of ${patternErrorMsg}`);
  6697. }
  6698. if (patternErrorMsg) this.checkCommaAfterRestFromSpread();
  6699. this.state.commaAfterSpreadAt = oldCommaAfterSpreadAt;
  6700. this.next();
  6701. node.right = this.parseMaybeAssign(noIn);
  6702. return this.finishNode(node, "AssignmentExpression");
  6703. } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
  6704. this.unexpected(refShorthandDefaultPos.start);
  6705. }
  6706. this.state.commaAfterSpreadAt = oldCommaAfterSpreadAt;
  6707. return left;
  6708. }
  6709. parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos) {
  6710. const startPos = this.state.start;
  6711. const startLoc = this.state.startLoc;
  6712. const potentialArrowAt = this.state.potentialArrowAt;
  6713. const expr = this.parseExprOps(noIn, refShorthandDefaultPos);
  6714. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  6715. return expr;
  6716. }
  6717. if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
  6718. return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  6719. }
  6720. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  6721. if (this.eat(types.question)) {
  6722. const node = this.startNodeAt(startPos, startLoc);
  6723. node.test = expr;
  6724. node.consequent = this.parseMaybeAssign();
  6725. this.expect(types.colon);
  6726. node.alternate = this.parseMaybeAssign(noIn);
  6727. return this.finishNode(node, "ConditionalExpression");
  6728. }
  6729. return expr;
  6730. }
  6731. parseExprOps(noIn, refShorthandDefaultPos) {
  6732. const startPos = this.state.start;
  6733. const startLoc = this.state.startLoc;
  6734. const potentialArrowAt = this.state.potentialArrowAt;
  6735. const expr = this.parseMaybeUnary(refShorthandDefaultPos);
  6736. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  6737. return expr;
  6738. }
  6739. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  6740. return expr;
  6741. }
  6742. return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  6743. }
  6744. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  6745. const prec = this.state.type.binop;
  6746. if (prec != null && (!noIn || !this.match(types._in))) {
  6747. if (prec > minPrec) {
  6748. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  6749. const operator = this.state.value;
  6750. node.left = left;
  6751. node.operator = operator;
  6752. if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  6753. this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");
  6754. }
  6755. const op = this.state.type;
  6756. if (op === types.pipeline) {
  6757. this.expectPlugin("pipelineOperator");
  6758. this.state.inPipeline = true;
  6759. this.checkPipelineAtInfixOperator(left, leftStartPos);
  6760. } else if (op === types.nullishCoalescing) {
  6761. this.expectPlugin("nullishCoalescingOperator");
  6762. }
  6763. this.next();
  6764. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  6765. if (this.match(types.name) && this.state.value === "await" && this.scope.inAsync) {
  6766. throw this.raise(this.state.start, `Unexpected "await" after pipeline body; await must have parentheses in minimal proposal`);
  6767. }
  6768. }
  6769. node.right = this.parseExprOpRightExpr(op, prec, noIn);
  6770. this.finishNode(node, op === types.logicalOR || op === types.logicalAND || op === types.nullishCoalescing ? "LogicalExpression" : "BinaryExpression");
  6771. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  6772. }
  6773. }
  6774. return left;
  6775. }
  6776. parseExprOpRightExpr(op, prec, noIn) {
  6777. switch (op) {
  6778. case types.pipeline:
  6779. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  6780. const startPos = this.state.start;
  6781. const startLoc = this.state.startLoc;
  6782. return this.withTopicPermittingContext(() => {
  6783. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc);
  6784. });
  6785. }
  6786. default:
  6787. return this.parseExprOpBaseRightExpr(op, prec, noIn);
  6788. }
  6789. }
  6790. parseExprOpBaseRightExpr(op, prec, noIn) {
  6791. const startPos = this.state.start;
  6792. const startLoc = this.state.startLoc;
  6793. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
  6794. }
  6795. parseMaybeUnary(refShorthandDefaultPos) {
  6796. if (this.isContextual("await") && (this.scope.inAsync || !this.scope.inFunction && this.options.allowAwaitOutsideFunction)) {
  6797. return this.parseAwait();
  6798. } else if (this.state.type.prefix) {
  6799. const node = this.startNode();
  6800. const update = this.match(types.incDec);
  6801. node.operator = this.state.value;
  6802. node.prefix = true;
  6803. if (node.operator === "throw") {
  6804. this.expectPlugin("throwExpressions");
  6805. }
  6806. this.next();
  6807. node.argument = this.parseMaybeUnary();
  6808. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  6809. this.unexpected(refShorthandDefaultPos.start);
  6810. }
  6811. if (update) {
  6812. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  6813. } else if (this.state.strict && node.operator === "delete") {
  6814. const arg = node.argument;
  6815. if (arg.type === "Identifier") {
  6816. this.raise(node.start, "Deleting local variable in strict mode");
  6817. } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") {
  6818. this.raise(node.start, "Deleting a private field is not allowed");
  6819. }
  6820. }
  6821. return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  6822. }
  6823. const startPos = this.state.start;
  6824. const startLoc = this.state.startLoc;
  6825. let expr = this.parseExprSubscripts(refShorthandDefaultPos);
  6826. if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
  6827. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  6828. const node = this.startNodeAt(startPos, startLoc);
  6829. node.operator = this.state.value;
  6830. node.prefix = false;
  6831. node.argument = expr;
  6832. this.checkLVal(expr, undefined, undefined, "postfix operation");
  6833. this.next();
  6834. expr = this.finishNode(node, "UpdateExpression");
  6835. }
  6836. return expr;
  6837. }
  6838. parseExprSubscripts(refShorthandDefaultPos) {
  6839. const startPos = this.state.start;
  6840. const startLoc = this.state.startLoc;
  6841. const potentialArrowAt = this.state.potentialArrowAt;
  6842. const expr = this.parseExprAtom(refShorthandDefaultPos);
  6843. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  6844. return expr;
  6845. }
  6846. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  6847. return expr;
  6848. }
  6849. return this.parseSubscripts(expr, startPos, startLoc);
  6850. }
  6851. parseSubscripts(base, startPos, startLoc, noCalls) {
  6852. const maybeAsyncArrow = this.atPossibleAsync(base);
  6853. const state = {
  6854. optionalChainMember: false,
  6855. stop: false
  6856. };
  6857. do {
  6858. base = this.parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow);
  6859. } while (!state.stop);
  6860. return base;
  6861. }
  6862. parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow) {
  6863. if (!noCalls && this.eat(types.doubleColon)) {
  6864. const node = this.startNodeAt(startPos, startLoc);
  6865. node.object = base;
  6866. node.callee = this.parseNoCallExpr();
  6867. state.stop = true;
  6868. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  6869. } else if (this.match(types.questionDot)) {
  6870. this.expectPlugin("optionalChaining");
  6871. state.optionalChainMember = true;
  6872. if (noCalls && this.lookahead().type === types.parenL) {
  6873. state.stop = true;
  6874. return base;
  6875. }
  6876. this.next();
  6877. const node = this.startNodeAt(startPos, startLoc);
  6878. if (this.eat(types.bracketL)) {
  6879. node.object = base;
  6880. node.property = this.parseExpression();
  6881. node.computed = true;
  6882. node.optional = true;
  6883. this.expect(types.bracketR);
  6884. return this.finishNode(node, "OptionalMemberExpression");
  6885. } else if (this.eat(types.parenL)) {
  6886. node.callee = base;
  6887. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  6888. node.optional = true;
  6889. return this.finishNode(node, "OptionalCallExpression");
  6890. } else {
  6891. node.object = base;
  6892. node.property = this.parseIdentifier(true);
  6893. node.computed = false;
  6894. node.optional = true;
  6895. return this.finishNode(node, "OptionalMemberExpression");
  6896. }
  6897. } else if (this.eat(types.dot)) {
  6898. const node = this.startNodeAt(startPos, startLoc);
  6899. node.object = base;
  6900. node.property = this.parseMaybePrivateName();
  6901. node.computed = false;
  6902. if (state.optionalChainMember) {
  6903. node.optional = false;
  6904. return this.finishNode(node, "OptionalMemberExpression");
  6905. }
  6906. return this.finishNode(node, "MemberExpression");
  6907. } else if (this.eat(types.bracketL)) {
  6908. const node = this.startNodeAt(startPos, startLoc);
  6909. node.object = base;
  6910. node.property = this.parseExpression();
  6911. node.computed = true;
  6912. this.expect(types.bracketR);
  6913. if (state.optionalChainMember) {
  6914. node.optional = false;
  6915. return this.finishNode(node, "OptionalMemberExpression");
  6916. }
  6917. return this.finishNode(node, "MemberExpression");
  6918. } else if (!noCalls && this.match(types.parenL)) {
  6919. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  6920. const oldYieldPos = this.state.yieldPos;
  6921. const oldAwaitPos = this.state.awaitPos;
  6922. this.state.maybeInArrowParameters = true;
  6923. this.state.yieldPos = 0;
  6924. this.state.awaitPos = 0;
  6925. this.next();
  6926. let node = this.startNodeAt(startPos, startLoc);
  6927. node.callee = base;
  6928. const oldCommaAfterSpreadAt = this.state.commaAfterSpreadAt;
  6929. this.state.commaAfterSpreadAt = -1;
  6930. node.arguments = this.parseCallExpressionArguments(types.parenR, maybeAsyncArrow, base.type === "Import", base.type !== "Super");
  6931. if (!state.optionalChainMember) {
  6932. this.finishCallExpression(node);
  6933. } else {
  6934. this.finishOptionalCallExpression(node);
  6935. }
  6936. if (maybeAsyncArrow && this.shouldParseAsyncArrow()) {
  6937. state.stop = true;
  6938. this.checkCommaAfterRestFromSpread();
  6939. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  6940. this.checkYieldAwaitInDefaultParams();
  6941. this.state.yieldPos = oldYieldPos;
  6942. this.state.awaitPos = oldAwaitPos;
  6943. } else {
  6944. this.toReferencedListDeep(node.arguments);
  6945. this.state.yieldPos = oldYieldPos || this.state.yieldPos;
  6946. this.state.awaitPos = oldAwaitPos || this.state.awaitPos;
  6947. }
  6948. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  6949. this.state.commaAfterSpreadAt = oldCommaAfterSpreadAt;
  6950. return node;
  6951. } else if (this.match(types.backQuote)) {
  6952. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state);
  6953. } else {
  6954. state.stop = true;
  6955. return base;
  6956. }
  6957. }
  6958. parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) {
  6959. const node = this.startNodeAt(startPos, startLoc);
  6960. node.tag = base;
  6961. node.quasi = this.parseTemplate(true);
  6962. if (typeArguments) node.typeParameters = typeArguments;
  6963. if (state.optionalChainMember) {
  6964. this.raise(startPos, "Tagged Template Literals are not allowed in optionalChain");
  6965. }
  6966. return this.finishNode(node, "TaggedTemplateExpression");
  6967. }
  6968. atPossibleAsync(base) {
  6969. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async";
  6970. }
  6971. finishCallExpression(node) {
  6972. if (node.callee.type === "Import") {
  6973. if (node.arguments.length !== 1) {
  6974. this.raise(node.start, "import() requires exactly one argument");
  6975. }
  6976. const importArg = node.arguments[0];
  6977. if (importArg && importArg.type === "SpreadElement") {
  6978. this.raise(importArg.start, "... is not allowed in import()");
  6979. }
  6980. }
  6981. return this.finishNode(node, "CallExpression");
  6982. }
  6983. finishOptionalCallExpression(node) {
  6984. if (node.callee.type === "Import") {
  6985. if (node.arguments.length !== 1) {
  6986. this.raise(node.start, "import() requires exactly one argument");
  6987. }
  6988. const importArg = node.arguments[0];
  6989. if (importArg && importArg.type === "SpreadElement") {
  6990. this.raise(importArg.start, "... is not allowed in import()");
  6991. }
  6992. }
  6993. return this.finishNode(node, "OptionalCallExpression");
  6994. }
  6995. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder) {
  6996. const elts = [];
  6997. let innerParenStart;
  6998. let first = true;
  6999. while (!this.eat(close)) {
  7000. if (first) {
  7001. first = false;
  7002. } else {
  7003. this.expect(types.comma);
  7004. if (this.eat(close)) {
  7005. if (dynamicImport) {
  7006. this.raise(this.state.lastTokStart, "Trailing comma is disallowed inside import(...) arguments");
  7007. }
  7008. break;
  7009. }
  7010. }
  7011. if (this.match(types.parenL) && !innerParenStart) {
  7012. innerParenStart = this.state.start;
  7013. }
  7014. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? {
  7015. start: 0
  7016. } : undefined, possibleAsyncArrow ? {
  7017. start: 0
  7018. } : undefined, allowPlaceholder));
  7019. }
  7020. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  7021. this.unexpected();
  7022. }
  7023. return elts;
  7024. }
  7025. shouldParseAsyncArrow() {
  7026. return this.match(types.arrow) && !this.canInsertSemicolon();
  7027. }
  7028. parseAsyncArrowFromCallExpression(node, call) {
  7029. this.expect(types.arrow);
  7030. this.parseArrowExpression(node, call.arguments, true);
  7031. return node;
  7032. }
  7033. parseNoCallExpr() {
  7034. const startPos = this.state.start;
  7035. const startLoc = this.state.startLoc;
  7036. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  7037. }
  7038. parseExprAtom(refShorthandDefaultPos) {
  7039. if (this.state.type === types.slash) this.readRegexp();
  7040. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  7041. let node;
  7042. switch (this.state.type) {
  7043. case types._super:
  7044. if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  7045. this.raise(this.state.start, "super is only allowed in object methods and classes");
  7046. }
  7047. node = this.startNode();
  7048. this.next();
  7049. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  7050. this.raise(node.start, "super() is only valid inside a class constructor of a subclass. " + "Maybe a typo in the method name ('constructor') or not extending another class?");
  7051. }
  7052. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  7053. this.unexpected();
  7054. }
  7055. return this.finishNode(node, "Super");
  7056. case types._import:
  7057. if (this.lookahead().type === types.dot) {
  7058. return this.parseImportMetaProperty();
  7059. }
  7060. this.expectPlugin("dynamicImport");
  7061. node = this.startNode();
  7062. this.next();
  7063. if (!this.match(types.parenL)) {
  7064. this.unexpected(null, types.parenL);
  7065. }
  7066. return this.finishNode(node, "Import");
  7067. case types._this:
  7068. node = this.startNode();
  7069. this.next();
  7070. return this.finishNode(node, "ThisExpression");
  7071. case types.name:
  7072. {
  7073. node = this.startNode();
  7074. const containsEsc = this.state.containsEsc;
  7075. const id = this.parseIdentifier();
  7076. if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) {
  7077. this.next();
  7078. return this.parseFunction(node, undefined, true);
  7079. } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) {
  7080. const params = [this.parseIdentifier()];
  7081. this.expect(types.arrow);
  7082. this.parseArrowExpression(node, params, true);
  7083. return node;
  7084. }
  7085. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  7086. this.next();
  7087. this.parseArrowExpression(node, [id], false);
  7088. return node;
  7089. }
  7090. return id;
  7091. }
  7092. case types._do:
  7093. {
  7094. this.expectPlugin("doExpressions");
  7095. const node = this.startNode();
  7096. this.next();
  7097. const oldLabels = this.state.labels;
  7098. this.state.labels = [];
  7099. node.body = this.parseBlock();
  7100. this.state.labels = oldLabels;
  7101. return this.finishNode(node, "DoExpression");
  7102. }
  7103. case types.regexp:
  7104. {
  7105. const value = this.state.value;
  7106. node = this.parseLiteral(value.value, "RegExpLiteral");
  7107. node.pattern = value.pattern;
  7108. node.flags = value.flags;
  7109. return node;
  7110. }
  7111. case types.num:
  7112. return this.parseLiteral(this.state.value, "NumericLiteral");
  7113. case types.bigint:
  7114. return this.parseLiteral(this.state.value, "BigIntLiteral");
  7115. case types.string:
  7116. return this.parseLiteral(this.state.value, "StringLiteral");
  7117. case types._null:
  7118. node = this.startNode();
  7119. this.next();
  7120. return this.finishNode(node, "NullLiteral");
  7121. case types._true:
  7122. case types._false:
  7123. return this.parseBooleanLiteral();
  7124. case types.parenL:
  7125. return this.parseParenAndDistinguishExpression(canBeArrow);
  7126. case types.bracketL:
  7127. node = this.startNode();
  7128. this.next();
  7129. node.elements = this.parseExprList(types.bracketR, true, refShorthandDefaultPos);
  7130. if (!this.state.maybeInArrowParameters) {
  7131. this.toReferencedList(node.elements);
  7132. }
  7133. return this.finishNode(node, "ArrayExpression");
  7134. case types.braceL:
  7135. return this.parseObj(false, refShorthandDefaultPos);
  7136. case types._function:
  7137. return this.parseFunctionExpression();
  7138. case types.at:
  7139. this.parseDecorators();
  7140. case types._class:
  7141. node = this.startNode();
  7142. this.takeDecorators(node);
  7143. return this.parseClass(node, false);
  7144. case types._new:
  7145. return this.parseNew();
  7146. case types.backQuote:
  7147. return this.parseTemplate(false);
  7148. case types.doubleColon:
  7149. {
  7150. node = this.startNode();
  7151. this.next();
  7152. node.object = null;
  7153. const callee = node.callee = this.parseNoCallExpr();
  7154. if (callee.type === "MemberExpression") {
  7155. return this.finishNode(node, "BindExpression");
  7156. } else {
  7157. throw this.raise(callee.start, "Binding should be performed on object property.");
  7158. }
  7159. }
  7160. case types.hash:
  7161. {
  7162. if (this.state.inPipeline) {
  7163. node = this.startNode();
  7164. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  7165. this.raise(node.start, "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.");
  7166. }
  7167. this.next();
  7168. if (this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  7169. this.registerTopicReference();
  7170. return this.finishNode(node, "PipelinePrimaryTopicReference");
  7171. } else {
  7172. throw this.raise(node.start, `Topic reference was used in a lexical context without topic binding`);
  7173. }
  7174. }
  7175. }
  7176. default:
  7177. throw this.unexpected();
  7178. }
  7179. }
  7180. parseBooleanLiteral() {
  7181. const node = this.startNode();
  7182. node.value = this.match(types._true);
  7183. this.next();
  7184. return this.finishNode(node, "BooleanLiteral");
  7185. }
  7186. parseMaybePrivateName() {
  7187. const isPrivate = this.match(types.hash);
  7188. if (isPrivate) {
  7189. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  7190. const node = this.startNode();
  7191. this.next();
  7192. this.assertNoSpace("Unexpected space between # and identifier");
  7193. node.id = this.parseIdentifier(true);
  7194. return this.finishNode(node, "PrivateName");
  7195. } else {
  7196. return this.parseIdentifier(true);
  7197. }
  7198. }
  7199. parseFunctionExpression() {
  7200. const node = this.startNode();
  7201. let meta = this.startNode();
  7202. this.next();
  7203. meta = this.createIdentifier(meta, "function");
  7204. if (this.scope.inGenerator && this.eat(types.dot)) {
  7205. return this.parseMetaProperty(node, meta, "sent");
  7206. }
  7207. return this.parseFunction(node);
  7208. }
  7209. parseMetaProperty(node, meta, propertyName) {
  7210. node.meta = meta;
  7211. if (meta.name === "function" && propertyName === "sent") {
  7212. if (this.isContextual(propertyName)) {
  7213. this.expectPlugin("functionSent");
  7214. } else if (!this.hasPlugin("functionSent")) {
  7215. this.unexpected();
  7216. }
  7217. }
  7218. const containsEsc = this.state.containsEsc;
  7219. node.property = this.parseIdentifier(true);
  7220. if (node.property.name !== propertyName || containsEsc) {
  7221. this.raise(node.property.start, `The only valid meta property for ${meta.name} is ${meta.name}.${propertyName}`);
  7222. }
  7223. return this.finishNode(node, "MetaProperty");
  7224. }
  7225. parseImportMetaProperty() {
  7226. const node = this.startNode();
  7227. const id = this.parseIdentifier(true);
  7228. this.expect(types.dot);
  7229. if (id.name === "import") {
  7230. if (this.isContextual("meta")) {
  7231. this.expectPlugin("importMeta");
  7232. } else if (!this.hasPlugin("importMeta")) {
  7233. this.raise(id.start, `Dynamic imports require a parameter: import('a.js')`);
  7234. }
  7235. }
  7236. if (!this.inModule) {
  7237. this.raise(id.start, `import.meta may appear only with 'sourceType: "module"'`, {
  7238. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  7239. });
  7240. }
  7241. this.sawUnambiguousESM = true;
  7242. return this.parseMetaProperty(node, id, "meta");
  7243. }
  7244. parseLiteral(value, type, startPos, startLoc) {
  7245. startPos = startPos || this.state.start;
  7246. startLoc = startLoc || this.state.startLoc;
  7247. const node = this.startNodeAt(startPos, startLoc);
  7248. this.addExtra(node, "rawValue", value);
  7249. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  7250. node.value = value;
  7251. this.next();
  7252. return this.finishNode(node, type);
  7253. }
  7254. parseParenAndDistinguishExpression(canBeArrow) {
  7255. const startPos = this.state.start;
  7256. const startLoc = this.state.startLoc;
  7257. let val;
  7258. this.expect(types.parenL);
  7259. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7260. const oldYieldPos = this.state.yieldPos;
  7261. const oldAwaitPos = this.state.awaitPos;
  7262. this.state.maybeInArrowParameters = true;
  7263. this.state.yieldPos = 0;
  7264. this.state.awaitPos = 0;
  7265. const innerStartPos = this.state.start;
  7266. const innerStartLoc = this.state.startLoc;
  7267. const exprList = [];
  7268. const refShorthandDefaultPos = {
  7269. start: 0
  7270. };
  7271. const refNeedsArrowPos = {
  7272. start: 0
  7273. };
  7274. let first = true;
  7275. let spreadStart;
  7276. let optionalCommaStart;
  7277. while (!this.match(types.parenR)) {
  7278. if (first) {
  7279. first = false;
  7280. } else {
  7281. this.expect(types.comma, refNeedsArrowPos.start || null);
  7282. if (this.match(types.parenR)) {
  7283. optionalCommaStart = this.state.start;
  7284. break;
  7285. }
  7286. }
  7287. if (this.match(types.ellipsis)) {
  7288. const spreadNodeStartPos = this.state.start;
  7289. const spreadNodeStartLoc = this.state.startLoc;
  7290. spreadStart = this.state.start;
  7291. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  7292. this.checkCommaAfterRest();
  7293. break;
  7294. } else {
  7295. exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos));
  7296. }
  7297. }
  7298. const innerEndPos = this.state.start;
  7299. const innerEndLoc = this.state.startLoc;
  7300. this.expect(types.parenR);
  7301. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7302. let arrowNode = this.startNodeAt(startPos, startLoc);
  7303. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  7304. this.checkYieldAwaitInDefaultParams();
  7305. this.state.yieldPos = oldYieldPos;
  7306. this.state.awaitPos = oldAwaitPos;
  7307. for (let _i = 0; _i < exprList.length; _i++) {
  7308. const param = exprList[_i];
  7309. if (param.extra && param.extra.parenthesized) {
  7310. this.unexpected(param.extra.parenStart);
  7311. }
  7312. }
  7313. this.parseArrowExpression(arrowNode, exprList, false);
  7314. return arrowNode;
  7315. }
  7316. this.state.yieldPos = oldYieldPos || this.state.yieldPos;
  7317. this.state.awaitPos = oldAwaitPos || this.state.awaitPos;
  7318. if (!exprList.length) {
  7319. this.unexpected(this.state.lastTokStart);
  7320. }
  7321. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  7322. if (spreadStart) this.unexpected(spreadStart);
  7323. if (refShorthandDefaultPos.start) {
  7324. this.unexpected(refShorthandDefaultPos.start);
  7325. }
  7326. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  7327. this.toReferencedListDeep(exprList, true);
  7328. if (exprList.length > 1) {
  7329. val = this.startNodeAt(innerStartPos, innerStartLoc);
  7330. val.expressions = exprList;
  7331. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  7332. } else {
  7333. val = exprList[0];
  7334. }
  7335. if (!this.options.createParenthesizedExpressions) {
  7336. this.addExtra(val, "parenthesized", true);
  7337. this.addExtra(val, "parenStart", startPos);
  7338. return val;
  7339. }
  7340. const parenExpression = this.startNodeAt(startPos, startLoc);
  7341. parenExpression.expression = val;
  7342. this.finishNode(parenExpression, "ParenthesizedExpression");
  7343. return parenExpression;
  7344. }
  7345. shouldParseArrow() {
  7346. return !this.canInsertSemicolon();
  7347. }
  7348. parseArrow(node) {
  7349. if (this.eat(types.arrow)) {
  7350. return node;
  7351. }
  7352. }
  7353. parseParenItem(node, startPos, startLoc) {
  7354. return node;
  7355. }
  7356. parseNew() {
  7357. const node = this.startNode();
  7358. const meta = this.parseIdentifier(true);
  7359. if (this.eat(types.dot)) {
  7360. const metaProp = this.parseMetaProperty(node, meta, "target");
  7361. if (!this.scope.inNonArrowFunction && !this.state.inClassProperty) {
  7362. let error = "new.target can only be used in functions";
  7363. if (this.hasPlugin("classProperties")) {
  7364. error += " or class properties";
  7365. }
  7366. this.raise(metaProp.start, error);
  7367. }
  7368. return metaProp;
  7369. }
  7370. node.callee = this.parseNoCallExpr();
  7371. if (node.callee.type === "Import") {
  7372. this.raise(node.callee.start, "Cannot use new with import(...)");
  7373. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  7374. this.raise(this.state.lastTokEnd, "constructors in/after an Optional Chain are not allowed");
  7375. } else if (this.eat(types.questionDot)) {
  7376. this.raise(this.state.start, "constructors in/after an Optional Chain are not allowed");
  7377. }
  7378. this.parseNewArguments(node);
  7379. return this.finishNode(node, "NewExpression");
  7380. }
  7381. parseNewArguments(node) {
  7382. if (this.eat(types.parenL)) {
  7383. const args = this.parseExprList(types.parenR);
  7384. this.toReferencedList(args);
  7385. node.arguments = args;
  7386. } else {
  7387. node.arguments = [];
  7388. }
  7389. }
  7390. parseTemplateElement(isTagged) {
  7391. const elem = this.startNode();
  7392. if (this.state.value === null) {
  7393. if (!isTagged) {
  7394. this.raise(this.state.invalidTemplateEscapePosition || 0, "Invalid escape sequence in template");
  7395. } else {
  7396. this.state.invalidTemplateEscapePosition = null;
  7397. }
  7398. }
  7399. elem.value = {
  7400. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  7401. cooked: this.state.value
  7402. };
  7403. this.next();
  7404. elem.tail = this.match(types.backQuote);
  7405. return this.finishNode(elem, "TemplateElement");
  7406. }
  7407. parseTemplate(isTagged) {
  7408. const node = this.startNode();
  7409. this.next();
  7410. node.expressions = [];
  7411. let curElt = this.parseTemplateElement(isTagged);
  7412. node.quasis = [curElt];
  7413. while (!curElt.tail) {
  7414. this.expect(types.dollarBraceL);
  7415. node.expressions.push(this.parseExpression());
  7416. this.expect(types.braceR);
  7417. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  7418. }
  7419. this.next();
  7420. return this.finishNode(node, "TemplateLiteral");
  7421. }
  7422. parseObj(isPattern, refShorthandDefaultPos) {
  7423. const propHash = Object.create(null);
  7424. let first = true;
  7425. const node = this.startNode();
  7426. node.properties = [];
  7427. this.next();
  7428. while (!this.eat(types.braceR)) {
  7429. if (first) {
  7430. first = false;
  7431. } else {
  7432. this.expect(types.comma);
  7433. if (this.eat(types.braceR)) break;
  7434. }
  7435. const prop = this.parseObjectMember(isPattern, refShorthandDefaultPos);
  7436. if (!isPattern) this.checkPropClash(prop, propHash);
  7437. if (prop.shorthand) {
  7438. this.addExtra(prop, "shorthand", true);
  7439. }
  7440. node.properties.push(prop);
  7441. }
  7442. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
  7443. }
  7444. isAsyncProp(prop) {
  7445. 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();
  7446. }
  7447. parseObjectMember(isPattern, refShorthandDefaultPos) {
  7448. let decorators = [];
  7449. if (this.match(types.at)) {
  7450. if (this.hasPlugin("decorators")) {
  7451. this.raise(this.state.start, "Stage 2 decorators disallow object literal property decorators");
  7452. } else {
  7453. while (this.match(types.at)) {
  7454. decorators.push(this.parseDecorator());
  7455. }
  7456. }
  7457. }
  7458. const prop = this.startNode();
  7459. let isGenerator = false;
  7460. let isAsync = false;
  7461. let startPos;
  7462. let startLoc;
  7463. if (this.match(types.ellipsis)) {
  7464. if (decorators.length) this.unexpected();
  7465. if (isPattern) {
  7466. this.next();
  7467. prop.argument = this.parseIdentifier();
  7468. this.checkCommaAfterRest();
  7469. return this.finishNode(prop, "RestElement");
  7470. }
  7471. return this.parseSpread();
  7472. }
  7473. if (decorators.length) {
  7474. prop.decorators = decorators;
  7475. decorators = [];
  7476. }
  7477. prop.method = false;
  7478. if (isPattern || refShorthandDefaultPos) {
  7479. startPos = this.state.start;
  7480. startLoc = this.state.startLoc;
  7481. }
  7482. if (!isPattern) {
  7483. isGenerator = this.eat(types.star);
  7484. }
  7485. const containsEsc = this.state.containsEsc;
  7486. this.parsePropertyName(prop);
  7487. if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) {
  7488. isAsync = true;
  7489. isGenerator = this.eat(types.star);
  7490. this.parsePropertyName(prop);
  7491. } else {
  7492. isAsync = false;
  7493. }
  7494. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc);
  7495. return prop;
  7496. }
  7497. isGetterOrSetterMethod(prop, isPattern) {
  7498. 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);
  7499. }
  7500. getGetterSetterExpectedParamCount(method) {
  7501. return method.kind === "get" ? 0 : 1;
  7502. }
  7503. checkGetterSetterParams(method) {
  7504. const paramCount = this.getGetterSetterExpectedParamCount(method);
  7505. const start = method.start;
  7506. if (method.params.length !== paramCount) {
  7507. if (method.kind === "get") {
  7508. this.raise(start, "getter must not have any formal parameters");
  7509. } else {
  7510. this.raise(start, "setter must have exactly one formal parameter");
  7511. }
  7512. }
  7513. if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") {
  7514. this.raise(start, "setter function argument must not be a rest parameter");
  7515. }
  7516. }
  7517. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  7518. if (isAsync || isGenerator || this.match(types.parenL)) {
  7519. if (isPattern) this.unexpected();
  7520. prop.kind = "method";
  7521. prop.method = true;
  7522. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  7523. }
  7524. if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) {
  7525. if (isGenerator || isAsync) this.unexpected();
  7526. prop.kind = prop.key.name;
  7527. this.parsePropertyName(prop);
  7528. this.parseMethod(prop, false, false, false, false, "ObjectMethod");
  7529. this.checkGetterSetterParams(prop);
  7530. return prop;
  7531. }
  7532. }
  7533. parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) {
  7534. prop.shorthand = false;
  7535. if (this.eat(types.colon)) {
  7536. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
  7537. return this.finishNode(prop, "ObjectProperty");
  7538. }
  7539. if (!prop.computed && prop.key.type === "Identifier") {
  7540. this.checkReservedWord(prop.key.name, prop.key.start, true, true);
  7541. if (isPattern) {
  7542. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  7543. } else if (this.match(types.eq) && refShorthandDefaultPos) {
  7544. if (!refShorthandDefaultPos.start) {
  7545. refShorthandDefaultPos.start = this.state.start;
  7546. }
  7547. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  7548. } else {
  7549. prop.value = prop.key.__clone();
  7550. }
  7551. prop.shorthand = true;
  7552. return this.finishNode(prop, "ObjectProperty");
  7553. }
  7554. }
  7555. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) {
  7556. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos);
  7557. if (!node) this.unexpected();
  7558. return node;
  7559. }
  7560. parsePropertyName(prop) {
  7561. if (this.eat(types.bracketL)) {
  7562. prop.computed = true;
  7563. prop.key = this.parseMaybeAssign();
  7564. this.expect(types.bracketR);
  7565. } else {
  7566. const oldInPropertyName = this.state.inPropertyName;
  7567. this.state.inPropertyName = true;
  7568. prop.key = this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseMaybePrivateName();
  7569. if (prop.key.type !== "PrivateName") {
  7570. prop.computed = false;
  7571. }
  7572. this.state.inPropertyName = oldInPropertyName;
  7573. }
  7574. return prop.key;
  7575. }
  7576. initFunction(node, isAsync) {
  7577. node.id = null;
  7578. node.generator = false;
  7579. node.async = !!isAsync;
  7580. }
  7581. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  7582. const oldYieldPos = this.state.yieldPos;
  7583. const oldAwaitPos = this.state.awaitPos;
  7584. this.state.yieldPos = 0;
  7585. this.state.awaitPos = 0;
  7586. this.initFunction(node, isAsync);
  7587. node.generator = !!isGenerator;
  7588. const allowModifiers = isConstructor;
  7589. this.scope.enter(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  7590. this.parseFunctionParams(node, allowModifiers);
  7591. this.checkYieldAwaitInDefaultParams();
  7592. this.parseFunctionBodyAndFinish(node, type, true);
  7593. this.scope.exit();
  7594. this.state.yieldPos = oldYieldPos;
  7595. this.state.awaitPos = oldAwaitPos;
  7596. return node;
  7597. }
  7598. parseArrowExpression(node, params, isAsync) {
  7599. this.scope.enter(functionFlags(isAsync, false) | SCOPE_ARROW);
  7600. this.initFunction(node, isAsync);
  7601. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7602. const oldYieldPos = this.state.yieldPos;
  7603. const oldAwaitPos = this.state.awaitPos;
  7604. this.state.maybeInArrowParameters = false;
  7605. this.state.yieldPos = 0;
  7606. this.state.awaitPos = 0;
  7607. if (params) this.setArrowFunctionParameters(node, params);
  7608. this.parseFunctionBody(node, true);
  7609. this.scope.exit();
  7610. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7611. this.state.yieldPos = oldYieldPos;
  7612. this.state.awaitPos = oldAwaitPos;
  7613. return this.finishNode(node, "ArrowFunctionExpression");
  7614. }
  7615. setArrowFunctionParameters(node, params) {
  7616. node.params = this.toAssignableList(params, true, "arrow function parameters");
  7617. }
  7618. isStrictBody(node) {
  7619. const isBlockStatement = node.body.type === "BlockStatement";
  7620. if (isBlockStatement && node.body.directives.length) {
  7621. for (let _i2 = 0, _node$body$directives = node.body.directives; _i2 < _node$body$directives.length; _i2++) {
  7622. const directive = _node$body$directives[_i2];
  7623. if (directive.value.value === "use strict") {
  7624. return true;
  7625. }
  7626. }
  7627. }
  7628. return false;
  7629. }
  7630. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  7631. this.parseFunctionBody(node, false, isMethod);
  7632. this.finishNode(node, type);
  7633. }
  7634. parseFunctionBody(node, allowExpression, isMethod = false) {
  7635. const isExpression = allowExpression && !this.match(types.braceL);
  7636. const oldStrict = this.state.strict;
  7637. let useStrict = false;
  7638. const oldInParameters = this.state.inParameters;
  7639. this.state.inParameters = false;
  7640. if (isExpression) {
  7641. node.body = this.parseMaybeAssign();
  7642. this.checkParams(node, false, allowExpression);
  7643. } else {
  7644. const nonSimple = !this.isSimpleParamList(node.params);
  7645. if (!oldStrict || nonSimple) {
  7646. useStrict = this.strictDirective(this.state.end);
  7647. if (useStrict && nonSimple) {
  7648. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  7649. this.raise(errorPos, "Illegal 'use strict' directive in function with non-simple parameter list");
  7650. }
  7651. }
  7652. const oldLabels = this.state.labels;
  7653. this.state.labels = [];
  7654. if (useStrict) this.state.strict = true;
  7655. this.checkParams(node, !oldStrict && !useStrict && !allowExpression && !isMethod && !nonSimple, allowExpression);
  7656. node.body = this.parseBlock(true, false);
  7657. this.state.labels = oldLabels;
  7658. }
  7659. this.state.inParameters = oldInParameters;
  7660. if (this.state.strict && node.id) {
  7661. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name");
  7662. }
  7663. this.state.strict = oldStrict;
  7664. }
  7665. isSimpleParamList(params) {
  7666. for (let i = 0, len = params.length; i < len; i++) {
  7667. if (params[i].type !== "Identifier") return false;
  7668. }
  7669. return true;
  7670. }
  7671. checkParams(node, allowDuplicates, isArrowFunction) {
  7672. const nameHash = Object.create(null);
  7673. for (let i = 0; i < node.params.length; i++) {
  7674. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function paramter list");
  7675. }
  7676. }
  7677. parseExprList(close, allowEmpty, refShorthandDefaultPos) {
  7678. const elts = [];
  7679. let first = true;
  7680. while (!this.eat(close)) {
  7681. if (first) {
  7682. first = false;
  7683. } else {
  7684. this.expect(types.comma);
  7685. if (this.eat(close)) break;
  7686. }
  7687. elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos));
  7688. }
  7689. return elts;
  7690. }
  7691. parseExprListItem(allowEmpty, refShorthandDefaultPos, refNeedsArrowPos, allowPlaceholder) {
  7692. let elt;
  7693. if (allowEmpty && this.match(types.comma)) {
  7694. elt = null;
  7695. } else if (this.match(types.ellipsis)) {
  7696. const spreadNodeStartPos = this.state.start;
  7697. const spreadNodeStartLoc = this.state.startLoc;
  7698. elt = this.parseParenItem(this.parseSpread(refShorthandDefaultPos, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  7699. } else if (this.match(types.question)) {
  7700. this.expectPlugin("partialApplication");
  7701. if (!allowPlaceholder) {
  7702. this.raise(this.state.start, "Unexpected argument placeholder");
  7703. }
  7704. const node = this.startNode();
  7705. this.next();
  7706. elt = this.finishNode(node, "ArgumentPlaceholder");
  7707. } else {
  7708. elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos);
  7709. }
  7710. return elt;
  7711. }
  7712. parseIdentifier(liberal) {
  7713. const node = this.startNode();
  7714. const name = this.parseIdentifierName(node.start, liberal);
  7715. return this.createIdentifier(node, name);
  7716. }
  7717. createIdentifier(node, name) {
  7718. node.name = name;
  7719. node.loc.identifierName = name;
  7720. return this.finishNode(node, "Identifier");
  7721. }
  7722. parseIdentifierName(pos, liberal) {
  7723. let name;
  7724. if (this.match(types.name)) {
  7725. name = this.state.value;
  7726. } else if (this.state.type.keyword) {
  7727. name = this.state.type.keyword;
  7728. if ((name === "class" || name === "function") && (this.state.lastTokEnd !== this.state.lastTokStart + 1 || this.input.charCodeAt(this.state.lastTokStart) !== 46)) {
  7729. this.state.context.pop();
  7730. }
  7731. } else {
  7732. throw this.unexpected();
  7733. }
  7734. if (!liberal) {
  7735. this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false);
  7736. }
  7737. this.next();
  7738. return name;
  7739. }
  7740. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  7741. if (this.scope.inGenerator && word === "yield") {
  7742. this.raise(startLoc, "Can not use 'yield' as identifier inside a generator");
  7743. }
  7744. if (this.scope.inAsync && word === "await") {
  7745. this.raise(startLoc, "Can not use 'await' as identifier inside an async function");
  7746. }
  7747. if (this.state.inClassProperty && word === "arguments") {
  7748. this.raise(startLoc, "'arguments' is not allowed in class field initializer");
  7749. }
  7750. if (checkKeywords && isKeyword(word)) {
  7751. this.raise(startLoc, `Unexpected keyword '${word}'`);
  7752. }
  7753. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  7754. if (reservedTest(word, this.inModule)) {
  7755. if (!this.scope.inAsync && word === "await") {
  7756. this.raise(startLoc, "Can not use keyword 'await' outside an async function");
  7757. }
  7758. this.raise(startLoc, `Unexpected reserved word '${word}'`);
  7759. }
  7760. }
  7761. parseAwait() {
  7762. if (!this.state.awaitPos) {
  7763. this.state.awaitPos = this.state.start;
  7764. }
  7765. const node = this.startNode();
  7766. this.next();
  7767. if (this.state.inParameters) {
  7768. this.raise(node.start, "await is not allowed in async function parameters");
  7769. }
  7770. if (this.match(types.star)) {
  7771. this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead.");
  7772. }
  7773. node.argument = this.parseMaybeUnary();
  7774. return this.finishNode(node, "AwaitExpression");
  7775. }
  7776. parseYield(noIn) {
  7777. if (!this.state.yieldPos) {
  7778. this.state.yieldPos = this.state.start;
  7779. }
  7780. const node = this.startNode();
  7781. if (this.state.inParameters) {
  7782. this.raise(node.start, "yield is not allowed in generator parameters");
  7783. }
  7784. this.next();
  7785. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.canInsertSemicolon()) {
  7786. node.delegate = false;
  7787. node.argument = null;
  7788. } else {
  7789. node.delegate = this.eat(types.star);
  7790. node.argument = this.parseMaybeAssign(noIn);
  7791. }
  7792. return this.finishNode(node, "YieldExpression");
  7793. }
  7794. checkPipelineAtInfixOperator(left, leftStartPos) {
  7795. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  7796. if (left.type === "SequenceExpression") {
  7797. throw this.raise(leftStartPos, `Pipeline head should not be a comma-separated sequence expression`);
  7798. }
  7799. }
  7800. }
  7801. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  7802. const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
  7803. this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos);
  7804. return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc);
  7805. }
  7806. checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) {
  7807. if (this.match(types.arrow)) {
  7808. throw this.raise(this.state.start, `Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized`);
  7809. } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") {
  7810. throw this.raise(startPos, `Pipeline body may not be a comma-separated sequence expression`);
  7811. }
  7812. }
  7813. parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) {
  7814. const bodyNode = this.startNodeAt(startPos, startLoc);
  7815. switch (pipelineStyle) {
  7816. case "PipelineBareFunction":
  7817. bodyNode.callee = childExpression;
  7818. break;
  7819. case "PipelineBareConstructor":
  7820. bodyNode.callee = childExpression.callee;
  7821. break;
  7822. case "PipelineBareAwaitedFunction":
  7823. bodyNode.callee = childExpression.argument;
  7824. break;
  7825. case "PipelineTopicExpression":
  7826. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  7827. throw this.raise(startPos, `Pipeline is in topic style but does not use topic reference`);
  7828. }
  7829. bodyNode.expression = childExpression;
  7830. break;
  7831. default:
  7832. throw this.raise(startPos, `Unknown pipeline style ${pipelineStyle}`);
  7833. }
  7834. return this.finishNode(bodyNode, pipelineStyle);
  7835. }
  7836. checkSmartPipelineBodyStyle(expression) {
  7837. switch (expression.type) {
  7838. default:
  7839. return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression";
  7840. }
  7841. }
  7842. isSimpleReference(expression) {
  7843. switch (expression.type) {
  7844. case "MemberExpression":
  7845. return !expression.computed && this.isSimpleReference(expression.object);
  7846. case "Identifier":
  7847. return true;
  7848. default:
  7849. return false;
  7850. }
  7851. }
  7852. withTopicPermittingContext(callback) {
  7853. const outerContextTopicState = this.state.topicContext;
  7854. this.state.topicContext = {
  7855. maxNumOfResolvableTopics: 1,
  7856. maxTopicIndex: null
  7857. };
  7858. try {
  7859. return callback();
  7860. } finally {
  7861. this.state.topicContext = outerContextTopicState;
  7862. }
  7863. }
  7864. withTopicForbiddingContext(callback) {
  7865. const outerContextTopicState = this.state.topicContext;
  7866. this.state.topicContext = {
  7867. maxNumOfResolvableTopics: 0,
  7868. maxTopicIndex: null
  7869. };
  7870. try {
  7871. return callback();
  7872. } finally {
  7873. this.state.topicContext = outerContextTopicState;
  7874. }
  7875. }
  7876. registerTopicReference() {
  7877. this.state.topicContext.maxTopicIndex = 0;
  7878. }
  7879. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  7880. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  7881. }
  7882. topicReferenceWasUsedInCurrentTopicContext() {
  7883. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  7884. }
  7885. }
  7886. const empty = [];
  7887. const loopLabel = {
  7888. kind: "loop"
  7889. },
  7890. switchLabel = {
  7891. kind: "switch"
  7892. };
  7893. const FUNC_NO_FLAGS = 0b000,
  7894. FUNC_STATEMENT = 0b001,
  7895. FUNC_HANGING_STATEMENT = 0b010,
  7896. FUNC_NULLABLE_ID = 0b100;
  7897. class StatementParser extends ExpressionParser {
  7898. parseTopLevel(file, program) {
  7899. program.sourceType = this.options.sourceType;
  7900. program.interpreter = this.parseInterpreterDirective();
  7901. this.parseBlockBody(program, true, true, types.eof);
  7902. if (this.inModule && this.scope.undefinedExports.size > 0) {
  7903. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  7904. const [name] = _Array$from[_i];
  7905. const pos = this.scope.undefinedExports.get(name);
  7906. this.raise(pos, `Export '${name}' is not defined`);
  7907. }
  7908. }
  7909. file.program = this.finishNode(program, "Program");
  7910. file.comments = this.state.comments;
  7911. if (this.options.tokens) file.tokens = this.state.tokens;
  7912. return this.finishNode(file, "File");
  7913. }
  7914. stmtToDirective(stmt) {
  7915. const expr = stmt.expression;
  7916. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  7917. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  7918. const raw = this.input.slice(expr.start, expr.end);
  7919. const val = directiveLiteral.value = raw.slice(1, -1);
  7920. this.addExtra(directiveLiteral, "raw", raw);
  7921. this.addExtra(directiveLiteral, "rawValue", val);
  7922. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  7923. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  7924. }
  7925. parseInterpreterDirective() {
  7926. if (!this.match(types.interpreterDirective)) {
  7927. return null;
  7928. }
  7929. const node = this.startNode();
  7930. node.value = this.state.value;
  7931. this.next();
  7932. return this.finishNode(node, "InterpreterDirective");
  7933. }
  7934. isLet(context) {
  7935. if (!this.isContextual("let")) {
  7936. return false;
  7937. }
  7938. skipWhiteSpace.lastIndex = this.state.pos;
  7939. const skip = skipWhiteSpace.exec(this.input);
  7940. const next = this.state.pos + skip[0].length;
  7941. const nextCh = this.input.charCodeAt(next);
  7942. if (nextCh === 91) return true;
  7943. if (context) return false;
  7944. if (nextCh === 123) return true;
  7945. if (isIdentifierStart(nextCh)) {
  7946. let pos = next + 1;
  7947. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  7948. ++pos;
  7949. }
  7950. const ident = this.input.slice(next, pos);
  7951. if (!keywordRelationalOperator.test(ident)) return true;
  7952. }
  7953. return false;
  7954. }
  7955. parseStatement(context, topLevel) {
  7956. if (this.match(types.at)) {
  7957. this.parseDecorators(true);
  7958. }
  7959. return this.parseStatementContent(context, topLevel);
  7960. }
  7961. parseStatementContent(context, topLevel) {
  7962. let starttype = this.state.type;
  7963. const node = this.startNode();
  7964. let kind;
  7965. if (this.isLet(context)) {
  7966. starttype = types._var;
  7967. kind = "let";
  7968. }
  7969. switch (starttype) {
  7970. case types._break:
  7971. case types._continue:
  7972. return this.parseBreakContinueStatement(node, starttype.keyword);
  7973. case types._debugger:
  7974. return this.parseDebuggerStatement(node);
  7975. case types._do:
  7976. return this.parseDoStatement(node);
  7977. case types._for:
  7978. return this.parseForStatement(node);
  7979. case types._function:
  7980. if (this.lookahead().type === types.dot) break;
  7981. if (context) {
  7982. if (this.state.strict) {
  7983. this.raise(this.state.start, "In strict mode code, functions can only be declared at top level or inside a block");
  7984. } else if (context !== "if" && context !== "label") {
  7985. this.raise(this.state.start, "In non-strict mode code, functions can only be declared at top level, " + "inside a block, or as the body of an if statement");
  7986. }
  7987. }
  7988. return this.parseFunctionStatement(node, false, !context);
  7989. case types._class:
  7990. if (context) this.unexpected();
  7991. return this.parseClass(node, true);
  7992. case types._if:
  7993. return this.parseIfStatement(node);
  7994. case types._return:
  7995. return this.parseReturnStatement(node);
  7996. case types._switch:
  7997. return this.parseSwitchStatement(node);
  7998. case types._throw:
  7999. return this.parseThrowStatement(node);
  8000. case types._try:
  8001. return this.parseTryStatement(node);
  8002. case types._const:
  8003. case types._var:
  8004. kind = kind || this.state.value;
  8005. if (context && kind !== "var") {
  8006. this.unexpected(this.state.start, "Lexical declaration cannot appear in a single-statement context");
  8007. }
  8008. return this.parseVarStatement(node, kind);
  8009. case types._while:
  8010. return this.parseWhileStatement(node);
  8011. case types._with:
  8012. return this.parseWithStatement(node);
  8013. case types.braceL:
  8014. return this.parseBlock();
  8015. case types.semi:
  8016. return this.parseEmptyStatement(node);
  8017. case types._export:
  8018. case types._import:
  8019. {
  8020. const nextToken = this.lookahead();
  8021. if (nextToken.type === types.parenL || nextToken.type === types.dot) {
  8022. break;
  8023. }
  8024. if (!this.options.allowImportExportEverywhere && !topLevel) {
  8025. this.raise(this.state.start, "'import' and 'export' may only appear at the top level");
  8026. }
  8027. this.next();
  8028. let result;
  8029. if (starttype === types._import) {
  8030. result = this.parseImport(node);
  8031. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  8032. this.sawUnambiguousESM = true;
  8033. }
  8034. } else {
  8035. result = this.parseExport(node);
  8036. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  8037. this.sawUnambiguousESM = true;
  8038. }
  8039. }
  8040. this.assertModuleNodeAllowed(node);
  8041. return result;
  8042. }
  8043. default:
  8044. {
  8045. if (this.isAsyncFunction()) {
  8046. if (context) {
  8047. this.unexpected(null, "Async functions can only be declared at the top level or inside a block");
  8048. }
  8049. this.next();
  8050. return this.parseFunctionStatement(node, true, !context);
  8051. }
  8052. }
  8053. }
  8054. const maybeName = this.state.value;
  8055. const expr = this.parseExpression();
  8056. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  8057. return this.parseLabeledStatement(node, maybeName, expr, context);
  8058. } else {
  8059. return this.parseExpressionStatement(node, expr);
  8060. }
  8061. }
  8062. assertModuleNodeAllowed(node) {
  8063. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  8064. this.raise(node.start, `'import' and 'export' may appear only with 'sourceType: "module"'`, {
  8065. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8066. });
  8067. }
  8068. }
  8069. takeDecorators(node) {
  8070. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  8071. if (decorators.length) {
  8072. node.decorators = decorators;
  8073. this.resetStartLocationFromNode(node, decorators[0]);
  8074. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  8075. }
  8076. }
  8077. canHaveLeadingDecorator() {
  8078. return this.match(types._class);
  8079. }
  8080. parseDecorators(allowExport) {
  8081. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  8082. while (this.match(types.at)) {
  8083. const decorator = this.parseDecorator();
  8084. currentContextDecorators.push(decorator);
  8085. }
  8086. if (this.match(types._export)) {
  8087. if (!allowExport) {
  8088. this.unexpected();
  8089. }
  8090. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  8091. this.raise(this.state.start, "Using the export keyword between a decorator and a class is not allowed. " + "Please use `export @dec class` instead.");
  8092. }
  8093. } else if (!this.canHaveLeadingDecorator()) {
  8094. this.raise(this.state.start, "Leading decorators must be attached to a class declaration");
  8095. }
  8096. }
  8097. parseDecorator() {
  8098. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  8099. const node = this.startNode();
  8100. this.next();
  8101. if (this.hasPlugin("decorators")) {
  8102. this.state.decoratorStack.push([]);
  8103. const startPos = this.state.start;
  8104. const startLoc = this.state.startLoc;
  8105. let expr;
  8106. if (this.eat(types.parenL)) {
  8107. expr = this.parseExpression();
  8108. this.expect(types.parenR);
  8109. } else {
  8110. expr = this.parseIdentifier(false);
  8111. while (this.eat(types.dot)) {
  8112. const node = this.startNodeAt(startPos, startLoc);
  8113. node.object = expr;
  8114. node.property = this.parseIdentifier(true);
  8115. node.computed = false;
  8116. expr = this.finishNode(node, "MemberExpression");
  8117. }
  8118. }
  8119. node.expression = this.parseMaybeDecoratorArguments(expr);
  8120. this.state.decoratorStack.pop();
  8121. } else {
  8122. node.expression = this.parseMaybeAssign();
  8123. }
  8124. return this.finishNode(node, "Decorator");
  8125. }
  8126. parseMaybeDecoratorArguments(expr) {
  8127. if (this.eat(types.parenL)) {
  8128. const node = this.startNodeAtNode(expr);
  8129. node.callee = expr;
  8130. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8131. this.toReferencedList(node.arguments);
  8132. return this.finishNode(node, "CallExpression");
  8133. }
  8134. return expr;
  8135. }
  8136. parseBreakContinueStatement(node, keyword) {
  8137. const isBreak = keyword === "break";
  8138. this.next();
  8139. if (this.isLineTerminator()) {
  8140. node.label = null;
  8141. } else {
  8142. node.label = this.parseIdentifier();
  8143. this.semicolon();
  8144. }
  8145. this.verifyBreakContinue(node, keyword);
  8146. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  8147. }
  8148. verifyBreakContinue(node, keyword) {
  8149. const isBreak = keyword === "break";
  8150. let i;
  8151. for (i = 0; i < this.state.labels.length; ++i) {
  8152. const lab = this.state.labels[i];
  8153. if (node.label == null || lab.name === node.label.name) {
  8154. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  8155. if (node.label && isBreak) break;
  8156. }
  8157. }
  8158. if (i === this.state.labels.length) {
  8159. this.raise(node.start, "Unsyntactic " + keyword);
  8160. }
  8161. }
  8162. parseDebuggerStatement(node) {
  8163. this.next();
  8164. this.semicolon();
  8165. return this.finishNode(node, "DebuggerStatement");
  8166. }
  8167. parseHeaderExpression() {
  8168. this.expect(types.parenL);
  8169. const val = this.parseExpression();
  8170. this.expect(types.parenR);
  8171. return val;
  8172. }
  8173. parseDoStatement(node) {
  8174. this.next();
  8175. this.state.labels.push(loopLabel);
  8176. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  8177. this.state.labels.pop();
  8178. this.expect(types._while);
  8179. node.test = this.parseHeaderExpression();
  8180. this.eat(types.semi);
  8181. return this.finishNode(node, "DoWhileStatement");
  8182. }
  8183. parseForStatement(node) {
  8184. this.next();
  8185. this.state.labels.push(loopLabel);
  8186. let awaitAt = -1;
  8187. if ((this.scope.inAsync || !this.scope.inFunction && this.options.allowAwaitOutsideFunction) && this.eatContextual("await")) {
  8188. awaitAt = this.state.lastTokStart;
  8189. }
  8190. this.scope.enter(SCOPE_OTHER);
  8191. this.expect(types.parenL);
  8192. if (this.match(types.semi)) {
  8193. if (awaitAt > -1) {
  8194. this.unexpected(awaitAt);
  8195. }
  8196. return this.parseFor(node, null);
  8197. }
  8198. const isLet = this.isLet();
  8199. if (this.match(types._var) || this.match(types._const) || isLet) {
  8200. const init = this.startNode();
  8201. const kind = isLet ? "let" : this.state.value;
  8202. this.next();
  8203. this.parseVar(init, true, kind);
  8204. this.finishNode(init, "VariableDeclaration");
  8205. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  8206. return this.parseForIn(node, init, awaitAt);
  8207. }
  8208. if (awaitAt > -1) {
  8209. this.unexpected(awaitAt);
  8210. }
  8211. return this.parseFor(node, init);
  8212. }
  8213. const refShorthandDefaultPos = {
  8214. start: 0
  8215. };
  8216. const init = this.parseExpression(true, refShorthandDefaultPos);
  8217. if (this.match(types._in) || this.isContextual("of")) {
  8218. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  8219. this.toAssignable(init, undefined, description);
  8220. this.checkLVal(init, undefined, undefined, description);
  8221. return this.parseForIn(node, init, awaitAt);
  8222. } else if (refShorthandDefaultPos.start) {
  8223. this.unexpected(refShorthandDefaultPos.start);
  8224. }
  8225. if (awaitAt > -1) {
  8226. this.unexpected(awaitAt);
  8227. }
  8228. return this.parseFor(node, init);
  8229. }
  8230. parseFunctionStatement(node, isAsync, declarationPosition) {
  8231. this.next();
  8232. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  8233. }
  8234. parseIfStatement(node) {
  8235. this.next();
  8236. node.test = this.parseHeaderExpression();
  8237. node.consequent = this.parseStatement("if");
  8238. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  8239. return this.finishNode(node, "IfStatement");
  8240. }
  8241. parseReturnStatement(node) {
  8242. if (!this.scope.inFunction && !this.options.allowReturnOutsideFunction) {
  8243. this.raise(this.state.start, "'return' outside of function");
  8244. }
  8245. this.next();
  8246. if (this.isLineTerminator()) {
  8247. node.argument = null;
  8248. } else {
  8249. node.argument = this.parseExpression();
  8250. this.semicolon();
  8251. }
  8252. return this.finishNode(node, "ReturnStatement");
  8253. }
  8254. parseSwitchStatement(node) {
  8255. this.next();
  8256. node.discriminant = this.parseHeaderExpression();
  8257. const cases = node.cases = [];
  8258. this.expect(types.braceL);
  8259. this.state.labels.push(switchLabel);
  8260. this.scope.enter(SCOPE_OTHER);
  8261. let cur;
  8262. for (let sawDefault; !this.match(types.braceR);) {
  8263. if (this.match(types._case) || this.match(types._default)) {
  8264. const isCase = this.match(types._case);
  8265. if (cur) this.finishNode(cur, "SwitchCase");
  8266. cases.push(cur = this.startNode());
  8267. cur.consequent = [];
  8268. this.next();
  8269. if (isCase) {
  8270. cur.test = this.parseExpression();
  8271. } else {
  8272. if (sawDefault) {
  8273. this.raise(this.state.lastTokStart, "Multiple default clauses");
  8274. }
  8275. sawDefault = true;
  8276. cur.test = null;
  8277. }
  8278. this.expect(types.colon);
  8279. } else {
  8280. if (cur) {
  8281. cur.consequent.push(this.parseStatement(null));
  8282. } else {
  8283. this.unexpected();
  8284. }
  8285. }
  8286. }
  8287. this.scope.exit();
  8288. if (cur) this.finishNode(cur, "SwitchCase");
  8289. this.next();
  8290. this.state.labels.pop();
  8291. return this.finishNode(node, "SwitchStatement");
  8292. }
  8293. parseThrowStatement(node) {
  8294. this.next();
  8295. if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) {
  8296. this.raise(this.state.lastTokEnd, "Illegal newline after throw");
  8297. }
  8298. node.argument = this.parseExpression();
  8299. this.semicolon();
  8300. return this.finishNode(node, "ThrowStatement");
  8301. }
  8302. parseTryStatement(node) {
  8303. this.next();
  8304. node.block = this.parseBlock();
  8305. node.handler = null;
  8306. if (this.match(types._catch)) {
  8307. const clause = this.startNode();
  8308. this.next();
  8309. if (this.match(types.parenL)) {
  8310. this.expect(types.parenL);
  8311. clause.param = this.parseBindingAtom();
  8312. const simple = clause.param.type === "Identifier";
  8313. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  8314. this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause");
  8315. this.expect(types.parenR);
  8316. } else {
  8317. clause.param = null;
  8318. this.scope.enter(SCOPE_OTHER);
  8319. }
  8320. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  8321. this.scope.exit();
  8322. node.handler = this.finishNode(clause, "CatchClause");
  8323. }
  8324. node.guardedHandlers = empty;
  8325. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  8326. if (!node.handler && !node.finalizer) {
  8327. this.raise(node.start, "Missing catch or finally clause");
  8328. }
  8329. return this.finishNode(node, "TryStatement");
  8330. }
  8331. parseVarStatement(node, kind) {
  8332. this.next();
  8333. this.parseVar(node, false, kind);
  8334. this.semicolon();
  8335. return this.finishNode(node, "VariableDeclaration");
  8336. }
  8337. parseWhileStatement(node) {
  8338. this.next();
  8339. node.test = this.parseHeaderExpression();
  8340. this.state.labels.push(loopLabel);
  8341. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  8342. this.state.labels.pop();
  8343. return this.finishNode(node, "WhileStatement");
  8344. }
  8345. parseWithStatement(node) {
  8346. if (this.state.strict) {
  8347. this.raise(this.state.start, "'with' in strict mode");
  8348. }
  8349. this.next();
  8350. node.object = this.parseHeaderExpression();
  8351. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  8352. return this.finishNode(node, "WithStatement");
  8353. }
  8354. parseEmptyStatement(node) {
  8355. this.next();
  8356. return this.finishNode(node, "EmptyStatement");
  8357. }
  8358. parseLabeledStatement(node, maybeName, expr, context) {
  8359. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  8360. const label = _this$state$labels[_i2];
  8361. if (label.name === maybeName) {
  8362. this.raise(expr.start, `Label '${maybeName}' is already declared`);
  8363. }
  8364. }
  8365. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  8366. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  8367. const label = this.state.labels[i];
  8368. if (label.statementStart === node.start) {
  8369. label.statementStart = this.state.start;
  8370. label.kind = kind;
  8371. } else {
  8372. break;
  8373. }
  8374. }
  8375. this.state.labels.push({
  8376. name: maybeName,
  8377. kind: kind,
  8378. statementStart: this.state.start
  8379. });
  8380. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  8381. this.state.labels.pop();
  8382. node.label = expr;
  8383. return this.finishNode(node, "LabeledStatement");
  8384. }
  8385. parseExpressionStatement(node, expr) {
  8386. node.expression = expr;
  8387. this.semicolon();
  8388. return this.finishNode(node, "ExpressionStatement");
  8389. }
  8390. parseBlock(allowDirectives = false, createNewLexicalScope = true) {
  8391. const node = this.startNode();
  8392. this.expect(types.braceL);
  8393. if (createNewLexicalScope) {
  8394. this.scope.enter(SCOPE_OTHER);
  8395. }
  8396. this.parseBlockBody(node, allowDirectives, false, types.braceR);
  8397. if (createNewLexicalScope) {
  8398. this.scope.exit();
  8399. }
  8400. return this.finishNode(node, "BlockStatement");
  8401. }
  8402. isValidDirective(stmt) {
  8403. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  8404. }
  8405. parseBlockBody(node, allowDirectives, topLevel, end) {
  8406. const body = node.body = [];
  8407. const directives = node.directives = [];
  8408. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end);
  8409. }
  8410. parseBlockOrModuleBlockBody(body, directives, topLevel, end) {
  8411. let parsedNonDirective = false;
  8412. let oldStrict;
  8413. let octalPosition;
  8414. while (!this.eat(end)) {
  8415. if (!parsedNonDirective && this.state.containsOctal && !octalPosition) {
  8416. octalPosition = this.state.octalPosition;
  8417. }
  8418. const stmt = this.parseStatement(null, topLevel);
  8419. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  8420. const directive = this.stmtToDirective(stmt);
  8421. directives.push(directive);
  8422. if (oldStrict === undefined && directive.value.value === "use strict") {
  8423. oldStrict = this.state.strict;
  8424. this.setStrict(true);
  8425. if (octalPosition) {
  8426. this.raise(octalPosition, "Octal literal in strict mode");
  8427. }
  8428. }
  8429. continue;
  8430. }
  8431. parsedNonDirective = true;
  8432. body.push(stmt);
  8433. }
  8434. if (oldStrict === false) {
  8435. this.setStrict(false);
  8436. }
  8437. }
  8438. parseFor(node, init) {
  8439. node.init = init;
  8440. this.expect(types.semi);
  8441. node.test = this.match(types.semi) ? null : this.parseExpression();
  8442. this.expect(types.semi);
  8443. node.update = this.match(types.parenR) ? null : this.parseExpression();
  8444. this.expect(types.parenR);
  8445. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  8446. this.scope.exit();
  8447. this.state.labels.pop();
  8448. return this.finishNode(node, "ForStatement");
  8449. }
  8450. parseForIn(node, init, awaitAt) {
  8451. const isForIn = this.match(types._in);
  8452. this.next();
  8453. if (isForIn) {
  8454. if (awaitAt > -1) this.unexpected(awaitAt);
  8455. } else {
  8456. node.await = awaitAt > -1;
  8457. }
  8458. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  8459. this.raise(init.start, `${isForIn ? "for-in" : "for-of"} loop variable declaration may not have an initializer`);
  8460. } else if (init.type === "AssignmentPattern") {
  8461. this.raise(init.start, "Invalid left-hand side in for-loop");
  8462. }
  8463. node.left = init;
  8464. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  8465. this.expect(types.parenR);
  8466. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  8467. this.scope.exit();
  8468. this.state.labels.pop();
  8469. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  8470. }
  8471. parseVar(node, isFor, kind) {
  8472. const declarations = node.declarations = [];
  8473. const isTypescript = this.hasPlugin("typescript");
  8474. node.kind = kind;
  8475. for (;;) {
  8476. const decl = this.startNode();
  8477. this.parseVarId(decl, kind);
  8478. if (this.eat(types.eq)) {
  8479. decl.init = this.parseMaybeAssign(isFor);
  8480. } else {
  8481. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  8482. if (!isTypescript) {
  8483. this.unexpected();
  8484. }
  8485. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  8486. this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value");
  8487. }
  8488. decl.init = null;
  8489. }
  8490. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  8491. if (!this.eat(types.comma)) break;
  8492. }
  8493. return node;
  8494. }
  8495. parseVarId(decl, kind) {
  8496. if ((kind === "const" || kind === "let") && this.isContextual("let")) {
  8497. this.unexpected(null, "let is disallowed as a lexically bound name");
  8498. }
  8499. decl.id = this.parseBindingAtom();
  8500. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration");
  8501. }
  8502. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  8503. const isStatement = statement & FUNC_STATEMENT;
  8504. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  8505. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  8506. this.initFunction(node, isAsync);
  8507. if (this.match(types.star) && isHangingStatement) {
  8508. this.unexpected(this.state.start, "Generators can only be declared at the top level or inside a block");
  8509. }
  8510. node.generator = this.eat(types.star);
  8511. if (isStatement) {
  8512. node.id = this.parseFunctionId(requireId);
  8513. }
  8514. const oldInClassProperty = this.state.inClassProperty;
  8515. const oldYieldPos = this.state.yieldPos;
  8516. const oldAwaitPos = this.state.awaitPos;
  8517. this.state.inClassProperty = false;
  8518. this.state.yieldPos = 0;
  8519. this.state.awaitPos = 0;
  8520. this.scope.enter(functionFlags(node.async, node.generator));
  8521. if (!isStatement) {
  8522. node.id = this.parseFunctionId();
  8523. }
  8524. this.parseFunctionParams(node);
  8525. this.withTopicForbiddingContext(() => {
  8526. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  8527. });
  8528. this.scope.exit();
  8529. if (isStatement && !isHangingStatement) {
  8530. this.checkFunctionStatementId(node);
  8531. }
  8532. this.state.inClassProperty = oldInClassProperty;
  8533. this.state.yieldPos = oldYieldPos;
  8534. this.state.awaitPos = oldAwaitPos;
  8535. return node;
  8536. }
  8537. parseFunctionId(requireId) {
  8538. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  8539. }
  8540. parseFunctionParams(node, allowModifiers) {
  8541. const oldInParameters = this.state.inParameters;
  8542. this.state.inParameters = true;
  8543. this.expect(types.parenL);
  8544. node.params = this.parseBindingList(types.parenR, false, allowModifiers);
  8545. this.state.inParameters = oldInParameters;
  8546. this.checkYieldAwaitInDefaultParams();
  8547. }
  8548. checkFunctionStatementId(node) {
  8549. if (!node.id) return;
  8550. this.checkLVal(node.id, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, null, "function name");
  8551. }
  8552. parseClass(node, isStatement, optionalId) {
  8553. this.next();
  8554. this.takeDecorators(node);
  8555. const oldStrict = this.state.strict;
  8556. this.state.strict = true;
  8557. this.parseClassId(node, isStatement, optionalId);
  8558. this.parseClassSuper(node);
  8559. node.body = this.parseClassBody(!!node.superClass);
  8560. this.state.strict = oldStrict;
  8561. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  8562. }
  8563. isClassProperty() {
  8564. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  8565. }
  8566. isClassMethod() {
  8567. return this.match(types.parenL);
  8568. }
  8569. isNonstaticConstructor(method) {
  8570. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  8571. }
  8572. parseClassBody(constructorAllowsSuper) {
  8573. this.state.classLevel++;
  8574. const state = {
  8575. hadConstructor: false
  8576. };
  8577. let decorators = [];
  8578. const classBody = this.startNode();
  8579. classBody.body = [];
  8580. this.expect(types.braceL);
  8581. this.withTopicForbiddingContext(() => {
  8582. while (!this.eat(types.braceR)) {
  8583. if (this.eat(types.semi)) {
  8584. if (decorators.length > 0) {
  8585. this.raise(this.state.lastTokEnd, "Decorators must not be followed by a semicolon");
  8586. }
  8587. continue;
  8588. }
  8589. if (this.match(types.at)) {
  8590. decorators.push(this.parseDecorator());
  8591. continue;
  8592. }
  8593. const member = this.startNode();
  8594. if (decorators.length) {
  8595. member.decorators = decorators;
  8596. this.resetStartLocationFromNode(member, decorators[0]);
  8597. decorators = [];
  8598. }
  8599. this.parseClassMember(classBody, member, state, constructorAllowsSuper);
  8600. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  8601. this.raise(member.start, "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?");
  8602. }
  8603. }
  8604. });
  8605. if (decorators.length) {
  8606. this.raise(this.state.start, "You have trailing decorators with no method");
  8607. }
  8608. this.state.classLevel--;
  8609. return this.finishNode(classBody, "ClassBody");
  8610. }
  8611. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  8612. let isStatic = false;
  8613. const containsEsc = this.state.containsEsc;
  8614. if (this.match(types.name) && this.state.value === "static") {
  8615. const key = this.parseIdentifier(true);
  8616. if (this.isClassMethod()) {
  8617. const method = member;
  8618. method.kind = "method";
  8619. method.computed = false;
  8620. method.key = key;
  8621. method.static = false;
  8622. this.pushClassMethod(classBody, method, false, false, false, false);
  8623. return;
  8624. } else if (this.isClassProperty()) {
  8625. const prop = member;
  8626. prop.computed = false;
  8627. prop.key = key;
  8628. prop.static = false;
  8629. classBody.body.push(this.parseClassProperty(prop));
  8630. return;
  8631. } else if (containsEsc) {
  8632. throw this.unexpected();
  8633. }
  8634. isStatic = true;
  8635. }
  8636. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  8637. }
  8638. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  8639. const publicMethod = member;
  8640. const privateMethod = member;
  8641. const publicProp = member;
  8642. const privateProp = member;
  8643. const method = publicMethod;
  8644. const publicMember = publicMethod;
  8645. member.static = isStatic;
  8646. if (this.eat(types.star)) {
  8647. method.kind = "method";
  8648. this.parseClassPropertyName(method);
  8649. if (method.key.type === "PrivateName") {
  8650. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  8651. return;
  8652. }
  8653. if (this.isNonstaticConstructor(publicMethod)) {
  8654. this.raise(publicMethod.key.start, "Constructor can't be a generator");
  8655. }
  8656. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  8657. return;
  8658. }
  8659. const containsEsc = this.state.containsEsc;
  8660. const key = this.parseClassPropertyName(member);
  8661. const isPrivate = key.type === "PrivateName";
  8662. const isSimple = key.type === "Identifier";
  8663. this.parsePostMemberNameModifiers(publicMember);
  8664. if (this.isClassMethod()) {
  8665. method.kind = "method";
  8666. if (isPrivate) {
  8667. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  8668. return;
  8669. }
  8670. const isConstructor = this.isNonstaticConstructor(publicMethod);
  8671. let allowsDirectSuper = false;
  8672. if (isConstructor) {
  8673. publicMethod.kind = "constructor";
  8674. if (publicMethod.decorators) {
  8675. this.raise(publicMethod.start, "You can't attach decorators to a class constructor");
  8676. }
  8677. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  8678. this.raise(key.start, "Duplicate constructor in the same class");
  8679. }
  8680. state.hadConstructor = true;
  8681. allowsDirectSuper = constructorAllowsSuper;
  8682. }
  8683. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  8684. } else if (this.isClassProperty()) {
  8685. if (isPrivate) {
  8686. this.pushClassPrivateProperty(classBody, privateProp);
  8687. } else {
  8688. this.pushClassProperty(classBody, publicProp);
  8689. }
  8690. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  8691. const isGenerator = this.eat(types.star);
  8692. method.kind = "method";
  8693. this.parseClassPropertyName(method);
  8694. if (method.key.type === "PrivateName") {
  8695. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  8696. } else {
  8697. if (this.isNonstaticConstructor(publicMethod)) {
  8698. this.raise(publicMethod.key.start, "Constructor can't be an async function");
  8699. }
  8700. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  8701. }
  8702. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  8703. method.kind = key.name;
  8704. this.parseClassPropertyName(publicMethod);
  8705. if (method.key.type === "PrivateName") {
  8706. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  8707. } else {
  8708. if (this.isNonstaticConstructor(publicMethod)) {
  8709. this.raise(publicMethod.key.start, "Constructor can't have get/set modifier");
  8710. }
  8711. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  8712. }
  8713. this.checkGetterSetterParams(publicMethod);
  8714. } else if (this.isLineTerminator()) {
  8715. if (isPrivate) {
  8716. this.pushClassPrivateProperty(classBody, privateProp);
  8717. } else {
  8718. this.pushClassProperty(classBody, publicProp);
  8719. }
  8720. } else {
  8721. this.unexpected();
  8722. }
  8723. }
  8724. parseClassPropertyName(member) {
  8725. const key = this.parsePropertyName(member);
  8726. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  8727. this.raise(key.start, "Classes may not have static property named prototype");
  8728. }
  8729. if (key.type === "PrivateName" && key.id.name === "constructor") {
  8730. this.raise(key.start, "Classes may not have a private field named '#constructor'");
  8731. }
  8732. return key;
  8733. }
  8734. pushClassProperty(classBody, prop) {
  8735. if (this.isNonstaticConstructor(prop)) {
  8736. this.raise(prop.key.start, "Classes may not have a non-static field named 'constructor'");
  8737. }
  8738. classBody.body.push(this.parseClassProperty(prop));
  8739. }
  8740. pushClassPrivateProperty(classBody, prop) {
  8741. this.expectPlugin("classPrivateProperties", prop.key.start);
  8742. classBody.body.push(this.parseClassPrivateProperty(prop));
  8743. }
  8744. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  8745. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  8746. }
  8747. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  8748. this.expectPlugin("classPrivateMethods", method.key.start);
  8749. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true));
  8750. }
  8751. parsePostMemberNameModifiers(methodOrProp) {}
  8752. parseAccessModifier() {
  8753. return undefined;
  8754. }
  8755. parseClassPrivateProperty(node) {
  8756. this.state.inClassProperty = true;
  8757. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  8758. node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null;
  8759. this.semicolon();
  8760. this.state.inClassProperty = false;
  8761. this.scope.exit();
  8762. return this.finishNode(node, "ClassPrivateProperty");
  8763. }
  8764. parseClassProperty(node) {
  8765. if (!node.typeAnnotation) {
  8766. this.expectPlugin("classProperties");
  8767. }
  8768. this.state.inClassProperty = true;
  8769. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  8770. if (this.match(types.eq)) {
  8771. this.expectPlugin("classProperties");
  8772. this.next();
  8773. node.value = this.parseMaybeAssign();
  8774. } else {
  8775. node.value = null;
  8776. }
  8777. this.semicolon();
  8778. this.state.inClassProperty = false;
  8779. this.scope.exit();
  8780. return this.finishNode(node, "ClassProperty");
  8781. }
  8782. parseClassId(node, isStatement, optionalId) {
  8783. if (this.match(types.name)) {
  8784. node.id = this.parseIdentifier();
  8785. if (isStatement) {
  8786. this.checkLVal(node.id, BIND_CLASS, undefined, "class name");
  8787. }
  8788. } else {
  8789. if (optionalId || !isStatement) {
  8790. node.id = null;
  8791. } else {
  8792. this.unexpected(null, "A class name is required");
  8793. }
  8794. }
  8795. }
  8796. parseClassSuper(node) {
  8797. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  8798. }
  8799. parseExport(node) {
  8800. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  8801. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  8802. const hasStar = parseAfterDefault && this.eatExportStar(node);
  8803. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  8804. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  8805. const isFromRequired = hasDefault || hasStar;
  8806. if (hasStar && !hasNamespace) {
  8807. if (hasDefault) this.unexpected();
  8808. this.parseExportFrom(node, true);
  8809. return this.finishNode(node, "ExportAllDeclaration");
  8810. }
  8811. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  8812. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  8813. throw this.unexpected(null, types.braceL);
  8814. }
  8815. let hasDeclaration;
  8816. if (isFromRequired || hasSpecifiers) {
  8817. hasDeclaration = false;
  8818. this.parseExportFrom(node, isFromRequired);
  8819. } else {
  8820. hasDeclaration = this.maybeParseExportDeclaration(node);
  8821. }
  8822. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  8823. this.checkExport(node, true, false, !!node.source);
  8824. return this.finishNode(node, "ExportNamedDeclaration");
  8825. }
  8826. if (this.eat(types._default)) {
  8827. node.declaration = this.parseExportDefaultExpression();
  8828. this.checkExport(node, true, true);
  8829. return this.finishNode(node, "ExportDefaultDeclaration");
  8830. }
  8831. throw this.unexpected(null, types.braceL);
  8832. }
  8833. eatExportStar(node) {
  8834. return this.eat(types.star);
  8835. }
  8836. maybeParseExportDefaultSpecifier(node) {
  8837. if (this.isExportDefaultSpecifier()) {
  8838. this.expectPlugin("exportDefaultFrom");
  8839. const specifier = this.startNode();
  8840. specifier.exported = this.parseIdentifier(true);
  8841. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  8842. return true;
  8843. }
  8844. return false;
  8845. }
  8846. maybeParseExportNamespaceSpecifier(node) {
  8847. if (this.isContextual("as")) {
  8848. if (!node.specifiers) node.specifiers = [];
  8849. this.expectPlugin("exportNamespaceFrom");
  8850. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  8851. this.next();
  8852. specifier.exported = this.parseIdentifier(true);
  8853. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  8854. return true;
  8855. }
  8856. return false;
  8857. }
  8858. maybeParseExportNamedSpecifiers(node) {
  8859. if (this.match(types.braceL)) {
  8860. if (!node.specifiers) node.specifiers = [];
  8861. node.specifiers.push(...this.parseExportSpecifiers());
  8862. node.source = null;
  8863. node.declaration = null;
  8864. return true;
  8865. }
  8866. return false;
  8867. }
  8868. maybeParseExportDeclaration(node) {
  8869. if (this.shouldParseExportDeclaration()) {
  8870. if (this.isContextual("async")) {
  8871. const next = this.lookahead();
  8872. if (next.type !== types._function) {
  8873. this.unexpected(next.start, `Unexpected token, expected "function"`);
  8874. }
  8875. }
  8876. node.specifiers = [];
  8877. node.source = null;
  8878. node.declaration = this.parseExportDeclaration(node);
  8879. return true;
  8880. }
  8881. return false;
  8882. }
  8883. isAsyncFunction() {
  8884. if (!this.isContextual("async")) return false;
  8885. const {
  8886. pos
  8887. } = this.state;
  8888. skipWhiteSpace.lastIndex = pos;
  8889. const skip = skipWhiteSpace.exec(this.input);
  8890. if (!skip || !skip.length) return false;
  8891. const next = pos + skip[0].length;
  8892. return !lineBreak.test(this.input.slice(pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.length || !isIdentifierChar(this.input.charCodeAt(next + 8)));
  8893. }
  8894. parseExportDefaultExpression() {
  8895. const expr = this.startNode();
  8896. const isAsync = this.isAsyncFunction();
  8897. if (this.match(types._function) || isAsync) {
  8898. this.next();
  8899. if (isAsync) {
  8900. this.next();
  8901. }
  8902. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  8903. } else if (this.match(types._class)) {
  8904. return this.parseClass(expr, true, true);
  8905. } else if (this.match(types.at)) {
  8906. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  8907. this.unexpected(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax");
  8908. }
  8909. this.parseDecorators(false);
  8910. return this.parseClass(expr, true, true);
  8911. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  8912. return this.raise(this.state.start, "Only expressions, functions or classes are allowed as the `default` export.");
  8913. } else {
  8914. const res = this.parseMaybeAssign();
  8915. this.semicolon();
  8916. return res;
  8917. }
  8918. }
  8919. parseExportDeclaration(node) {
  8920. return this.parseStatement(null);
  8921. }
  8922. isExportDefaultSpecifier() {
  8923. if (this.match(types.name)) {
  8924. return this.state.value !== "async" && this.state.value !== "let";
  8925. }
  8926. if (!this.match(types._default)) {
  8927. return false;
  8928. }
  8929. const lookahead = this.lookahead();
  8930. return lookahead.type === types.comma || lookahead.type === types.name && lookahead.value === "from";
  8931. }
  8932. parseExportFrom(node, expect) {
  8933. if (this.eatContextual("from")) {
  8934. node.source = this.parseImportSource();
  8935. this.checkExport(node);
  8936. } else {
  8937. if (expect) {
  8938. this.unexpected();
  8939. } else {
  8940. node.source = null;
  8941. }
  8942. }
  8943. this.semicolon();
  8944. }
  8945. shouldParseExportDeclaration() {
  8946. if (this.match(types.at)) {
  8947. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  8948. if (this.hasPlugin("decorators")) {
  8949. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  8950. this.unexpected(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax");
  8951. } else {
  8952. return true;
  8953. }
  8954. }
  8955. }
  8956. 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();
  8957. }
  8958. checkExport(node, checkNames, isDefault, isFrom) {
  8959. if (checkNames) {
  8960. if (isDefault) {
  8961. this.checkDuplicateExports(node, "default");
  8962. } else if (node.specifiers && node.specifiers.length) {
  8963. for (let _i3 = 0, _node$specifiers = node.specifiers; _i3 < _node$specifiers.length; _i3++) {
  8964. const specifier = _node$specifiers[_i3];
  8965. this.checkDuplicateExports(specifier, specifier.exported.name);
  8966. if (!isFrom && specifier.local) {
  8967. this.checkReservedWord(specifier.local.name, specifier.local.start, true, false);
  8968. this.scope.checkLocalExport(specifier.local);
  8969. }
  8970. }
  8971. } else if (node.declaration) {
  8972. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  8973. const id = node.declaration.id;
  8974. if (!id) throw new Error("Assertion failure");
  8975. this.checkDuplicateExports(node, id.name);
  8976. } else if (node.declaration.type === "VariableDeclaration") {
  8977. for (let _i4 = 0, _node$declaration$dec = node.declaration.declarations; _i4 < _node$declaration$dec.length; _i4++) {
  8978. const declaration = _node$declaration$dec[_i4];
  8979. this.checkDeclaration(declaration.id);
  8980. }
  8981. }
  8982. }
  8983. }
  8984. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  8985. if (currentContextDecorators.length) {
  8986. const isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
  8987. if (!node.declaration || !isClass) {
  8988. throw this.raise(node.start, "You can only use decorators on an export when exporting a class");
  8989. }
  8990. this.takeDecorators(node.declaration);
  8991. }
  8992. }
  8993. checkDeclaration(node) {
  8994. if (node.type === "Identifier") {
  8995. this.checkDuplicateExports(node, node.name);
  8996. } else if (node.type === "ObjectPattern") {
  8997. for (let _i5 = 0, _node$properties = node.properties; _i5 < _node$properties.length; _i5++) {
  8998. const prop = _node$properties[_i5];
  8999. this.checkDeclaration(prop);
  9000. }
  9001. } else if (node.type === "ArrayPattern") {
  9002. for (let _i6 = 0, _node$elements = node.elements; _i6 < _node$elements.length; _i6++) {
  9003. const elem = _node$elements[_i6];
  9004. if (elem) {
  9005. this.checkDeclaration(elem);
  9006. }
  9007. }
  9008. } else if (node.type === "ObjectProperty") {
  9009. this.checkDeclaration(node.value);
  9010. } else if (node.type === "RestElement") {
  9011. this.checkDeclaration(node.argument);
  9012. } else if (node.type === "AssignmentPattern") {
  9013. this.checkDeclaration(node.left);
  9014. }
  9015. }
  9016. checkDuplicateExports(node, name) {
  9017. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  9018. throw this.raise(node.start, name === "default" ? "Only one default export allowed per module." : `\`${name}\` has already been exported. Exported identifiers must be unique.`);
  9019. }
  9020. this.state.exportedIdentifiers.push(name);
  9021. }
  9022. parseExportSpecifiers() {
  9023. const nodes = [];
  9024. let first = true;
  9025. this.expect(types.braceL);
  9026. while (!this.eat(types.braceR)) {
  9027. if (first) {
  9028. first = false;
  9029. } else {
  9030. this.expect(types.comma);
  9031. if (this.eat(types.braceR)) break;
  9032. }
  9033. const node = this.startNode();
  9034. node.local = this.parseIdentifier(true);
  9035. node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
  9036. nodes.push(this.finishNode(node, "ExportSpecifier"));
  9037. }
  9038. return nodes;
  9039. }
  9040. parseImport(node) {
  9041. node.specifiers = [];
  9042. if (!this.match(types.string)) {
  9043. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  9044. const parseNext = !hasDefault || this.eat(types.comma);
  9045. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  9046. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  9047. this.expectContextual("from");
  9048. }
  9049. node.source = this.parseImportSource();
  9050. this.semicolon();
  9051. return this.finishNode(node, "ImportDeclaration");
  9052. }
  9053. parseImportSource() {
  9054. if (!this.match(types.string)) this.unexpected();
  9055. return this.parseExprAtom();
  9056. }
  9057. shouldParseDefaultImport(node) {
  9058. return this.match(types.name);
  9059. }
  9060. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  9061. specifier.local = this.parseIdentifier();
  9062. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  9063. node.specifiers.push(this.finishNode(specifier, type));
  9064. }
  9065. maybeParseDefaultImportSpecifier(node) {
  9066. if (this.shouldParseDefaultImport(node)) {
  9067. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  9068. return true;
  9069. }
  9070. return false;
  9071. }
  9072. maybeParseStarImportSpecifier(node) {
  9073. if (this.match(types.star)) {
  9074. const specifier = this.startNode();
  9075. this.next();
  9076. this.expectContextual("as");
  9077. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  9078. return true;
  9079. }
  9080. return false;
  9081. }
  9082. parseNamedImportSpecifiers(node) {
  9083. let first = true;
  9084. this.expect(types.braceL);
  9085. while (!this.eat(types.braceR)) {
  9086. if (first) {
  9087. first = false;
  9088. } else {
  9089. if (this.eat(types.colon)) {
  9090. this.unexpected(null, "ES2015 named imports do not destructure. " + "Use another statement for destructuring after the import.");
  9091. }
  9092. this.expect(types.comma);
  9093. if (this.eat(types.braceR)) break;
  9094. }
  9095. this.parseImportSpecifier(node);
  9096. }
  9097. }
  9098. parseImportSpecifier(node) {
  9099. const specifier = this.startNode();
  9100. specifier.imported = this.parseIdentifier(true);
  9101. if (this.eatContextual("as")) {
  9102. specifier.local = this.parseIdentifier();
  9103. } else {
  9104. this.checkReservedWord(specifier.imported.name, specifier.start, true, true);
  9105. specifier.local = specifier.imported.__clone();
  9106. }
  9107. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  9108. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  9109. }
  9110. }
  9111. class Parser extends StatementParser {
  9112. constructor(options, input) {
  9113. options = getOptions(options);
  9114. super(options, input);
  9115. const ScopeHandler = this.getScopeHandler();
  9116. this.options = options;
  9117. this.inModule = this.options.sourceType === "module";
  9118. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  9119. this.plugins = pluginsMap(this.options.plugins);
  9120. this.filename = options.sourceFilename;
  9121. }
  9122. getScopeHandler() {
  9123. return ScopeHandler;
  9124. }
  9125. parse() {
  9126. this.scope.enter(SCOPE_PROGRAM);
  9127. const file = this.startNode();
  9128. const program = this.startNode();
  9129. this.nextToken();
  9130. return this.parseTopLevel(file, program);
  9131. }
  9132. }
  9133. function pluginsMap(plugins) {
  9134. const pluginMap = new Map();
  9135. for (let _i = 0; _i < plugins.length; _i++) {
  9136. const plugin = plugins[_i];
  9137. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  9138. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  9139. }
  9140. return pluginMap;
  9141. }
  9142. function parse(input, options) {
  9143. if (options && options.sourceType === "unambiguous") {
  9144. options = Object.assign({}, options);
  9145. try {
  9146. options.sourceType = "module";
  9147. const parser = getParser(options, input);
  9148. const ast = parser.parse();
  9149. if (!parser.sawUnambiguousESM) ast.program.sourceType = "script";
  9150. return ast;
  9151. } catch (moduleError) {
  9152. try {
  9153. options.sourceType = "script";
  9154. return getParser(options, input).parse();
  9155. } catch (scriptError) {}
  9156. throw moduleError;
  9157. }
  9158. } else {
  9159. return getParser(options, input).parse();
  9160. }
  9161. }
  9162. function parseExpression(input, options) {
  9163. const parser = getParser(options, input);
  9164. if (parser.options.strictMode) {
  9165. parser.state.strict = true;
  9166. }
  9167. return parser.getExpression();
  9168. }
  9169. function getParser(options, input) {
  9170. let cls = Parser;
  9171. if (options && options.plugins) {
  9172. validatePlugins(options.plugins);
  9173. cls = getParserClass(options.plugins);
  9174. }
  9175. return new cls(options, input);
  9176. }
  9177. const parserClassCache = {};
  9178. function getParserClass(pluginsFromOptions) {
  9179. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  9180. const key = pluginList.join("/");
  9181. let cls = parserClassCache[key];
  9182. if (!cls) {
  9183. cls = Parser;
  9184. for (let _i = 0; _i < pluginList.length; _i++) {
  9185. const plugin = pluginList[_i];
  9186. cls = mixinPlugins[plugin](cls);
  9187. }
  9188. parserClassCache[key] = cls;
  9189. }
  9190. return cls;
  9191. }
  9192. exports.parse = parse;
  9193. exports.parseExpression = parseExpression;
  9194. exports.tokTypes = types;