Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 474KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. function _objectWithoutPropertiesLoose(r, e) {
  6. if (null == r) return {};
  7. var t = {};
  8. for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
  9. if (e.includes(n)) continue;
  10. t[n] = r[n];
  11. }
  12. return t;
  13. }
  14. class Position {
  15. constructor(line, col, index) {
  16. this.line = void 0;
  17. this.column = void 0;
  18. this.index = void 0;
  19. this.line = line;
  20. this.column = col;
  21. this.index = index;
  22. }
  23. }
  24. class SourceLocation {
  25. constructor(start, end) {
  26. this.start = void 0;
  27. this.end = void 0;
  28. this.filename = void 0;
  29. this.identifierName = void 0;
  30. this.start = start;
  31. this.end = end;
  32. }
  33. }
  34. function createPositionWithColumnOffset(position, columnOffset) {
  35. const {
  36. line,
  37. column,
  38. index
  39. } = position;
  40. return new Position(line, column + columnOffset, index + columnOffset);
  41. }
  42. const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";
  43. var ModuleErrors = {
  44. ImportMetaOutsideModule: {
  45. message: `import.meta may appear only with 'sourceType: "module"'`,
  46. code
  47. },
  48. ImportOutsideModule: {
  49. message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  50. code
  51. }
  52. };
  53. const NodeDescriptions = {
  54. ArrayPattern: "array destructuring pattern",
  55. AssignmentExpression: "assignment expression",
  56. AssignmentPattern: "assignment expression",
  57. ArrowFunctionExpression: "arrow function expression",
  58. ConditionalExpression: "conditional expression",
  59. CatchClause: "catch clause",
  60. ForOfStatement: "for-of statement",
  61. ForInStatement: "for-in statement",
  62. ForStatement: "for-loop",
  63. FormalParameters: "function parameter list",
  64. Identifier: "identifier",
  65. ImportSpecifier: "import specifier",
  66. ImportDefaultSpecifier: "import default specifier",
  67. ImportNamespaceSpecifier: "import namespace specifier",
  68. ObjectPattern: "object destructuring pattern",
  69. ParenthesizedExpression: "parenthesized expression",
  70. RestElement: "rest element",
  71. UpdateExpression: {
  72. true: "prefix operation",
  73. false: "postfix operation"
  74. },
  75. VariableDeclarator: "variable declaration",
  76. YieldExpression: "yield expression"
  77. };
  78. const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type];
  79. var StandardErrors = {
  80. AccessorIsGenerator: ({
  81. kind
  82. }) => `A ${kind}ter cannot be a generator.`,
  83. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  84. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  85. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  86. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  87. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  88. AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.",
  89. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  90. AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  91. BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  92. BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  93. BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  94. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  95. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  96. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  97. ConstructorIsAsync: "Constructor can't be an async function.",
  98. ConstructorIsGenerator: "Constructor can't be a generator.",
  99. DeclarationMissingInitializer: ({
  100. kind
  101. }) => `Missing initializer in ${kind} declaration.`,
  102. DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  103. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
  104. DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
  105. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  106. DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
  107. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  108. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  109. DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.',
  110. DeletePrivateField: "Deleting a private field is not allowed.",
  111. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  112. DuplicateConstructor: "Duplicate constructor in the same class.",
  113. DuplicateDefaultExport: "Only one default export allowed per module.",
  114. DuplicateExport: ({
  115. exportName
  116. }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  117. DuplicateProto: "Redefinition of __proto__ property.",
  118. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  119. DynamicImportPhaseRequiresImportExpressions: ({
  120. phase
  121. }) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`,
  122. ElementAfterRest: "Rest element must be last element.",
  123. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  124. ExportBindingIsString: ({
  125. localName,
  126. exportName
  127. }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  128. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  129. ForInOfLoopInitializer: ({
  130. type
  131. }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  132. ForInUsing: "For-in loop may not start with 'using' declaration.",
  133. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  134. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  135. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  136. IllegalBreakContinue: ({
  137. type
  138. }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  139. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  140. IllegalReturn: "'return' outside of function.",
  141. ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedAssertSyntax: true` option in the import attributes plugin to suppress this error.",
  142. ImportBindingIsString: ({
  143. importName
  144. }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
  145. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.",
  146. ImportCallArity: ({
  147. maxArgumentCount
  148. }) => `\`import()\` requires exactly ${maxArgumentCount === 1 ? "one argument" : "one or two arguments"}.`,
  149. ImportCallNotNewExpression: "Cannot use new with import(...).",
  150. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  151. ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  152. ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  153. ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  154. IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  155. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  156. InvalidCodePoint: "Code point out of bounds.",
  157. InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  158. InvalidDecimal: "Invalid decimal.",
  159. InvalidDigit: ({
  160. radix
  161. }) => `Expected number in radix ${radix}.`,
  162. InvalidEscapeSequence: "Bad character escape sequence.",
  163. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  164. InvalidEscapedReservedWord: ({
  165. reservedWord
  166. }) => `Escape sequence in keyword ${reservedWord}.`,
  167. InvalidIdentifier: ({
  168. identifierName
  169. }) => `Invalid identifier ${identifierName}.`,
  170. InvalidLhs: ({
  171. ancestor
  172. }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  173. InvalidLhsBinding: ({
  174. ancestor
  175. }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  176. InvalidLhsOptionalChaining: ({
  177. ancestor
  178. }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,
  179. InvalidNumber: "Invalid number.",
  180. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  181. InvalidOrUnexpectedToken: ({
  182. unexpected
  183. }) => `Unexpected character '${unexpected}'.`,
  184. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  185. InvalidPrivateFieldResolution: ({
  186. identifierName
  187. }) => `Private name #${identifierName} is not defined.`,
  188. InvalidPropertyBindingPattern: "Binding member expression.",
  189. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  190. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  191. LabelRedeclaration: ({
  192. labelName
  193. }) => `Label '${labelName}' is already declared.`,
  194. LetInLexicalBinding: "'let' is disallowed as a lexically bound name.",
  195. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  196. MalformedRegExpFlags: "Invalid regular expression flag.",
  197. MissingClassName: "A class name is required.",
  198. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  199. MissingSemicolon: "Missing semicolon.",
  200. MissingPlugin: ({
  201. missingPlugin
  202. }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  203. MissingOneOfPlugins: ({
  204. missingPlugin
  205. }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  206. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  207. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  208. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  209. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  210. ModuleAttributesWithDuplicateKeys: ({
  211. key
  212. }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  213. ModuleExportNameHasLoneSurrogate: ({
  214. surrogateCharCode
  215. }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  216. ModuleExportUndefined: ({
  217. localName
  218. }) => `Export '${localName}' is not defined.`,
  219. MultipleDefaultsInSwitch: "Multiple default clauses.",
  220. NewlineAfterThrow: "Illegal newline after throw.",
  221. NoCatchOrFinally: "Missing catch or finally clause.",
  222. NumberIdentifier: "Identifier directly after number.",
  223. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  224. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  225. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  226. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  227. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  228. ParamDupe: "Argument name clash.",
  229. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  230. PatternHasMethod: "Object pattern can't contain methods.",
  231. PrivateInExpectedIn: ({
  232. identifierName
  233. }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  234. PrivateNameRedeclaration: ({
  235. identifierName
  236. }) => `Duplicate private name #${identifierName}.`,
  237. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  238. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  239. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  240. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  241. RestTrailingComma: "Unexpected trailing comma after rest element.",
  242. SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.",
  243. SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",
  244. SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.',
  245. StaticPrototype: "Classes may not have static property named prototype.",
  246. SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  247. SuperPrivateField: "Private fields can't be accessed on super.",
  248. TrailingDecorator: "Decorators must be attached to a class element.",
  249. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  250. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  251. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  252. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  253. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  254. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  255. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  256. UnexpectedKeyword: ({
  257. keyword
  258. }) => `Unexpected keyword '${keyword}'.`,
  259. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  260. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  261. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  262. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  263. UnexpectedPrivateField: "Unexpected private name.",
  264. UnexpectedReservedWord: ({
  265. reservedWord
  266. }) => `Unexpected reserved word '${reservedWord}'.`,
  267. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  268. UnexpectedToken: ({
  269. expected,
  270. unexpected
  271. }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  272. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  273. UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.",
  274. UnsupportedBind: "Binding should be performed on object property.",
  275. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  276. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  277. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  278. UnsupportedMetaProperty: ({
  279. target,
  280. onlyValidPropertyName
  281. }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  282. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  283. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  284. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  285. UnterminatedComment: "Unterminated comment.",
  286. UnterminatedRegExp: "Unterminated regular expression.",
  287. UnterminatedString: "Unterminated string constant.",
  288. UnterminatedTemplate: "Unterminated template.",
  289. UsingDeclarationExport: "Using declaration cannot be exported.",
  290. UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  291. VarRedeclaration: ({
  292. identifierName
  293. }) => `Identifier '${identifierName}' has already been declared.`,
  294. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  295. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  296. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  297. };
  298. var StrictModeErrors = {
  299. StrictDelete: "Deleting local variable in strict mode.",
  300. StrictEvalArguments: ({
  301. referenceName
  302. }) => `Assigning to '${referenceName}' in strict mode.`,
  303. StrictEvalArgumentsBinding: ({
  304. bindingName
  305. }) => `Binding '${bindingName}' in strict mode.`,
  306. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  307. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  308. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  309. StrictWith: "'with' in strict mode."
  310. };
  311. const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]);
  312. var PipelineOperatorErrors = {
  313. PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  314. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  315. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  316. PipeTopicUnconfiguredToken: ({
  317. token
  318. }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`,
  319. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  320. PipeUnparenthesizedBody: ({
  321. type
  322. }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({
  323. type
  324. })}; please wrap it in parentheses.`,
  325. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  326. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  327. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  328. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  329. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  330. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'
  331. };
  332. const _excluded = ["message"];
  333. function defineHidden(obj, key, value) {
  334. Object.defineProperty(obj, key, {
  335. enumerable: false,
  336. configurable: true,
  337. value
  338. });
  339. }
  340. function toParseErrorConstructor({
  341. toMessage,
  342. code,
  343. reasonCode,
  344. syntaxPlugin
  345. }) {
  346. const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins";
  347. return function constructor(loc, details) {
  348. const error = new SyntaxError();
  349. error.code = code;
  350. error.reasonCode = reasonCode;
  351. error.loc = loc;
  352. error.pos = loc.index;
  353. error.syntaxPlugin = syntaxPlugin;
  354. if (hasMissingPlugin) {
  355. error.missingPlugin = details.missingPlugin;
  356. }
  357. defineHidden(error, "clone", function clone(overrides = {}) {
  358. var _overrides$loc;
  359. const {
  360. line,
  361. column,
  362. index
  363. } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc;
  364. return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details));
  365. });
  366. defineHidden(error, "details", details);
  367. Object.defineProperty(error, "message", {
  368. configurable: true,
  369. get() {
  370. const message = `${toMessage(details)} (${loc.line}:${loc.column})`;
  371. this.message = message;
  372. return message;
  373. },
  374. set(value) {
  375. Object.defineProperty(this, "message", {
  376. value,
  377. writable: true
  378. });
  379. }
  380. });
  381. return error;
  382. };
  383. }
  384. function ParseErrorEnum(argument, syntaxPlugin) {
  385. if (Array.isArray(argument)) {
  386. return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]);
  387. }
  388. const ParseErrorConstructors = {};
  389. for (const reasonCode of Object.keys(argument)) {
  390. const template = argument[reasonCode];
  391. const _ref = typeof template === "string" ? {
  392. message: () => template
  393. } : typeof template === "function" ? {
  394. message: template
  395. } : template,
  396. {
  397. message
  398. } = _ref,
  399. rest = _objectWithoutPropertiesLoose(_ref, _excluded);
  400. const toMessage = typeof message === "string" ? () => message : message;
  401. ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({
  402. code: "BABEL_PARSER_SYNTAX_ERROR",
  403. reasonCode,
  404. toMessage
  405. }, syntaxPlugin ? {
  406. syntaxPlugin
  407. } : {}, rest));
  408. }
  409. return ParseErrorConstructors;
  410. }
  411. const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors));
  412. const {
  413. defineProperty
  414. } = Object;
  415. const toUnenumerable = (object, key) => {
  416. if (object) {
  417. defineProperty(object, key, {
  418. enumerable: false,
  419. value: object[key]
  420. });
  421. }
  422. };
  423. function toESTreeLocation(node) {
  424. toUnenumerable(node.loc.start, "index");
  425. toUnenumerable(node.loc.end, "index");
  426. return node;
  427. }
  428. var estree = superClass => class ESTreeParserMixin extends superClass {
  429. parse() {
  430. const file = toESTreeLocation(super.parse());
  431. if (this.options.tokens) {
  432. file.tokens = file.tokens.map(toESTreeLocation);
  433. }
  434. return file;
  435. }
  436. parseRegExpLiteral({
  437. pattern,
  438. flags
  439. }) {
  440. let regex = null;
  441. try {
  442. regex = new RegExp(pattern, flags);
  443. } catch (_) {}
  444. const node = this.estreeParseLiteral(regex);
  445. node.regex = {
  446. pattern,
  447. flags
  448. };
  449. return node;
  450. }
  451. parseBigIntLiteral(value) {
  452. let bigInt;
  453. try {
  454. bigInt = BigInt(value);
  455. } catch (_unused) {
  456. bigInt = null;
  457. }
  458. const node = this.estreeParseLiteral(bigInt);
  459. node.bigint = String(node.value || value);
  460. return node;
  461. }
  462. parseDecimalLiteral(value) {
  463. const decimal = null;
  464. const node = this.estreeParseLiteral(decimal);
  465. node.decimal = String(node.value || value);
  466. return node;
  467. }
  468. estreeParseLiteral(value) {
  469. return this.parseLiteral(value, "Literal");
  470. }
  471. parseStringLiteral(value) {
  472. return this.estreeParseLiteral(value);
  473. }
  474. parseNumericLiteral(value) {
  475. return this.estreeParseLiteral(value);
  476. }
  477. parseNullLiteral() {
  478. return this.estreeParseLiteral(null);
  479. }
  480. parseBooleanLiteral(value) {
  481. return this.estreeParseLiteral(value);
  482. }
  483. directiveToStmt(directive) {
  484. const expression = directive.value;
  485. delete directive.value;
  486. expression.type = "Literal";
  487. expression.raw = expression.extra.raw;
  488. expression.value = expression.extra.expressionValue;
  489. const stmt = directive;
  490. stmt.type = "ExpressionStatement";
  491. stmt.expression = expression;
  492. stmt.directive = expression.extra.rawValue;
  493. delete expression.extra;
  494. return stmt;
  495. }
  496. initFunction(node, isAsync) {
  497. super.initFunction(node, isAsync);
  498. node.expression = false;
  499. }
  500. checkDeclaration(node) {
  501. if (node != null && this.isObjectProperty(node)) {
  502. this.checkDeclaration(node.value);
  503. } else {
  504. super.checkDeclaration(node);
  505. }
  506. }
  507. getObjectOrClassMethodParams(method) {
  508. return method.value.params;
  509. }
  510. isValidDirective(stmt) {
  511. var _stmt$expression$extr;
  512. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  513. }
  514. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  515. super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse);
  516. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  517. node.body = directiveStatements.concat(node.body);
  518. delete node.directives;
  519. }
  520. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  521. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  522. if (method.typeParameters) {
  523. method.value.typeParameters = method.typeParameters;
  524. delete method.typeParameters;
  525. }
  526. classBody.body.push(method);
  527. }
  528. parsePrivateName() {
  529. const node = super.parsePrivateName();
  530. {
  531. if (!this.getPluginOption("estree", "classFeatures")) {
  532. return node;
  533. }
  534. }
  535. return this.convertPrivateNameToPrivateIdentifier(node);
  536. }
  537. convertPrivateNameToPrivateIdentifier(node) {
  538. const name = super.getPrivateNameSV(node);
  539. node = node;
  540. delete node.id;
  541. node.name = name;
  542. node.type = "PrivateIdentifier";
  543. return node;
  544. }
  545. isPrivateName(node) {
  546. {
  547. if (!this.getPluginOption("estree", "classFeatures")) {
  548. return super.isPrivateName(node);
  549. }
  550. }
  551. return node.type === "PrivateIdentifier";
  552. }
  553. getPrivateNameSV(node) {
  554. {
  555. if (!this.getPluginOption("estree", "classFeatures")) {
  556. return super.getPrivateNameSV(node);
  557. }
  558. }
  559. return node.name;
  560. }
  561. parseLiteral(value, type) {
  562. const node = super.parseLiteral(value, type);
  563. node.raw = node.extra.raw;
  564. delete node.extra;
  565. return node;
  566. }
  567. parseFunctionBody(node, allowExpression, isMethod = false) {
  568. super.parseFunctionBody(node, allowExpression, isMethod);
  569. node.expression = node.body.type !== "BlockStatement";
  570. }
  571. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  572. let funcNode = this.startNode();
  573. funcNode.kind = node.kind;
  574. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  575. funcNode.type = "FunctionExpression";
  576. delete funcNode.kind;
  577. node.value = funcNode;
  578. if (type === "ClassPrivateMethod") {
  579. node.computed = false;
  580. }
  581. return this.finishNode(node, "MethodDefinition");
  582. }
  583. nameIsConstructor(key) {
  584. if (key.type === "Literal") return key.value === "constructor";
  585. return super.nameIsConstructor(key);
  586. }
  587. parseClassProperty(...args) {
  588. const propertyNode = super.parseClassProperty(...args);
  589. {
  590. if (!this.getPluginOption("estree", "classFeatures")) {
  591. return propertyNode;
  592. }
  593. }
  594. propertyNode.type = "PropertyDefinition";
  595. return propertyNode;
  596. }
  597. parseClassPrivateProperty(...args) {
  598. const propertyNode = super.parseClassPrivateProperty(...args);
  599. {
  600. if (!this.getPluginOption("estree", "classFeatures")) {
  601. return propertyNode;
  602. }
  603. }
  604. propertyNode.type = "PropertyDefinition";
  605. propertyNode.computed = false;
  606. return propertyNode;
  607. }
  608. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  609. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  610. if (node) {
  611. node.type = "Property";
  612. if (node.kind === "method") {
  613. node.kind = "init";
  614. }
  615. node.shorthand = false;
  616. }
  617. return node;
  618. }
  619. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  620. const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  621. if (node) {
  622. node.kind = "init";
  623. node.type = "Property";
  624. }
  625. return node;
  626. }
  627. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  628. return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  629. }
  630. isAssignable(node, isBinding) {
  631. if (node != null && this.isObjectProperty(node)) {
  632. return this.isAssignable(node.value, isBinding);
  633. }
  634. return super.isAssignable(node, isBinding);
  635. }
  636. toAssignable(node, isLHS = false) {
  637. if (node != null && this.isObjectProperty(node)) {
  638. const {
  639. key,
  640. value
  641. } = node;
  642. if (this.isPrivateName(key)) {
  643. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  644. }
  645. this.toAssignable(value, isLHS);
  646. } else {
  647. super.toAssignable(node, isLHS);
  648. }
  649. }
  650. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  651. if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) {
  652. this.raise(Errors.PatternHasAccessor, prop.key);
  653. } else if (prop.type === "Property" && prop.method) {
  654. this.raise(Errors.PatternHasMethod, prop.key);
  655. } else {
  656. super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  657. }
  658. }
  659. finishCallExpression(unfinished, optional) {
  660. const node = super.finishCallExpression(unfinished, optional);
  661. if (node.callee.type === "Import") {
  662. node.type = "ImportExpression";
  663. node.source = node.arguments[0];
  664. if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) {
  665. var _ref, _ref2;
  666. node.options = (_ref = node.arguments[1]) != null ? _ref : null;
  667. node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null;
  668. }
  669. delete node.arguments;
  670. delete node.callee;
  671. }
  672. return node;
  673. }
  674. toReferencedArguments(node) {
  675. if (node.type === "ImportExpression") {
  676. return;
  677. }
  678. super.toReferencedArguments(node);
  679. }
  680. parseExport(unfinished, decorators) {
  681. const exportStartLoc = this.state.lastTokStartLoc;
  682. const node = super.parseExport(unfinished, decorators);
  683. switch (node.type) {
  684. case "ExportAllDeclaration":
  685. node.exported = null;
  686. break;
  687. case "ExportNamedDeclaration":
  688. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  689. node.type = "ExportAllDeclaration";
  690. node.exported = node.specifiers[0].exported;
  691. delete node.specifiers;
  692. }
  693. case "ExportDefaultDeclaration":
  694. {
  695. var _declaration$decorato;
  696. const {
  697. declaration
  698. } = node;
  699. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) {
  700. this.resetStartLocation(node, exportStartLoc);
  701. }
  702. }
  703. break;
  704. }
  705. return node;
  706. }
  707. parseSubscript(base, startLoc, noCalls, state) {
  708. const node = super.parseSubscript(base, startLoc, noCalls, state);
  709. if (state.optionalChainMember) {
  710. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  711. node.type = node.type.substring(8);
  712. }
  713. if (state.stop) {
  714. const chain = this.startNodeAtNode(node);
  715. chain.expression = node;
  716. return this.finishNode(chain, "ChainExpression");
  717. }
  718. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  719. node.optional = false;
  720. }
  721. return node;
  722. }
  723. isOptionalMemberExpression(node) {
  724. if (node.type === "ChainExpression") {
  725. return node.expression.type === "MemberExpression";
  726. }
  727. return super.isOptionalMemberExpression(node);
  728. }
  729. hasPropertyAsPrivateName(node) {
  730. if (node.type === "ChainExpression") {
  731. node = node.expression;
  732. }
  733. return super.hasPropertyAsPrivateName(node);
  734. }
  735. isObjectProperty(node) {
  736. return node.type === "Property" && node.kind === "init" && !node.method;
  737. }
  738. isObjectMethod(node) {
  739. return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set");
  740. }
  741. finishNodeAt(node, type, endLoc) {
  742. return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
  743. }
  744. resetStartLocation(node, startLoc) {
  745. super.resetStartLocation(node, startLoc);
  746. toESTreeLocation(node);
  747. }
  748. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  749. super.resetEndLocation(node, endLoc);
  750. toESTreeLocation(node);
  751. }
  752. };
  753. class TokContext {
  754. constructor(token, preserveSpace) {
  755. this.token = void 0;
  756. this.preserveSpace = void 0;
  757. this.token = token;
  758. this.preserveSpace = !!preserveSpace;
  759. }
  760. }
  761. const types = {
  762. brace: new TokContext("{"),
  763. j_oTag: new TokContext("<tag"),
  764. j_cTag: new TokContext("</tag"),
  765. j_expr: new TokContext("<tag>...</tag>", true)
  766. };
  767. {
  768. types.template = new TokContext("`", true);
  769. }
  770. const beforeExpr = true;
  771. const startsExpr = true;
  772. const isLoop = true;
  773. const isAssign = true;
  774. const prefix = true;
  775. const postfix = true;
  776. class ExportedTokenType {
  777. constructor(label, conf = {}) {
  778. this.label = void 0;
  779. this.keyword = void 0;
  780. this.beforeExpr = void 0;
  781. this.startsExpr = void 0;
  782. this.rightAssociative = void 0;
  783. this.isLoop = void 0;
  784. this.isAssign = void 0;
  785. this.prefix = void 0;
  786. this.postfix = void 0;
  787. this.binop = void 0;
  788. this.label = label;
  789. this.keyword = conf.keyword;
  790. this.beforeExpr = !!conf.beforeExpr;
  791. this.startsExpr = !!conf.startsExpr;
  792. this.rightAssociative = !!conf.rightAssociative;
  793. this.isLoop = !!conf.isLoop;
  794. this.isAssign = !!conf.isAssign;
  795. this.prefix = !!conf.prefix;
  796. this.postfix = !!conf.postfix;
  797. this.binop = conf.binop != null ? conf.binop : null;
  798. {
  799. this.updateContext = null;
  800. }
  801. }
  802. }
  803. const keywords$1 = new Map();
  804. function createKeyword(name, options = {}) {
  805. options.keyword = name;
  806. const token = createToken(name, options);
  807. keywords$1.set(name, token);
  808. return token;
  809. }
  810. function createBinop(name, binop) {
  811. return createToken(name, {
  812. beforeExpr,
  813. binop
  814. });
  815. }
  816. let tokenTypeCounter = -1;
  817. const tokenTypes = [];
  818. const tokenLabels = [];
  819. const tokenBinops = [];
  820. const tokenBeforeExprs = [];
  821. const tokenStartsExprs = [];
  822. const tokenPrefixes = [];
  823. function createToken(name, options = {}) {
  824. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  825. ++tokenTypeCounter;
  826. tokenLabels.push(name);
  827. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  828. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  829. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  830. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  831. tokenTypes.push(new ExportedTokenType(name, options));
  832. return tokenTypeCounter;
  833. }
  834. function createKeywordLike(name, options = {}) {
  835. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  836. ++tokenTypeCounter;
  837. keywords$1.set(name, tokenTypeCounter);
  838. tokenLabels.push(name);
  839. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  840. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  841. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  842. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  843. tokenTypes.push(new ExportedTokenType("name", options));
  844. return tokenTypeCounter;
  845. }
  846. const tt = {
  847. bracketL: createToken("[", {
  848. beforeExpr,
  849. startsExpr
  850. }),
  851. bracketHashL: createToken("#[", {
  852. beforeExpr,
  853. startsExpr
  854. }),
  855. bracketBarL: createToken("[|", {
  856. beforeExpr,
  857. startsExpr
  858. }),
  859. bracketR: createToken("]"),
  860. bracketBarR: createToken("|]"),
  861. braceL: createToken("{", {
  862. beforeExpr,
  863. startsExpr
  864. }),
  865. braceBarL: createToken("{|", {
  866. beforeExpr,
  867. startsExpr
  868. }),
  869. braceHashL: createToken("#{", {
  870. beforeExpr,
  871. startsExpr
  872. }),
  873. braceR: createToken("}"),
  874. braceBarR: createToken("|}"),
  875. parenL: createToken("(", {
  876. beforeExpr,
  877. startsExpr
  878. }),
  879. parenR: createToken(")"),
  880. comma: createToken(",", {
  881. beforeExpr
  882. }),
  883. semi: createToken(";", {
  884. beforeExpr
  885. }),
  886. colon: createToken(":", {
  887. beforeExpr
  888. }),
  889. doubleColon: createToken("::", {
  890. beforeExpr
  891. }),
  892. dot: createToken("."),
  893. question: createToken("?", {
  894. beforeExpr
  895. }),
  896. questionDot: createToken("?."),
  897. arrow: createToken("=>", {
  898. beforeExpr
  899. }),
  900. template: createToken("template"),
  901. ellipsis: createToken("...", {
  902. beforeExpr
  903. }),
  904. backQuote: createToken("`", {
  905. startsExpr
  906. }),
  907. dollarBraceL: createToken("${", {
  908. beforeExpr,
  909. startsExpr
  910. }),
  911. templateTail: createToken("...`", {
  912. startsExpr
  913. }),
  914. templateNonTail: createToken("...${", {
  915. beforeExpr,
  916. startsExpr
  917. }),
  918. at: createToken("@"),
  919. hash: createToken("#", {
  920. startsExpr
  921. }),
  922. interpreterDirective: createToken("#!..."),
  923. eq: createToken("=", {
  924. beforeExpr,
  925. isAssign
  926. }),
  927. assign: createToken("_=", {
  928. beforeExpr,
  929. isAssign
  930. }),
  931. slashAssign: createToken("_=", {
  932. beforeExpr,
  933. isAssign
  934. }),
  935. xorAssign: createToken("_=", {
  936. beforeExpr,
  937. isAssign
  938. }),
  939. moduloAssign: createToken("_=", {
  940. beforeExpr,
  941. isAssign
  942. }),
  943. incDec: createToken("++/--", {
  944. prefix,
  945. postfix,
  946. startsExpr
  947. }),
  948. bang: createToken("!", {
  949. beforeExpr,
  950. prefix,
  951. startsExpr
  952. }),
  953. tilde: createToken("~", {
  954. beforeExpr,
  955. prefix,
  956. startsExpr
  957. }),
  958. doubleCaret: createToken("^^", {
  959. startsExpr
  960. }),
  961. doubleAt: createToken("@@", {
  962. startsExpr
  963. }),
  964. pipeline: createBinop("|>", 0),
  965. nullishCoalescing: createBinop("??", 1),
  966. logicalOR: createBinop("||", 1),
  967. logicalAND: createBinop("&&", 2),
  968. bitwiseOR: createBinop("|", 3),
  969. bitwiseXOR: createBinop("^", 4),
  970. bitwiseAND: createBinop("&", 5),
  971. equality: createBinop("==/!=/===/!==", 6),
  972. lt: createBinop("</>/<=/>=", 7),
  973. gt: createBinop("</>/<=/>=", 7),
  974. relational: createBinop("</>/<=/>=", 7),
  975. bitShift: createBinop("<</>>/>>>", 8),
  976. bitShiftL: createBinop("<</>>/>>>", 8),
  977. bitShiftR: createBinop("<</>>/>>>", 8),
  978. plusMin: createToken("+/-", {
  979. beforeExpr,
  980. binop: 9,
  981. prefix,
  982. startsExpr
  983. }),
  984. modulo: createToken("%", {
  985. binop: 10,
  986. startsExpr
  987. }),
  988. star: createToken("*", {
  989. binop: 10
  990. }),
  991. slash: createBinop("/", 10),
  992. exponent: createToken("**", {
  993. beforeExpr,
  994. binop: 11,
  995. rightAssociative: true
  996. }),
  997. _in: createKeyword("in", {
  998. beforeExpr,
  999. binop: 7
  1000. }),
  1001. _instanceof: createKeyword("instanceof", {
  1002. beforeExpr,
  1003. binop: 7
  1004. }),
  1005. _break: createKeyword("break"),
  1006. _case: createKeyword("case", {
  1007. beforeExpr
  1008. }),
  1009. _catch: createKeyword("catch"),
  1010. _continue: createKeyword("continue"),
  1011. _debugger: createKeyword("debugger"),
  1012. _default: createKeyword("default", {
  1013. beforeExpr
  1014. }),
  1015. _else: createKeyword("else", {
  1016. beforeExpr
  1017. }),
  1018. _finally: createKeyword("finally"),
  1019. _function: createKeyword("function", {
  1020. startsExpr
  1021. }),
  1022. _if: createKeyword("if"),
  1023. _return: createKeyword("return", {
  1024. beforeExpr
  1025. }),
  1026. _switch: createKeyword("switch"),
  1027. _throw: createKeyword("throw", {
  1028. beforeExpr,
  1029. prefix,
  1030. startsExpr
  1031. }),
  1032. _try: createKeyword("try"),
  1033. _var: createKeyword("var"),
  1034. _const: createKeyword("const"),
  1035. _with: createKeyword("with"),
  1036. _new: createKeyword("new", {
  1037. beforeExpr,
  1038. startsExpr
  1039. }),
  1040. _this: createKeyword("this", {
  1041. startsExpr
  1042. }),
  1043. _super: createKeyword("super", {
  1044. startsExpr
  1045. }),
  1046. _class: createKeyword("class", {
  1047. startsExpr
  1048. }),
  1049. _extends: createKeyword("extends", {
  1050. beforeExpr
  1051. }),
  1052. _export: createKeyword("export"),
  1053. _import: createKeyword("import", {
  1054. startsExpr
  1055. }),
  1056. _null: createKeyword("null", {
  1057. startsExpr
  1058. }),
  1059. _true: createKeyword("true", {
  1060. startsExpr
  1061. }),
  1062. _false: createKeyword("false", {
  1063. startsExpr
  1064. }),
  1065. _typeof: createKeyword("typeof", {
  1066. beforeExpr,
  1067. prefix,
  1068. startsExpr
  1069. }),
  1070. _void: createKeyword("void", {
  1071. beforeExpr,
  1072. prefix,
  1073. startsExpr
  1074. }),
  1075. _delete: createKeyword("delete", {
  1076. beforeExpr,
  1077. prefix,
  1078. startsExpr
  1079. }),
  1080. _do: createKeyword("do", {
  1081. isLoop,
  1082. beforeExpr
  1083. }),
  1084. _for: createKeyword("for", {
  1085. isLoop
  1086. }),
  1087. _while: createKeyword("while", {
  1088. isLoop
  1089. }),
  1090. _as: createKeywordLike("as", {
  1091. startsExpr
  1092. }),
  1093. _assert: createKeywordLike("assert", {
  1094. startsExpr
  1095. }),
  1096. _async: createKeywordLike("async", {
  1097. startsExpr
  1098. }),
  1099. _await: createKeywordLike("await", {
  1100. startsExpr
  1101. }),
  1102. _defer: createKeywordLike("defer", {
  1103. startsExpr
  1104. }),
  1105. _from: createKeywordLike("from", {
  1106. startsExpr
  1107. }),
  1108. _get: createKeywordLike("get", {
  1109. startsExpr
  1110. }),
  1111. _let: createKeywordLike("let", {
  1112. startsExpr
  1113. }),
  1114. _meta: createKeywordLike("meta", {
  1115. startsExpr
  1116. }),
  1117. _of: createKeywordLike("of", {
  1118. startsExpr
  1119. }),
  1120. _sent: createKeywordLike("sent", {
  1121. startsExpr
  1122. }),
  1123. _set: createKeywordLike("set", {
  1124. startsExpr
  1125. }),
  1126. _source: createKeywordLike("source", {
  1127. startsExpr
  1128. }),
  1129. _static: createKeywordLike("static", {
  1130. startsExpr
  1131. }),
  1132. _using: createKeywordLike("using", {
  1133. startsExpr
  1134. }),
  1135. _yield: createKeywordLike("yield", {
  1136. startsExpr
  1137. }),
  1138. _asserts: createKeywordLike("asserts", {
  1139. startsExpr
  1140. }),
  1141. _checks: createKeywordLike("checks", {
  1142. startsExpr
  1143. }),
  1144. _exports: createKeywordLike("exports", {
  1145. startsExpr
  1146. }),
  1147. _global: createKeywordLike("global", {
  1148. startsExpr
  1149. }),
  1150. _implements: createKeywordLike("implements", {
  1151. startsExpr
  1152. }),
  1153. _intrinsic: createKeywordLike("intrinsic", {
  1154. startsExpr
  1155. }),
  1156. _infer: createKeywordLike("infer", {
  1157. startsExpr
  1158. }),
  1159. _is: createKeywordLike("is", {
  1160. startsExpr
  1161. }),
  1162. _mixins: createKeywordLike("mixins", {
  1163. startsExpr
  1164. }),
  1165. _proto: createKeywordLike("proto", {
  1166. startsExpr
  1167. }),
  1168. _require: createKeywordLike("require", {
  1169. startsExpr
  1170. }),
  1171. _satisfies: createKeywordLike("satisfies", {
  1172. startsExpr
  1173. }),
  1174. _keyof: createKeywordLike("keyof", {
  1175. startsExpr
  1176. }),
  1177. _readonly: createKeywordLike("readonly", {
  1178. startsExpr
  1179. }),
  1180. _unique: createKeywordLike("unique", {
  1181. startsExpr
  1182. }),
  1183. _abstract: createKeywordLike("abstract", {
  1184. startsExpr
  1185. }),
  1186. _declare: createKeywordLike("declare", {
  1187. startsExpr
  1188. }),
  1189. _enum: createKeywordLike("enum", {
  1190. startsExpr
  1191. }),
  1192. _module: createKeywordLike("module", {
  1193. startsExpr
  1194. }),
  1195. _namespace: createKeywordLike("namespace", {
  1196. startsExpr
  1197. }),
  1198. _interface: createKeywordLike("interface", {
  1199. startsExpr
  1200. }),
  1201. _type: createKeywordLike("type", {
  1202. startsExpr
  1203. }),
  1204. _opaque: createKeywordLike("opaque", {
  1205. startsExpr
  1206. }),
  1207. name: createToken("name", {
  1208. startsExpr
  1209. }),
  1210. string: createToken("string", {
  1211. startsExpr
  1212. }),
  1213. num: createToken("num", {
  1214. startsExpr
  1215. }),
  1216. bigint: createToken("bigint", {
  1217. startsExpr
  1218. }),
  1219. decimal: createToken("decimal", {
  1220. startsExpr
  1221. }),
  1222. regexp: createToken("regexp", {
  1223. startsExpr
  1224. }),
  1225. privateName: createToken("#name", {
  1226. startsExpr
  1227. }),
  1228. eof: createToken("eof"),
  1229. jsxName: createToken("jsxName"),
  1230. jsxText: createToken("jsxText", {
  1231. beforeExpr: true
  1232. }),
  1233. jsxTagStart: createToken("jsxTagStart", {
  1234. startsExpr: true
  1235. }),
  1236. jsxTagEnd: createToken("jsxTagEnd"),
  1237. placeholder: createToken("%%", {
  1238. startsExpr: true
  1239. })
  1240. };
  1241. function tokenIsIdentifier(token) {
  1242. return token >= 93 && token <= 132;
  1243. }
  1244. function tokenKeywordOrIdentifierIsKeyword(token) {
  1245. return token <= 92;
  1246. }
  1247. function tokenIsKeywordOrIdentifier(token) {
  1248. return token >= 58 && token <= 132;
  1249. }
  1250. function tokenIsLiteralPropertyName(token) {
  1251. return token >= 58 && token <= 136;
  1252. }
  1253. function tokenComesBeforeExpression(token) {
  1254. return tokenBeforeExprs[token];
  1255. }
  1256. function tokenCanStartExpression(token) {
  1257. return tokenStartsExprs[token];
  1258. }
  1259. function tokenIsAssignment(token) {
  1260. return token >= 29 && token <= 33;
  1261. }
  1262. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  1263. return token >= 129 && token <= 131;
  1264. }
  1265. function tokenIsLoop(token) {
  1266. return token >= 90 && token <= 92;
  1267. }
  1268. function tokenIsKeyword(token) {
  1269. return token >= 58 && token <= 92;
  1270. }
  1271. function tokenIsOperator(token) {
  1272. return token >= 39 && token <= 59;
  1273. }
  1274. function tokenIsPostfix(token) {
  1275. return token === 34;
  1276. }
  1277. function tokenIsPrefix(token) {
  1278. return tokenPrefixes[token];
  1279. }
  1280. function tokenIsTSTypeOperator(token) {
  1281. return token >= 121 && token <= 123;
  1282. }
  1283. function tokenIsTSDeclarationStart(token) {
  1284. return token >= 124 && token <= 130;
  1285. }
  1286. function tokenLabelName(token) {
  1287. return tokenLabels[token];
  1288. }
  1289. function tokenOperatorPrecedence(token) {
  1290. return tokenBinops[token];
  1291. }
  1292. function tokenIsRightAssociative(token) {
  1293. return token === 57;
  1294. }
  1295. function tokenIsTemplate(token) {
  1296. return token >= 24 && token <= 25;
  1297. }
  1298. function getExportedToken(token) {
  1299. return tokenTypes[token];
  1300. }
  1301. {
  1302. tokenTypes[8].updateContext = context => {
  1303. context.pop();
  1304. };
  1305. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  1306. context.push(types.brace);
  1307. };
  1308. tokenTypes[22].updateContext = context => {
  1309. if (context[context.length - 1] === types.template) {
  1310. context.pop();
  1311. } else {
  1312. context.push(types.template);
  1313. }
  1314. };
  1315. tokenTypes[142].updateContext = context => {
  1316. context.push(types.j_expr, types.j_oTag);
  1317. };
  1318. }
  1319. 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\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\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-\u1b4c\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-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  1320. 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\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\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\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\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-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65";
  1321. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1322. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1323. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1324. 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, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 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, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 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, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 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, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
  1325. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  1326. function isInAstralSet(code, set) {
  1327. let pos = 0x10000;
  1328. for (let i = 0, length = set.length; i < length; i += 2) {
  1329. pos += set[i];
  1330. if (pos > code) return false;
  1331. pos += set[i + 1];
  1332. if (pos >= code) return true;
  1333. }
  1334. return false;
  1335. }
  1336. function isIdentifierStart(code) {
  1337. if (code < 65) return code === 36;
  1338. if (code <= 90) return true;
  1339. if (code < 97) return code === 95;
  1340. if (code <= 122) return true;
  1341. if (code <= 0xffff) {
  1342. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1343. }
  1344. return isInAstralSet(code, astralIdentifierStartCodes);
  1345. }
  1346. function isIdentifierChar(code) {
  1347. if (code < 48) return code === 36;
  1348. if (code < 58) return true;
  1349. if (code < 65) return false;
  1350. if (code <= 90) return true;
  1351. if (code < 97) return code === 95;
  1352. if (code <= 122) return true;
  1353. if (code <= 0xffff) {
  1354. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1355. }
  1356. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1357. }
  1358. const reservedWords = {
  1359. keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  1360. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1361. strictBind: ["eval", "arguments"]
  1362. };
  1363. const keywords = new Set(reservedWords.keyword);
  1364. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1365. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1366. function isReservedWord(word, inModule) {
  1367. return inModule && word === "await" || word === "enum";
  1368. }
  1369. function isStrictReservedWord(word, inModule) {
  1370. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1371. }
  1372. function isStrictBindOnlyReservedWord(word) {
  1373. return reservedWordsStrictBindSet.has(word);
  1374. }
  1375. function isStrictBindReservedWord(word, inModule) {
  1376. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1377. }
  1378. function isKeyword(word) {
  1379. return keywords.has(word);
  1380. }
  1381. function isIteratorStart(current, next, next2) {
  1382. return current === 64 && next === 64 && isIdentifierStart(next2);
  1383. }
  1384. const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]);
  1385. function canBeReservedWord(word) {
  1386. return reservedWordLikeSet.has(word);
  1387. }
  1388. class Scope {
  1389. constructor(flags) {
  1390. this.flags = 0;
  1391. this.names = new Map();
  1392. this.firstLexicalName = "";
  1393. this.flags = flags;
  1394. }
  1395. }
  1396. class ScopeHandler {
  1397. constructor(parser, inModule) {
  1398. this.parser = void 0;
  1399. this.scopeStack = [];
  1400. this.inModule = void 0;
  1401. this.undefinedExports = new Map();
  1402. this.parser = parser;
  1403. this.inModule = inModule;
  1404. }
  1405. get inTopLevel() {
  1406. return (this.currentScope().flags & 1) > 0;
  1407. }
  1408. get inFunction() {
  1409. return (this.currentVarScopeFlags() & 2) > 0;
  1410. }
  1411. get allowSuper() {
  1412. return (this.currentThisScopeFlags() & 16) > 0;
  1413. }
  1414. get allowDirectSuper() {
  1415. return (this.currentThisScopeFlags() & 32) > 0;
  1416. }
  1417. get inClass() {
  1418. return (this.currentThisScopeFlags() & 64) > 0;
  1419. }
  1420. get inClassAndNotInNonArrowFunction() {
  1421. const flags = this.currentThisScopeFlags();
  1422. return (flags & 64) > 0 && (flags & 2) === 0;
  1423. }
  1424. get inStaticBlock() {
  1425. for (let i = this.scopeStack.length - 1;; i--) {
  1426. const {
  1427. flags
  1428. } = this.scopeStack[i];
  1429. if (flags & 128) {
  1430. return true;
  1431. }
  1432. if (flags & (387 | 64)) {
  1433. return false;
  1434. }
  1435. }
  1436. }
  1437. get inNonArrowFunction() {
  1438. return (this.currentThisScopeFlags() & 2) > 0;
  1439. }
  1440. get treatFunctionsAsVar() {
  1441. return this.treatFunctionsAsVarInScope(this.currentScope());
  1442. }
  1443. createScope(flags) {
  1444. return new Scope(flags);
  1445. }
  1446. enter(flags) {
  1447. this.scopeStack.push(this.createScope(flags));
  1448. }
  1449. exit() {
  1450. const scope = this.scopeStack.pop();
  1451. return scope.flags;
  1452. }
  1453. treatFunctionsAsVarInScope(scope) {
  1454. return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1);
  1455. }
  1456. declareName(name, bindingType, loc) {
  1457. let scope = this.currentScope();
  1458. if (bindingType & 8 || bindingType & 16) {
  1459. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1460. let type = scope.names.get(name) || 0;
  1461. if (bindingType & 16) {
  1462. type = type | 4;
  1463. } else {
  1464. if (!scope.firstLexicalName) {
  1465. scope.firstLexicalName = name;
  1466. }
  1467. type = type | 2;
  1468. }
  1469. scope.names.set(name, type);
  1470. if (bindingType & 8) {
  1471. this.maybeExportDefined(scope, name);
  1472. }
  1473. } else if (bindingType & 4) {
  1474. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  1475. scope = this.scopeStack[i];
  1476. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1477. scope.names.set(name, (scope.names.get(name) || 0) | 1);
  1478. this.maybeExportDefined(scope, name);
  1479. if (scope.flags & 387) break;
  1480. }
  1481. }
  1482. if (this.parser.inModule && scope.flags & 1) {
  1483. this.undefinedExports.delete(name);
  1484. }
  1485. }
  1486. maybeExportDefined(scope, name) {
  1487. if (this.parser.inModule && scope.flags & 1) {
  1488. this.undefinedExports.delete(name);
  1489. }
  1490. }
  1491. checkRedeclarationInScope(scope, name, bindingType, loc) {
  1492. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  1493. this.parser.raise(Errors.VarRedeclaration, loc, {
  1494. identifierName: name
  1495. });
  1496. }
  1497. }
  1498. isRedeclaredInScope(scope, name, bindingType) {
  1499. if (!(bindingType & 1)) return false;
  1500. if (bindingType & 8) {
  1501. return scope.names.has(name);
  1502. }
  1503. const type = scope.names.get(name);
  1504. if (bindingType & 16) {
  1505. return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0;
  1506. }
  1507. return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0;
  1508. }
  1509. checkLocalExport(id) {
  1510. const {
  1511. name
  1512. } = id;
  1513. const topLevelScope = this.scopeStack[0];
  1514. if (!topLevelScope.names.has(name)) {
  1515. this.undefinedExports.set(name, id.loc.start);
  1516. }
  1517. }
  1518. currentScope() {
  1519. return this.scopeStack[this.scopeStack.length - 1];
  1520. }
  1521. currentVarScopeFlags() {
  1522. for (let i = this.scopeStack.length - 1;; i--) {
  1523. const {
  1524. flags
  1525. } = this.scopeStack[i];
  1526. if (flags & 387) {
  1527. return flags;
  1528. }
  1529. }
  1530. }
  1531. currentThisScopeFlags() {
  1532. for (let i = this.scopeStack.length - 1;; i--) {
  1533. const {
  1534. flags
  1535. } = this.scopeStack[i];
  1536. if (flags & (387 | 64) && !(flags & 4)) {
  1537. return flags;
  1538. }
  1539. }
  1540. }
  1541. }
  1542. class FlowScope extends Scope {
  1543. constructor(...args) {
  1544. super(...args);
  1545. this.declareFunctions = new Set();
  1546. }
  1547. }
  1548. class FlowScopeHandler extends ScopeHandler {
  1549. createScope(flags) {
  1550. return new FlowScope(flags);
  1551. }
  1552. declareName(name, bindingType, loc) {
  1553. const scope = this.currentScope();
  1554. if (bindingType & 2048) {
  1555. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  1556. this.maybeExportDefined(scope, name);
  1557. scope.declareFunctions.add(name);
  1558. return;
  1559. }
  1560. super.declareName(name, bindingType, loc);
  1561. }
  1562. isRedeclaredInScope(scope, name, bindingType) {
  1563. if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
  1564. if (bindingType & 2048 && !scope.declareFunctions.has(name)) {
  1565. const type = scope.names.get(name);
  1566. return (type & 4) > 0 || (type & 2) > 0;
  1567. }
  1568. return false;
  1569. }
  1570. checkLocalExport(id) {
  1571. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  1572. super.checkLocalExport(id);
  1573. }
  1574. }
  1575. }
  1576. class BaseParser {
  1577. constructor() {
  1578. this.sawUnambiguousESM = false;
  1579. this.ambiguousScriptDifferentAst = false;
  1580. }
  1581. hasPlugin(pluginConfig) {
  1582. if (typeof pluginConfig === "string") {
  1583. return this.plugins.has(pluginConfig);
  1584. } else {
  1585. const [pluginName, pluginOptions] = pluginConfig;
  1586. if (!this.hasPlugin(pluginName)) {
  1587. return false;
  1588. }
  1589. const actualOptions = this.plugins.get(pluginName);
  1590. for (const key of Object.keys(pluginOptions)) {
  1591. if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
  1592. return false;
  1593. }
  1594. }
  1595. return true;
  1596. }
  1597. }
  1598. getPluginOption(plugin, name) {
  1599. var _this$plugins$get;
  1600. return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name];
  1601. }
  1602. }
  1603. function setTrailingComments(node, comments) {
  1604. if (node.trailingComments === undefined) {
  1605. node.trailingComments = comments;
  1606. } else {
  1607. node.trailingComments.unshift(...comments);
  1608. }
  1609. }
  1610. function setLeadingComments(node, comments) {
  1611. if (node.leadingComments === undefined) {
  1612. node.leadingComments = comments;
  1613. } else {
  1614. node.leadingComments.unshift(...comments);
  1615. }
  1616. }
  1617. function setInnerComments(node, comments) {
  1618. if (node.innerComments === undefined) {
  1619. node.innerComments = comments;
  1620. } else {
  1621. node.innerComments.unshift(...comments);
  1622. }
  1623. }
  1624. function adjustInnerComments(node, elements, commentWS) {
  1625. let lastElement = null;
  1626. let i = elements.length;
  1627. while (lastElement === null && i > 0) {
  1628. lastElement = elements[--i];
  1629. }
  1630. if (lastElement === null || lastElement.start > commentWS.start) {
  1631. setInnerComments(node, commentWS.comments);
  1632. } else {
  1633. setTrailingComments(lastElement, commentWS.comments);
  1634. }
  1635. }
  1636. class CommentsParser extends BaseParser {
  1637. addComment(comment) {
  1638. if (this.filename) comment.loc.filename = this.filename;
  1639. const {
  1640. commentsLen
  1641. } = this.state;
  1642. if (this.comments.length !== commentsLen) {
  1643. this.comments.length = commentsLen;
  1644. }
  1645. this.comments.push(comment);
  1646. this.state.commentsLen++;
  1647. }
  1648. processComment(node) {
  1649. const {
  1650. commentStack
  1651. } = this.state;
  1652. const commentStackLength = commentStack.length;
  1653. if (commentStackLength === 0) return;
  1654. let i = commentStackLength - 1;
  1655. const lastCommentWS = commentStack[i];
  1656. if (lastCommentWS.start === node.end) {
  1657. lastCommentWS.leadingNode = node;
  1658. i--;
  1659. }
  1660. const {
  1661. start: nodeStart
  1662. } = node;
  1663. for (; i >= 0; i--) {
  1664. const commentWS = commentStack[i];
  1665. const commentEnd = commentWS.end;
  1666. if (commentEnd > nodeStart) {
  1667. commentWS.containingNode = node;
  1668. this.finalizeComment(commentWS);
  1669. commentStack.splice(i, 1);
  1670. } else {
  1671. if (commentEnd === nodeStart) {
  1672. commentWS.trailingNode = node;
  1673. }
  1674. break;
  1675. }
  1676. }
  1677. }
  1678. finalizeComment(commentWS) {
  1679. const {
  1680. comments
  1681. } = commentWS;
  1682. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  1683. if (commentWS.leadingNode !== null) {
  1684. setTrailingComments(commentWS.leadingNode, comments);
  1685. }
  1686. if (commentWS.trailingNode !== null) {
  1687. setLeadingComments(commentWS.trailingNode, comments);
  1688. }
  1689. } else {
  1690. const {
  1691. containingNode: node,
  1692. start: commentStart
  1693. } = commentWS;
  1694. if (this.input.charCodeAt(commentStart - 1) === 44) {
  1695. switch (node.type) {
  1696. case "ObjectExpression":
  1697. case "ObjectPattern":
  1698. case "RecordExpression":
  1699. adjustInnerComments(node, node.properties, commentWS);
  1700. break;
  1701. case "CallExpression":
  1702. case "OptionalCallExpression":
  1703. adjustInnerComments(node, node.arguments, commentWS);
  1704. break;
  1705. case "FunctionDeclaration":
  1706. case "FunctionExpression":
  1707. case "ArrowFunctionExpression":
  1708. case "ObjectMethod":
  1709. case "ClassMethod":
  1710. case "ClassPrivateMethod":
  1711. adjustInnerComments(node, node.params, commentWS);
  1712. break;
  1713. case "ArrayExpression":
  1714. case "ArrayPattern":
  1715. case "TupleExpression":
  1716. adjustInnerComments(node, node.elements, commentWS);
  1717. break;
  1718. case "ExportNamedDeclaration":
  1719. case "ImportDeclaration":
  1720. adjustInnerComments(node, node.specifiers, commentWS);
  1721. break;
  1722. default:
  1723. {
  1724. setInnerComments(node, comments);
  1725. }
  1726. }
  1727. } else {
  1728. setInnerComments(node, comments);
  1729. }
  1730. }
  1731. }
  1732. finalizeRemainingComments() {
  1733. const {
  1734. commentStack
  1735. } = this.state;
  1736. for (let i = commentStack.length - 1; i >= 0; i--) {
  1737. this.finalizeComment(commentStack[i]);
  1738. }
  1739. this.state.commentStack = [];
  1740. }
  1741. resetPreviousNodeTrailingComments(node) {
  1742. const {
  1743. commentStack
  1744. } = this.state;
  1745. const {
  1746. length
  1747. } = commentStack;
  1748. if (length === 0) return;
  1749. const commentWS = commentStack[length - 1];
  1750. if (commentWS.leadingNode === node) {
  1751. commentWS.leadingNode = null;
  1752. }
  1753. }
  1754. resetPreviousIdentifierLeadingComments(node) {
  1755. const {
  1756. commentStack
  1757. } = this.state;
  1758. const {
  1759. length
  1760. } = commentStack;
  1761. if (length === 0) return;
  1762. if (commentStack[length - 1].trailingNode === node) {
  1763. commentStack[length - 1].trailingNode = null;
  1764. } else if (length >= 2 && commentStack[length - 2].trailingNode === node) {
  1765. commentStack[length - 2].trailingNode = null;
  1766. }
  1767. }
  1768. takeSurroundingComments(node, start, end) {
  1769. const {
  1770. commentStack
  1771. } = this.state;
  1772. const commentStackLength = commentStack.length;
  1773. if (commentStackLength === 0) return;
  1774. let i = commentStackLength - 1;
  1775. for (; i >= 0; i--) {
  1776. const commentWS = commentStack[i];
  1777. const commentEnd = commentWS.end;
  1778. const commentStart = commentWS.start;
  1779. if (commentStart === end) {
  1780. commentWS.leadingNode = node;
  1781. } else if (commentEnd === start) {
  1782. commentWS.trailingNode = node;
  1783. } else if (commentEnd < start) {
  1784. break;
  1785. }
  1786. }
  1787. }
  1788. }
  1789. const lineBreak = /\r\n|[\r\n\u2028\u2029]/;
  1790. const lineBreakG = new RegExp(lineBreak.source, "g");
  1791. function isNewLine(code) {
  1792. switch (code) {
  1793. case 10:
  1794. case 13:
  1795. case 8232:
  1796. case 8233:
  1797. return true;
  1798. default:
  1799. return false;
  1800. }
  1801. }
  1802. function hasNewLine(input, start, end) {
  1803. for (let i = start; i < end; i++) {
  1804. if (isNewLine(input.charCodeAt(i))) {
  1805. return true;
  1806. }
  1807. }
  1808. return false;
  1809. }
  1810. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  1811. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;
  1812. function isWhitespace(code) {
  1813. switch (code) {
  1814. case 0x0009:
  1815. case 0x000b:
  1816. case 0x000c:
  1817. case 32:
  1818. case 160:
  1819. case 5760:
  1820. case 0x2000:
  1821. case 0x2001:
  1822. case 0x2002:
  1823. case 0x2003:
  1824. case 0x2004:
  1825. case 0x2005:
  1826. case 0x2006:
  1827. case 0x2007:
  1828. case 0x2008:
  1829. case 0x2009:
  1830. case 0x200a:
  1831. case 0x202f:
  1832. case 0x205f:
  1833. case 0x3000:
  1834. case 0xfeff:
  1835. return true;
  1836. default:
  1837. return false;
  1838. }
  1839. }
  1840. class State {
  1841. constructor() {
  1842. this.flags = 1024;
  1843. this.curLine = void 0;
  1844. this.lineStart = void 0;
  1845. this.startLoc = void 0;
  1846. this.endLoc = void 0;
  1847. this.errors = [];
  1848. this.potentialArrowAt = -1;
  1849. this.noArrowAt = [];
  1850. this.noArrowParamsConversionAt = [];
  1851. this.topicContext = {
  1852. maxNumOfResolvableTopics: 0,
  1853. maxTopicIndex: null
  1854. };
  1855. this.labels = [];
  1856. this.commentsLen = 0;
  1857. this.commentStack = [];
  1858. this.pos = 0;
  1859. this.type = 139;
  1860. this.value = null;
  1861. this.start = 0;
  1862. this.end = 0;
  1863. this.lastTokEndLoc = null;
  1864. this.lastTokStartLoc = null;
  1865. this.context = [types.brace];
  1866. this.firstInvalidTemplateEscapePos = null;
  1867. this.strictErrors = new Map();
  1868. this.tokensLength = 0;
  1869. }
  1870. get strict() {
  1871. return (this.flags & 1) > 0;
  1872. }
  1873. set strict(v) {
  1874. if (v) this.flags |= 1;else this.flags &= -2;
  1875. }
  1876. init({
  1877. strictMode,
  1878. sourceType,
  1879. startLine,
  1880. startColumn
  1881. }) {
  1882. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  1883. this.curLine = startLine;
  1884. this.lineStart = -startColumn;
  1885. this.startLoc = this.endLoc = new Position(startLine, startColumn, 0);
  1886. }
  1887. get maybeInArrowParameters() {
  1888. return (this.flags & 2) > 0;
  1889. }
  1890. set maybeInArrowParameters(v) {
  1891. if (v) this.flags |= 2;else this.flags &= -3;
  1892. }
  1893. get inType() {
  1894. return (this.flags & 4) > 0;
  1895. }
  1896. set inType(v) {
  1897. if (v) this.flags |= 4;else this.flags &= -5;
  1898. }
  1899. get noAnonFunctionType() {
  1900. return (this.flags & 8) > 0;
  1901. }
  1902. set noAnonFunctionType(v) {
  1903. if (v) this.flags |= 8;else this.flags &= -9;
  1904. }
  1905. get hasFlowComment() {
  1906. return (this.flags & 16) > 0;
  1907. }
  1908. set hasFlowComment(v) {
  1909. if (v) this.flags |= 16;else this.flags &= -17;
  1910. }
  1911. get isAmbientContext() {
  1912. return (this.flags & 32) > 0;
  1913. }
  1914. set isAmbientContext(v) {
  1915. if (v) this.flags |= 32;else this.flags &= -33;
  1916. }
  1917. get inAbstractClass() {
  1918. return (this.flags & 64) > 0;
  1919. }
  1920. set inAbstractClass(v) {
  1921. if (v) this.flags |= 64;else this.flags &= -65;
  1922. }
  1923. get inDisallowConditionalTypesContext() {
  1924. return (this.flags & 128) > 0;
  1925. }
  1926. set inDisallowConditionalTypesContext(v) {
  1927. if (v) this.flags |= 128;else this.flags &= -129;
  1928. }
  1929. get soloAwait() {
  1930. return (this.flags & 256) > 0;
  1931. }
  1932. set soloAwait(v) {
  1933. if (v) this.flags |= 256;else this.flags &= -257;
  1934. }
  1935. get inFSharpPipelineDirectBody() {
  1936. return (this.flags & 512) > 0;
  1937. }
  1938. set inFSharpPipelineDirectBody(v) {
  1939. if (v) this.flags |= 512;else this.flags &= -513;
  1940. }
  1941. get canStartJSXElement() {
  1942. return (this.flags & 1024) > 0;
  1943. }
  1944. set canStartJSXElement(v) {
  1945. if (v) this.flags |= 1024;else this.flags &= -1025;
  1946. }
  1947. get containsEsc() {
  1948. return (this.flags & 2048) > 0;
  1949. }
  1950. set containsEsc(v) {
  1951. if (v) this.flags |= 2048;else this.flags &= -2049;
  1952. }
  1953. get hasTopLevelAwait() {
  1954. return (this.flags & 4096) > 0;
  1955. }
  1956. set hasTopLevelAwait(v) {
  1957. if (v) this.flags |= 4096;else this.flags &= -4097;
  1958. }
  1959. curPosition() {
  1960. return new Position(this.curLine, this.pos - this.lineStart, this.pos);
  1961. }
  1962. clone() {
  1963. const state = new State();
  1964. state.flags = this.flags;
  1965. state.curLine = this.curLine;
  1966. state.lineStart = this.lineStart;
  1967. state.startLoc = this.startLoc;
  1968. state.endLoc = this.endLoc;
  1969. state.errors = this.errors.slice();
  1970. state.potentialArrowAt = this.potentialArrowAt;
  1971. state.noArrowAt = this.noArrowAt.slice();
  1972. state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();
  1973. state.topicContext = this.topicContext;
  1974. state.labels = this.labels.slice();
  1975. state.commentsLen = this.commentsLen;
  1976. state.commentStack = this.commentStack.slice();
  1977. state.pos = this.pos;
  1978. state.type = this.type;
  1979. state.value = this.value;
  1980. state.start = this.start;
  1981. state.end = this.end;
  1982. state.lastTokEndLoc = this.lastTokEndLoc;
  1983. state.lastTokStartLoc = this.lastTokStartLoc;
  1984. state.context = this.context.slice();
  1985. state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;
  1986. state.strictErrors = this.strictErrors;
  1987. state.tokensLength = this.tokensLength;
  1988. return state;
  1989. }
  1990. }
  1991. var _isDigit = function isDigit(code) {
  1992. return code >= 48 && code <= 57;
  1993. };
  1994. const forbiddenNumericSeparatorSiblings = {
  1995. decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  1996. hex: new Set([46, 88, 95, 120])
  1997. };
  1998. const isAllowedNumericSeparatorSibling = {
  1999. bin: ch => ch === 48 || ch === 49,
  2000. oct: ch => ch >= 48 && ch <= 55,
  2001. dec: ch => ch >= 48 && ch <= 57,
  2002. hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
  2003. };
  2004. function readStringContents(type, input, pos, lineStart, curLine, errors) {
  2005. const initialPos = pos;
  2006. const initialLineStart = lineStart;
  2007. const initialCurLine = curLine;
  2008. let out = "";
  2009. let firstInvalidLoc = null;
  2010. let chunkStart = pos;
  2011. const {
  2012. length
  2013. } = input;
  2014. for (;;) {
  2015. if (pos >= length) {
  2016. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  2017. out += input.slice(chunkStart, pos);
  2018. break;
  2019. }
  2020. const ch = input.charCodeAt(pos);
  2021. if (isStringEnd(type, ch, input, pos)) {
  2022. out += input.slice(chunkStart, pos);
  2023. break;
  2024. }
  2025. if (ch === 92) {
  2026. out += input.slice(chunkStart, pos);
  2027. const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors);
  2028. if (res.ch === null && !firstInvalidLoc) {
  2029. firstInvalidLoc = {
  2030. pos,
  2031. lineStart,
  2032. curLine
  2033. };
  2034. } else {
  2035. out += res.ch;
  2036. }
  2037. ({
  2038. pos,
  2039. lineStart,
  2040. curLine
  2041. } = res);
  2042. chunkStart = pos;
  2043. } else if (ch === 8232 || ch === 8233) {
  2044. ++pos;
  2045. ++curLine;
  2046. lineStart = pos;
  2047. } else if (ch === 10 || ch === 13) {
  2048. if (type === "template") {
  2049. out += input.slice(chunkStart, pos) + "\n";
  2050. ++pos;
  2051. if (ch === 13 && input.charCodeAt(pos) === 10) {
  2052. ++pos;
  2053. }
  2054. ++curLine;
  2055. chunkStart = lineStart = pos;
  2056. } else {
  2057. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  2058. }
  2059. } else {
  2060. ++pos;
  2061. }
  2062. }
  2063. return {
  2064. pos,
  2065. str: out,
  2066. firstInvalidLoc,
  2067. lineStart,
  2068. curLine,
  2069. containsInvalid: !!firstInvalidLoc
  2070. };
  2071. }
  2072. function isStringEnd(type, ch, input, pos) {
  2073. if (type === "template") {
  2074. return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123;
  2075. }
  2076. return ch === (type === "double" ? 34 : 39);
  2077. }
  2078. function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
  2079. const throwOnInvalid = !inTemplate;
  2080. pos++;
  2081. const res = ch => ({
  2082. pos,
  2083. ch,
  2084. lineStart,
  2085. curLine
  2086. });
  2087. const ch = input.charCodeAt(pos++);
  2088. switch (ch) {
  2089. case 110:
  2090. return res("\n");
  2091. case 114:
  2092. return res("\r");
  2093. case 120:
  2094. {
  2095. let code;
  2096. ({
  2097. code,
  2098. pos
  2099. } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors));
  2100. return res(code === null ? null : String.fromCharCode(code));
  2101. }
  2102. case 117:
  2103. {
  2104. let code;
  2105. ({
  2106. code,
  2107. pos
  2108. } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors));
  2109. return res(code === null ? null : String.fromCodePoint(code));
  2110. }
  2111. case 116:
  2112. return res("\t");
  2113. case 98:
  2114. return res("\b");
  2115. case 118:
  2116. return res("\u000b");
  2117. case 102:
  2118. return res("\f");
  2119. case 13:
  2120. if (input.charCodeAt(pos) === 10) {
  2121. ++pos;
  2122. }
  2123. case 10:
  2124. lineStart = pos;
  2125. ++curLine;
  2126. case 8232:
  2127. case 8233:
  2128. return res("");
  2129. case 56:
  2130. case 57:
  2131. if (inTemplate) {
  2132. return res(null);
  2133. } else {
  2134. errors.strictNumericEscape(pos - 1, lineStart, curLine);
  2135. }
  2136. default:
  2137. if (ch >= 48 && ch <= 55) {
  2138. const startPos = pos - 1;
  2139. const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
  2140. let octalStr = match[0];
  2141. let octal = parseInt(octalStr, 8);
  2142. if (octal > 255) {
  2143. octalStr = octalStr.slice(0, -1);
  2144. octal = parseInt(octalStr, 8);
  2145. }
  2146. pos += octalStr.length - 1;
  2147. const next = input.charCodeAt(pos);
  2148. if (octalStr !== "0" || next === 56 || next === 57) {
  2149. if (inTemplate) {
  2150. return res(null);
  2151. } else {
  2152. errors.strictNumericEscape(startPos, lineStart, curLine);
  2153. }
  2154. }
  2155. return res(String.fromCharCode(octal));
  2156. }
  2157. return res(String.fromCharCode(ch));
  2158. }
  2159. }
  2160. function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) {
  2161. const initialPos = pos;
  2162. let n;
  2163. ({
  2164. n,
  2165. pos
  2166. } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid));
  2167. if (n === null) {
  2168. if (throwOnInvalid) {
  2169. errors.invalidEscapeSequence(initialPos, lineStart, curLine);
  2170. } else {
  2171. pos = initialPos - 1;
  2172. }
  2173. }
  2174. return {
  2175. code: n,
  2176. pos
  2177. };
  2178. }
  2179. function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) {
  2180. const start = pos;
  2181. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  2182. const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  2183. let invalid = false;
  2184. let total = 0;
  2185. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  2186. const code = input.charCodeAt(pos);
  2187. let val;
  2188. if (code === 95 && allowNumSeparator !== "bail") {
  2189. const prev = input.charCodeAt(pos - 1);
  2190. const next = input.charCodeAt(pos + 1);
  2191. if (!allowNumSeparator) {
  2192. if (bailOnError) return {
  2193. n: null,
  2194. pos
  2195. };
  2196. errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
  2197. } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
  2198. if (bailOnError) return {
  2199. n: null,
  2200. pos
  2201. };
  2202. errors.unexpectedNumericSeparator(pos, lineStart, curLine);
  2203. }
  2204. ++pos;
  2205. continue;
  2206. }
  2207. if (code >= 97) {
  2208. val = code - 97 + 10;
  2209. } else if (code >= 65) {
  2210. val = code - 65 + 10;
  2211. } else if (_isDigit(code)) {
  2212. val = code - 48;
  2213. } else {
  2214. val = Infinity;
  2215. }
  2216. if (val >= radix) {
  2217. if (val <= 9 && bailOnError) {
  2218. return {
  2219. n: null,
  2220. pos
  2221. };
  2222. } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
  2223. val = 0;
  2224. } else if (forceLen) {
  2225. val = 0;
  2226. invalid = true;
  2227. } else {
  2228. break;
  2229. }
  2230. }
  2231. ++pos;
  2232. total = total * radix + val;
  2233. }
  2234. if (pos === start || len != null && pos - start !== len || invalid) {
  2235. return {
  2236. n: null,
  2237. pos
  2238. };
  2239. }
  2240. return {
  2241. n: total,
  2242. pos
  2243. };
  2244. }
  2245. function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) {
  2246. const ch = input.charCodeAt(pos);
  2247. let code;
  2248. if (ch === 123) {
  2249. ++pos;
  2250. ({
  2251. code,
  2252. pos
  2253. } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors));
  2254. ++pos;
  2255. if (code !== null && code > 0x10ffff) {
  2256. if (throwOnInvalid) {
  2257. errors.invalidCodePoint(pos, lineStart, curLine);
  2258. } else {
  2259. return {
  2260. code: null,
  2261. pos
  2262. };
  2263. }
  2264. }
  2265. } else {
  2266. ({
  2267. code,
  2268. pos
  2269. } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors));
  2270. }
  2271. return {
  2272. code,
  2273. pos
  2274. };
  2275. }
  2276. function buildPosition(pos, lineStart, curLine) {
  2277. return new Position(curLine, pos - lineStart, pos);
  2278. }
  2279. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]);
  2280. class Token {
  2281. constructor(state) {
  2282. this.type = state.type;
  2283. this.value = state.value;
  2284. this.start = state.start;
  2285. this.end = state.end;
  2286. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2287. }
  2288. }
  2289. class Tokenizer extends CommentsParser {
  2290. constructor(options, input) {
  2291. super();
  2292. this.isLookahead = void 0;
  2293. this.tokens = [];
  2294. this.errorHandlers_readInt = {
  2295. invalidDigit: (pos, lineStart, curLine, radix) => {
  2296. if (!this.options.errorRecovery) return false;
  2297. this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), {
  2298. radix
  2299. });
  2300. return true;
  2301. },
  2302. numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
  2303. unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
  2304. };
  2305. this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
  2306. invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
  2307. invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
  2308. });
  2309. this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
  2310. strictNumericEscape: (pos, lineStart, curLine) => {
  2311. this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine));
  2312. },
  2313. unterminated: (pos, lineStart, curLine) => {
  2314. throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine));
  2315. }
  2316. });
  2317. this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
  2318. strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
  2319. unterminated: (pos, lineStart, curLine) => {
  2320. throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine));
  2321. }
  2322. });
  2323. this.state = new State();
  2324. this.state.init(options);
  2325. this.input = input;
  2326. this.length = input.length;
  2327. this.comments = [];
  2328. this.isLookahead = false;
  2329. }
  2330. pushToken(token) {
  2331. this.tokens.length = this.state.tokensLength;
  2332. this.tokens.push(token);
  2333. ++this.state.tokensLength;
  2334. }
  2335. next() {
  2336. this.checkKeywordEscapes();
  2337. if (this.options.tokens) {
  2338. this.pushToken(new Token(this.state));
  2339. }
  2340. this.state.lastTokEndLoc = this.state.endLoc;
  2341. this.state.lastTokStartLoc = this.state.startLoc;
  2342. this.nextToken();
  2343. }
  2344. eat(type) {
  2345. if (this.match(type)) {
  2346. this.next();
  2347. return true;
  2348. } else {
  2349. return false;
  2350. }
  2351. }
  2352. match(type) {
  2353. return this.state.type === type;
  2354. }
  2355. createLookaheadState(state) {
  2356. return {
  2357. pos: state.pos,
  2358. value: null,
  2359. type: state.type,
  2360. start: state.start,
  2361. end: state.end,
  2362. context: [this.curContext()],
  2363. inType: state.inType,
  2364. startLoc: state.startLoc,
  2365. lastTokEndLoc: state.lastTokEndLoc,
  2366. curLine: state.curLine,
  2367. lineStart: state.lineStart,
  2368. curPosition: state.curPosition
  2369. };
  2370. }
  2371. lookahead() {
  2372. const old = this.state;
  2373. this.state = this.createLookaheadState(old);
  2374. this.isLookahead = true;
  2375. this.nextToken();
  2376. this.isLookahead = false;
  2377. const curr = this.state;
  2378. this.state = old;
  2379. return curr;
  2380. }
  2381. nextTokenStart() {
  2382. return this.nextTokenStartSince(this.state.pos);
  2383. }
  2384. nextTokenStartSince(pos) {
  2385. skipWhiteSpace.lastIndex = pos;
  2386. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2387. }
  2388. lookaheadCharCode() {
  2389. return this.input.charCodeAt(this.nextTokenStart());
  2390. }
  2391. nextTokenInLineStart() {
  2392. return this.nextTokenInLineStartSince(this.state.pos);
  2393. }
  2394. nextTokenInLineStartSince(pos) {
  2395. skipWhiteSpaceInLine.lastIndex = pos;
  2396. return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos;
  2397. }
  2398. lookaheadInLineCharCode() {
  2399. return this.input.charCodeAt(this.nextTokenInLineStart());
  2400. }
  2401. codePointAtPos(pos) {
  2402. let cp = this.input.charCodeAt(pos);
  2403. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2404. const trail = this.input.charCodeAt(pos);
  2405. if ((trail & 0xfc00) === 0xdc00) {
  2406. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2407. }
  2408. }
  2409. return cp;
  2410. }
  2411. setStrict(strict) {
  2412. this.state.strict = strict;
  2413. if (strict) {
  2414. this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at));
  2415. this.state.strictErrors.clear();
  2416. }
  2417. }
  2418. curContext() {
  2419. return this.state.context[this.state.context.length - 1];
  2420. }
  2421. nextToken() {
  2422. this.skipSpace();
  2423. this.state.start = this.state.pos;
  2424. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2425. if (this.state.pos >= this.length) {
  2426. this.finishToken(139);
  2427. return;
  2428. }
  2429. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2430. }
  2431. skipBlockComment(commentEnd) {
  2432. let startLoc;
  2433. if (!this.isLookahead) startLoc = this.state.curPosition();
  2434. const start = this.state.pos;
  2435. const end = this.input.indexOf(commentEnd, start + 2);
  2436. if (end === -1) {
  2437. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  2438. }
  2439. this.state.pos = end + commentEnd.length;
  2440. lineBreakG.lastIndex = start + 2;
  2441. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2442. ++this.state.curLine;
  2443. this.state.lineStart = lineBreakG.lastIndex;
  2444. }
  2445. if (this.isLookahead) return;
  2446. const comment = {
  2447. type: "CommentBlock",
  2448. value: this.input.slice(start + 2, end),
  2449. start,
  2450. end: end + commentEnd.length,
  2451. loc: new SourceLocation(startLoc, this.state.curPosition())
  2452. };
  2453. if (this.options.tokens) this.pushToken(comment);
  2454. return comment;
  2455. }
  2456. skipLineComment(startSkip) {
  2457. const start = this.state.pos;
  2458. let startLoc;
  2459. if (!this.isLookahead) startLoc = this.state.curPosition();
  2460. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2461. if (this.state.pos < this.length) {
  2462. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2463. ch = this.input.charCodeAt(this.state.pos);
  2464. }
  2465. }
  2466. if (this.isLookahead) return;
  2467. const end = this.state.pos;
  2468. const value = this.input.slice(start + startSkip, end);
  2469. const comment = {
  2470. type: "CommentLine",
  2471. value,
  2472. start,
  2473. end,
  2474. loc: new SourceLocation(startLoc, this.state.curPosition())
  2475. };
  2476. if (this.options.tokens) this.pushToken(comment);
  2477. return comment;
  2478. }
  2479. skipSpace() {
  2480. const spaceStart = this.state.pos;
  2481. const comments = [];
  2482. loop: while (this.state.pos < this.length) {
  2483. const ch = this.input.charCodeAt(this.state.pos);
  2484. switch (ch) {
  2485. case 32:
  2486. case 160:
  2487. case 9:
  2488. ++this.state.pos;
  2489. break;
  2490. case 13:
  2491. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2492. ++this.state.pos;
  2493. }
  2494. case 10:
  2495. case 8232:
  2496. case 8233:
  2497. ++this.state.pos;
  2498. ++this.state.curLine;
  2499. this.state.lineStart = this.state.pos;
  2500. break;
  2501. case 47:
  2502. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2503. case 42:
  2504. {
  2505. const comment = this.skipBlockComment("*/");
  2506. if (comment !== undefined) {
  2507. this.addComment(comment);
  2508. if (this.options.attachComment) comments.push(comment);
  2509. }
  2510. break;
  2511. }
  2512. case 47:
  2513. {
  2514. const comment = this.skipLineComment(2);
  2515. if (comment !== undefined) {
  2516. this.addComment(comment);
  2517. if (this.options.attachComment) comments.push(comment);
  2518. }
  2519. break;
  2520. }
  2521. default:
  2522. break loop;
  2523. }
  2524. break;
  2525. default:
  2526. if (isWhitespace(ch)) {
  2527. ++this.state.pos;
  2528. } else if (ch === 45 && !this.inModule && this.options.annexB) {
  2529. const pos = this.state.pos;
  2530. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2531. const comment = this.skipLineComment(3);
  2532. if (comment !== undefined) {
  2533. this.addComment(comment);
  2534. if (this.options.attachComment) comments.push(comment);
  2535. }
  2536. } else {
  2537. break loop;
  2538. }
  2539. } else if (ch === 60 && !this.inModule && this.options.annexB) {
  2540. const pos = this.state.pos;
  2541. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2542. const comment = this.skipLineComment(4);
  2543. if (comment !== undefined) {
  2544. this.addComment(comment);
  2545. if (this.options.attachComment) comments.push(comment);
  2546. }
  2547. } else {
  2548. break loop;
  2549. }
  2550. } else {
  2551. break loop;
  2552. }
  2553. }
  2554. }
  2555. if (comments.length > 0) {
  2556. const end = this.state.pos;
  2557. const commentWhitespace = {
  2558. start: spaceStart,
  2559. end,
  2560. comments,
  2561. leadingNode: null,
  2562. trailingNode: null,
  2563. containingNode: null
  2564. };
  2565. this.state.commentStack.push(commentWhitespace);
  2566. }
  2567. }
  2568. finishToken(type, val) {
  2569. this.state.end = this.state.pos;
  2570. this.state.endLoc = this.state.curPosition();
  2571. const prevType = this.state.type;
  2572. this.state.type = type;
  2573. this.state.value = val;
  2574. if (!this.isLookahead) {
  2575. this.updateContext(prevType);
  2576. }
  2577. }
  2578. replaceToken(type) {
  2579. this.state.type = type;
  2580. this.updateContext();
  2581. }
  2582. readToken_numberSign() {
  2583. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2584. return;
  2585. }
  2586. const nextPos = this.state.pos + 1;
  2587. const next = this.codePointAtPos(nextPos);
  2588. if (next >= 48 && next <= 57) {
  2589. throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition());
  2590. }
  2591. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2592. this.expectPlugin("recordAndTuple");
  2593. if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
  2594. throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition());
  2595. }
  2596. this.state.pos += 2;
  2597. if (next === 123) {
  2598. this.finishToken(7);
  2599. } else {
  2600. this.finishToken(1);
  2601. }
  2602. } else if (isIdentifierStart(next)) {
  2603. ++this.state.pos;
  2604. this.finishToken(138, this.readWord1(next));
  2605. } else if (next === 92) {
  2606. ++this.state.pos;
  2607. this.finishToken(138, this.readWord1());
  2608. } else {
  2609. this.finishOp(27, 1);
  2610. }
  2611. }
  2612. readToken_dot() {
  2613. const next = this.input.charCodeAt(this.state.pos + 1);
  2614. if (next >= 48 && next <= 57) {
  2615. this.readNumber(true);
  2616. return;
  2617. }
  2618. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2619. this.state.pos += 3;
  2620. this.finishToken(21);
  2621. } else {
  2622. ++this.state.pos;
  2623. this.finishToken(16);
  2624. }
  2625. }
  2626. readToken_slash() {
  2627. const next = this.input.charCodeAt(this.state.pos + 1);
  2628. if (next === 61) {
  2629. this.finishOp(31, 2);
  2630. } else {
  2631. this.finishOp(56, 1);
  2632. }
  2633. }
  2634. readToken_interpreter() {
  2635. if (this.state.pos !== 0 || this.length < 2) return false;
  2636. let ch = this.input.charCodeAt(this.state.pos + 1);
  2637. if (ch !== 33) return false;
  2638. const start = this.state.pos;
  2639. this.state.pos += 1;
  2640. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2641. ch = this.input.charCodeAt(this.state.pos);
  2642. }
  2643. const value = this.input.slice(start + 2, this.state.pos);
  2644. this.finishToken(28, value);
  2645. return true;
  2646. }
  2647. readToken_mult_modulo(code) {
  2648. let type = code === 42 ? 55 : 54;
  2649. let width = 1;
  2650. let next = this.input.charCodeAt(this.state.pos + 1);
  2651. if (code === 42 && next === 42) {
  2652. width++;
  2653. next = this.input.charCodeAt(this.state.pos + 2);
  2654. type = 57;
  2655. }
  2656. if (next === 61 && !this.state.inType) {
  2657. width++;
  2658. type = code === 37 ? 33 : 30;
  2659. }
  2660. this.finishOp(type, width);
  2661. }
  2662. readToken_pipe_amp(code) {
  2663. const next = this.input.charCodeAt(this.state.pos + 1);
  2664. if (next === code) {
  2665. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2666. this.finishOp(30, 3);
  2667. } else {
  2668. this.finishOp(code === 124 ? 41 : 42, 2);
  2669. }
  2670. return;
  2671. }
  2672. if (code === 124) {
  2673. if (next === 62) {
  2674. this.finishOp(39, 2);
  2675. return;
  2676. }
  2677. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2678. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2679. throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  2680. }
  2681. this.state.pos += 2;
  2682. this.finishToken(9);
  2683. return;
  2684. }
  2685. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2686. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2687. throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  2688. }
  2689. this.state.pos += 2;
  2690. this.finishToken(4);
  2691. return;
  2692. }
  2693. }
  2694. if (next === 61) {
  2695. this.finishOp(30, 2);
  2696. return;
  2697. }
  2698. this.finishOp(code === 124 ? 43 : 45, 1);
  2699. }
  2700. readToken_caret() {
  2701. const next = this.input.charCodeAt(this.state.pos + 1);
  2702. if (next === 61 && !this.state.inType) {
  2703. this.finishOp(32, 2);
  2704. } else if (next === 94 && this.hasPlugin(["pipelineOperator", {
  2705. proposal: "hack",
  2706. topicToken: "^^"
  2707. }])) {
  2708. this.finishOp(37, 2);
  2709. const lookaheadCh = this.input.codePointAt(this.state.pos);
  2710. if (lookaheadCh === 94) {
  2711. this.unexpected();
  2712. }
  2713. } else {
  2714. this.finishOp(44, 1);
  2715. }
  2716. }
  2717. readToken_atSign() {
  2718. const next = this.input.charCodeAt(this.state.pos + 1);
  2719. if (next === 64 && this.hasPlugin(["pipelineOperator", {
  2720. proposal: "hack",
  2721. topicToken: "@@"
  2722. }])) {
  2723. this.finishOp(38, 2);
  2724. } else {
  2725. this.finishOp(26, 1);
  2726. }
  2727. }
  2728. readToken_plus_min(code) {
  2729. const next = this.input.charCodeAt(this.state.pos + 1);
  2730. if (next === code) {
  2731. this.finishOp(34, 2);
  2732. return;
  2733. }
  2734. if (next === 61) {
  2735. this.finishOp(30, 2);
  2736. } else {
  2737. this.finishOp(53, 1);
  2738. }
  2739. }
  2740. readToken_lt() {
  2741. const {
  2742. pos
  2743. } = this.state;
  2744. const next = this.input.charCodeAt(pos + 1);
  2745. if (next === 60) {
  2746. if (this.input.charCodeAt(pos + 2) === 61) {
  2747. this.finishOp(30, 3);
  2748. return;
  2749. }
  2750. this.finishOp(51, 2);
  2751. return;
  2752. }
  2753. if (next === 61) {
  2754. this.finishOp(49, 2);
  2755. return;
  2756. }
  2757. this.finishOp(47, 1);
  2758. }
  2759. readToken_gt() {
  2760. const {
  2761. pos
  2762. } = this.state;
  2763. const next = this.input.charCodeAt(pos + 1);
  2764. if (next === 62) {
  2765. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2766. if (this.input.charCodeAt(pos + size) === 61) {
  2767. this.finishOp(30, size + 1);
  2768. return;
  2769. }
  2770. this.finishOp(52, size);
  2771. return;
  2772. }
  2773. if (next === 61) {
  2774. this.finishOp(49, 2);
  2775. return;
  2776. }
  2777. this.finishOp(48, 1);
  2778. }
  2779. readToken_eq_excl(code) {
  2780. const next = this.input.charCodeAt(this.state.pos + 1);
  2781. if (next === 61) {
  2782. this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2783. return;
  2784. }
  2785. if (code === 61 && next === 62) {
  2786. this.state.pos += 2;
  2787. this.finishToken(19);
  2788. return;
  2789. }
  2790. this.finishOp(code === 61 ? 29 : 35, 1);
  2791. }
  2792. readToken_question() {
  2793. const next = this.input.charCodeAt(this.state.pos + 1);
  2794. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2795. if (next === 63) {
  2796. if (next2 === 61) {
  2797. this.finishOp(30, 3);
  2798. } else {
  2799. this.finishOp(40, 2);
  2800. }
  2801. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2802. this.state.pos += 2;
  2803. this.finishToken(18);
  2804. } else {
  2805. ++this.state.pos;
  2806. this.finishToken(17);
  2807. }
  2808. }
  2809. getTokenFromCode(code) {
  2810. switch (code) {
  2811. case 46:
  2812. this.readToken_dot();
  2813. return;
  2814. case 40:
  2815. ++this.state.pos;
  2816. this.finishToken(10);
  2817. return;
  2818. case 41:
  2819. ++this.state.pos;
  2820. this.finishToken(11);
  2821. return;
  2822. case 59:
  2823. ++this.state.pos;
  2824. this.finishToken(13);
  2825. return;
  2826. case 44:
  2827. ++this.state.pos;
  2828. this.finishToken(12);
  2829. return;
  2830. case 91:
  2831. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2832. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2833. throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  2834. }
  2835. this.state.pos += 2;
  2836. this.finishToken(2);
  2837. } else {
  2838. ++this.state.pos;
  2839. this.finishToken(0);
  2840. }
  2841. return;
  2842. case 93:
  2843. ++this.state.pos;
  2844. this.finishToken(3);
  2845. return;
  2846. case 123:
  2847. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2848. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2849. throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  2850. }
  2851. this.state.pos += 2;
  2852. this.finishToken(6);
  2853. } else {
  2854. ++this.state.pos;
  2855. this.finishToken(5);
  2856. }
  2857. return;
  2858. case 125:
  2859. ++this.state.pos;
  2860. this.finishToken(8);
  2861. return;
  2862. case 58:
  2863. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  2864. this.finishOp(15, 2);
  2865. } else {
  2866. ++this.state.pos;
  2867. this.finishToken(14);
  2868. }
  2869. return;
  2870. case 63:
  2871. this.readToken_question();
  2872. return;
  2873. case 96:
  2874. this.readTemplateToken();
  2875. return;
  2876. case 48:
  2877. {
  2878. const next = this.input.charCodeAt(this.state.pos + 1);
  2879. if (next === 120 || next === 88) {
  2880. this.readRadixNumber(16);
  2881. return;
  2882. }
  2883. if (next === 111 || next === 79) {
  2884. this.readRadixNumber(8);
  2885. return;
  2886. }
  2887. if (next === 98 || next === 66) {
  2888. this.readRadixNumber(2);
  2889. return;
  2890. }
  2891. }
  2892. case 49:
  2893. case 50:
  2894. case 51:
  2895. case 52:
  2896. case 53:
  2897. case 54:
  2898. case 55:
  2899. case 56:
  2900. case 57:
  2901. this.readNumber(false);
  2902. return;
  2903. case 34:
  2904. case 39:
  2905. this.readString(code);
  2906. return;
  2907. case 47:
  2908. this.readToken_slash();
  2909. return;
  2910. case 37:
  2911. case 42:
  2912. this.readToken_mult_modulo(code);
  2913. return;
  2914. case 124:
  2915. case 38:
  2916. this.readToken_pipe_amp(code);
  2917. return;
  2918. case 94:
  2919. this.readToken_caret();
  2920. return;
  2921. case 43:
  2922. case 45:
  2923. this.readToken_plus_min(code);
  2924. return;
  2925. case 60:
  2926. this.readToken_lt();
  2927. return;
  2928. case 62:
  2929. this.readToken_gt();
  2930. return;
  2931. case 61:
  2932. case 33:
  2933. this.readToken_eq_excl(code);
  2934. return;
  2935. case 126:
  2936. this.finishOp(36, 1);
  2937. return;
  2938. case 64:
  2939. this.readToken_atSign();
  2940. return;
  2941. case 35:
  2942. this.readToken_numberSign();
  2943. return;
  2944. case 92:
  2945. this.readWord();
  2946. return;
  2947. default:
  2948. if (isIdentifierStart(code)) {
  2949. this.readWord(code);
  2950. return;
  2951. }
  2952. }
  2953. throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), {
  2954. unexpected: String.fromCodePoint(code)
  2955. });
  2956. }
  2957. finishOp(type, size) {
  2958. const str = this.input.slice(this.state.pos, this.state.pos + size);
  2959. this.state.pos += size;
  2960. this.finishToken(type, str);
  2961. }
  2962. readRegexp() {
  2963. const startLoc = this.state.startLoc;
  2964. const start = this.state.start + 1;
  2965. let escaped, inClass;
  2966. let {
  2967. pos
  2968. } = this.state;
  2969. for (;; ++pos) {
  2970. if (pos >= this.length) {
  2971. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  2972. }
  2973. const ch = this.input.charCodeAt(pos);
  2974. if (isNewLine(ch)) {
  2975. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  2976. }
  2977. if (escaped) {
  2978. escaped = false;
  2979. } else {
  2980. if (ch === 91) {
  2981. inClass = true;
  2982. } else if (ch === 93 && inClass) {
  2983. inClass = false;
  2984. } else if (ch === 47 && !inClass) {
  2985. break;
  2986. }
  2987. escaped = ch === 92;
  2988. }
  2989. }
  2990. const content = this.input.slice(start, pos);
  2991. ++pos;
  2992. let mods = "";
  2993. const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start);
  2994. while (pos < this.length) {
  2995. const cp = this.codePointAtPos(pos);
  2996. const char = String.fromCharCode(cp);
  2997. if (VALID_REGEX_FLAGS.has(cp)) {
  2998. if (cp === 118) {
  2999. if (mods.includes("u")) {
  3000. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  3001. }
  3002. } else if (cp === 117) {
  3003. if (mods.includes("v")) {
  3004. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  3005. }
  3006. }
  3007. if (mods.includes(char)) {
  3008. this.raise(Errors.DuplicateRegExpFlags, nextPos());
  3009. }
  3010. } else if (isIdentifierChar(cp) || cp === 92) {
  3011. this.raise(Errors.MalformedRegExpFlags, nextPos());
  3012. } else {
  3013. break;
  3014. }
  3015. ++pos;
  3016. mods += char;
  3017. }
  3018. this.state.pos = pos;
  3019. this.finishToken(137, {
  3020. pattern: content,
  3021. flags: mods
  3022. });
  3023. }
  3024. readInt(radix, len, forceLen = false, allowNumSeparator = true) {
  3025. const {
  3026. n,
  3027. pos
  3028. } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
  3029. this.state.pos = pos;
  3030. return n;
  3031. }
  3032. readRadixNumber(radix) {
  3033. const startLoc = this.state.curPosition();
  3034. let isBigInt = false;
  3035. this.state.pos += 2;
  3036. const val = this.readInt(radix);
  3037. if (val == null) {
  3038. this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), {
  3039. radix
  3040. });
  3041. }
  3042. const next = this.input.charCodeAt(this.state.pos);
  3043. if (next === 110) {
  3044. ++this.state.pos;
  3045. isBigInt = true;
  3046. } else if (next === 109) {
  3047. throw this.raise(Errors.InvalidDecimal, startLoc);
  3048. }
  3049. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3050. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  3051. }
  3052. if (isBigInt) {
  3053. const str = this.input.slice(startLoc.index, this.state.pos).replace(/[_n]/g, "");
  3054. this.finishToken(135, str);
  3055. return;
  3056. }
  3057. this.finishToken(134, val);
  3058. }
  3059. readNumber(startsWithDot) {
  3060. const start = this.state.pos;
  3061. const startLoc = this.state.curPosition();
  3062. let isFloat = false;
  3063. let isBigInt = false;
  3064. let isDecimal = false;
  3065. let hasExponent = false;
  3066. let isOctal = false;
  3067. if (!startsWithDot && this.readInt(10) === null) {
  3068. this.raise(Errors.InvalidNumber, this.state.curPosition());
  3069. }
  3070. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3071. if (hasLeadingZero) {
  3072. const integer = this.input.slice(start, this.state.pos);
  3073. this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc);
  3074. if (!this.state.strict) {
  3075. const underscorePos = integer.indexOf("_");
  3076. if (underscorePos > 0) {
  3077. this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos));
  3078. }
  3079. }
  3080. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3081. }
  3082. let next = this.input.charCodeAt(this.state.pos);
  3083. if (next === 46 && !isOctal) {
  3084. ++this.state.pos;
  3085. this.readInt(10);
  3086. isFloat = true;
  3087. next = this.input.charCodeAt(this.state.pos);
  3088. }
  3089. if ((next === 69 || next === 101) && !isOctal) {
  3090. next = this.input.charCodeAt(++this.state.pos);
  3091. if (next === 43 || next === 45) {
  3092. ++this.state.pos;
  3093. }
  3094. if (this.readInt(10) === null) {
  3095. this.raise(Errors.InvalidOrMissingExponent, startLoc);
  3096. }
  3097. isFloat = true;
  3098. hasExponent = true;
  3099. next = this.input.charCodeAt(this.state.pos);
  3100. }
  3101. if (next === 110) {
  3102. if (isFloat || hasLeadingZero) {
  3103. this.raise(Errors.InvalidBigIntLiteral, startLoc);
  3104. }
  3105. ++this.state.pos;
  3106. isBigInt = true;
  3107. }
  3108. if (next === 109) {
  3109. this.expectPlugin("decimal", this.state.curPosition());
  3110. if (hasExponent || hasLeadingZero) {
  3111. this.raise(Errors.InvalidDecimal, startLoc);
  3112. }
  3113. ++this.state.pos;
  3114. isDecimal = true;
  3115. }
  3116. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3117. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  3118. }
  3119. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3120. if (isBigInt) {
  3121. this.finishToken(135, str);
  3122. return;
  3123. }
  3124. if (isDecimal) {
  3125. this.finishToken(136, str);
  3126. return;
  3127. }
  3128. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3129. this.finishToken(134, val);
  3130. }
  3131. readCodePoint(throwOnInvalid) {
  3132. const {
  3133. code,
  3134. pos
  3135. } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
  3136. this.state.pos = pos;
  3137. return code;
  3138. }
  3139. readString(quote) {
  3140. const {
  3141. str,
  3142. pos,
  3143. curLine,
  3144. lineStart
  3145. } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
  3146. this.state.pos = pos + 1;
  3147. this.state.lineStart = lineStart;
  3148. this.state.curLine = curLine;
  3149. this.finishToken(133, str);
  3150. }
  3151. readTemplateContinuation() {
  3152. if (!this.match(8)) {
  3153. this.unexpected(null, 8);
  3154. }
  3155. this.state.pos--;
  3156. this.readTemplateToken();
  3157. }
  3158. readTemplateToken() {
  3159. const opening = this.input[this.state.pos];
  3160. const {
  3161. str,
  3162. firstInvalidLoc,
  3163. pos,
  3164. curLine,
  3165. lineStart
  3166. } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
  3167. this.state.pos = pos + 1;
  3168. this.state.lineStart = lineStart;
  3169. this.state.curLine = curLine;
  3170. if (firstInvalidLoc) {
  3171. this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, firstInvalidLoc.pos);
  3172. }
  3173. if (this.input.codePointAt(pos) === 96) {
  3174. this.finishToken(24, firstInvalidLoc ? null : opening + str + "`");
  3175. } else {
  3176. this.state.pos++;
  3177. this.finishToken(25, firstInvalidLoc ? null : opening + str + "${");
  3178. }
  3179. }
  3180. recordStrictModeErrors(toParseError, at) {
  3181. const index = at.index;
  3182. if (this.state.strict && !this.state.strictErrors.has(index)) {
  3183. this.raise(toParseError, at);
  3184. } else {
  3185. this.state.strictErrors.set(index, [toParseError, at]);
  3186. }
  3187. }
  3188. readWord1(firstCode) {
  3189. this.state.containsEsc = false;
  3190. let word = "";
  3191. const start = this.state.pos;
  3192. let chunkStart = this.state.pos;
  3193. if (firstCode !== undefined) {
  3194. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3195. }
  3196. while (this.state.pos < this.length) {
  3197. const ch = this.codePointAtPos(this.state.pos);
  3198. if (isIdentifierChar(ch)) {
  3199. this.state.pos += ch <= 0xffff ? 1 : 2;
  3200. } else if (ch === 92) {
  3201. this.state.containsEsc = true;
  3202. word += this.input.slice(chunkStart, this.state.pos);
  3203. const escStart = this.state.curPosition();
  3204. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3205. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3206. this.raise(Errors.MissingUnicodeEscape, this.state.curPosition());
  3207. chunkStart = this.state.pos - 1;
  3208. continue;
  3209. }
  3210. ++this.state.pos;
  3211. const esc = this.readCodePoint(true);
  3212. if (esc !== null) {
  3213. if (!identifierCheck(esc)) {
  3214. this.raise(Errors.EscapedCharNotAnIdentifier, escStart);
  3215. }
  3216. word += String.fromCodePoint(esc);
  3217. }
  3218. chunkStart = this.state.pos;
  3219. } else {
  3220. break;
  3221. }
  3222. }
  3223. return word + this.input.slice(chunkStart, this.state.pos);
  3224. }
  3225. readWord(firstCode) {
  3226. const word = this.readWord1(firstCode);
  3227. const type = keywords$1.get(word);
  3228. if (type !== undefined) {
  3229. this.finishToken(type, tokenLabelName(type));
  3230. } else {
  3231. this.finishToken(132, word);
  3232. }
  3233. }
  3234. checkKeywordEscapes() {
  3235. const {
  3236. type
  3237. } = this.state;
  3238. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3239. this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, {
  3240. reservedWord: tokenLabelName(type)
  3241. });
  3242. }
  3243. }
  3244. raise(toParseError, at, details = {}) {
  3245. const loc = at instanceof Position ? at : at.loc.start;
  3246. const error = toParseError(loc, details);
  3247. if (!this.options.errorRecovery) throw error;
  3248. if (!this.isLookahead) this.state.errors.push(error);
  3249. return error;
  3250. }
  3251. raiseOverwrite(toParseError, at, details = {}) {
  3252. const loc = at instanceof Position ? at : at.loc.start;
  3253. const pos = loc.index;
  3254. const errors = this.state.errors;
  3255. for (let i = errors.length - 1; i >= 0; i--) {
  3256. const error = errors[i];
  3257. if (error.loc.index === pos) {
  3258. return errors[i] = toParseError(loc, details);
  3259. }
  3260. if (error.loc.index < pos) break;
  3261. }
  3262. return this.raise(toParseError, at, details);
  3263. }
  3264. updateContext(prevType) {}
  3265. unexpected(loc, type) {
  3266. throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, {
  3267. expected: type ? tokenLabelName(type) : null
  3268. });
  3269. }
  3270. expectPlugin(pluginName, loc) {
  3271. if (this.hasPlugin(pluginName)) {
  3272. return true;
  3273. }
  3274. throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, {
  3275. missingPlugin: [pluginName]
  3276. });
  3277. }
  3278. expectOnePlugin(pluginNames) {
  3279. if (!pluginNames.some(name => this.hasPlugin(name))) {
  3280. throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, {
  3281. missingPlugin: pluginNames
  3282. });
  3283. }
  3284. }
  3285. errorBuilder(error) {
  3286. return (pos, lineStart, curLine) => {
  3287. this.raise(error, buildPosition(pos, lineStart, curLine));
  3288. };
  3289. }
  3290. }
  3291. class ClassScope {
  3292. constructor() {
  3293. this.privateNames = new Set();
  3294. this.loneAccessors = new Map();
  3295. this.undefinedPrivateNames = new Map();
  3296. }
  3297. }
  3298. class ClassScopeHandler {
  3299. constructor(parser) {
  3300. this.parser = void 0;
  3301. this.stack = [];
  3302. this.undefinedPrivateNames = new Map();
  3303. this.parser = parser;
  3304. }
  3305. current() {
  3306. return this.stack[this.stack.length - 1];
  3307. }
  3308. enter() {
  3309. this.stack.push(new ClassScope());
  3310. }
  3311. exit() {
  3312. const oldClassScope = this.stack.pop();
  3313. const current = this.current();
  3314. for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3315. if (current) {
  3316. if (!current.undefinedPrivateNames.has(name)) {
  3317. current.undefinedPrivateNames.set(name, loc);
  3318. }
  3319. } else {
  3320. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  3321. identifierName: name
  3322. });
  3323. }
  3324. }
  3325. }
  3326. declarePrivateName(name, elementType, loc) {
  3327. const {
  3328. privateNames,
  3329. loneAccessors,
  3330. undefinedPrivateNames
  3331. } = this.current();
  3332. let redefined = privateNames.has(name);
  3333. if (elementType & 3) {
  3334. const accessor = redefined && loneAccessors.get(name);
  3335. if (accessor) {
  3336. const oldStatic = accessor & 4;
  3337. const newStatic = elementType & 4;
  3338. const oldKind = accessor & 3;
  3339. const newKind = elementType & 3;
  3340. redefined = oldKind === newKind || oldStatic !== newStatic;
  3341. if (!redefined) loneAccessors.delete(name);
  3342. } else if (!redefined) {
  3343. loneAccessors.set(name, elementType);
  3344. }
  3345. }
  3346. if (redefined) {
  3347. this.parser.raise(Errors.PrivateNameRedeclaration, loc, {
  3348. identifierName: name
  3349. });
  3350. }
  3351. privateNames.add(name);
  3352. undefinedPrivateNames.delete(name);
  3353. }
  3354. usePrivateName(name, loc) {
  3355. let classScope;
  3356. for (classScope of this.stack) {
  3357. if (classScope.privateNames.has(name)) return;
  3358. }
  3359. if (classScope) {
  3360. classScope.undefinedPrivateNames.set(name, loc);
  3361. } else {
  3362. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  3363. identifierName: name
  3364. });
  3365. }
  3366. }
  3367. }
  3368. class ExpressionScope {
  3369. constructor(type = 0) {
  3370. this.type = type;
  3371. }
  3372. canBeArrowParameterDeclaration() {
  3373. return this.type === 2 || this.type === 1;
  3374. }
  3375. isCertainlyParameterDeclaration() {
  3376. return this.type === 3;
  3377. }
  3378. }
  3379. class ArrowHeadParsingScope extends ExpressionScope {
  3380. constructor(type) {
  3381. super(type);
  3382. this.declarationErrors = new Map();
  3383. }
  3384. recordDeclarationError(ParsingErrorClass, at) {
  3385. const index = at.index;
  3386. this.declarationErrors.set(index, [ParsingErrorClass, at]);
  3387. }
  3388. clearDeclarationError(index) {
  3389. this.declarationErrors.delete(index);
  3390. }
  3391. iterateErrors(iterator) {
  3392. this.declarationErrors.forEach(iterator);
  3393. }
  3394. }
  3395. class ExpressionScopeHandler {
  3396. constructor(parser) {
  3397. this.parser = void 0;
  3398. this.stack = [new ExpressionScope()];
  3399. this.parser = parser;
  3400. }
  3401. enter(scope) {
  3402. this.stack.push(scope);
  3403. }
  3404. exit() {
  3405. this.stack.pop();
  3406. }
  3407. recordParameterInitializerError(toParseError, node) {
  3408. const origin = node.loc.start;
  3409. const {
  3410. stack
  3411. } = this;
  3412. let i = stack.length - 1;
  3413. let scope = stack[i];
  3414. while (!scope.isCertainlyParameterDeclaration()) {
  3415. if (scope.canBeArrowParameterDeclaration()) {
  3416. scope.recordDeclarationError(toParseError, origin);
  3417. } else {
  3418. return;
  3419. }
  3420. scope = stack[--i];
  3421. }
  3422. this.parser.raise(toParseError, origin);
  3423. }
  3424. recordArrowParameterBindingError(error, node) {
  3425. const {
  3426. stack
  3427. } = this;
  3428. const scope = stack[stack.length - 1];
  3429. const origin = node.loc.start;
  3430. if (scope.isCertainlyParameterDeclaration()) {
  3431. this.parser.raise(error, origin);
  3432. } else if (scope.canBeArrowParameterDeclaration()) {
  3433. scope.recordDeclarationError(error, origin);
  3434. } else {
  3435. return;
  3436. }
  3437. }
  3438. recordAsyncArrowParametersError(at) {
  3439. const {
  3440. stack
  3441. } = this;
  3442. let i = stack.length - 1;
  3443. let scope = stack[i];
  3444. while (scope.canBeArrowParameterDeclaration()) {
  3445. if (scope.type === 2) {
  3446. scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at);
  3447. }
  3448. scope = stack[--i];
  3449. }
  3450. }
  3451. validateAsPattern() {
  3452. const {
  3453. stack
  3454. } = this;
  3455. const currentScope = stack[stack.length - 1];
  3456. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3457. currentScope.iterateErrors(([toParseError, loc]) => {
  3458. this.parser.raise(toParseError, loc);
  3459. let i = stack.length - 2;
  3460. let scope = stack[i];
  3461. while (scope.canBeArrowParameterDeclaration()) {
  3462. scope.clearDeclarationError(loc.index);
  3463. scope = stack[--i];
  3464. }
  3465. });
  3466. }
  3467. }
  3468. function newParameterDeclarationScope() {
  3469. return new ExpressionScope(3);
  3470. }
  3471. function newArrowHeadScope() {
  3472. return new ArrowHeadParsingScope(1);
  3473. }
  3474. function newAsyncArrowScope() {
  3475. return new ArrowHeadParsingScope(2);
  3476. }
  3477. function newExpressionScope() {
  3478. return new ExpressionScope();
  3479. }
  3480. class ProductionParameterHandler {
  3481. constructor() {
  3482. this.stacks = [];
  3483. }
  3484. enter(flags) {
  3485. this.stacks.push(flags);
  3486. }
  3487. exit() {
  3488. this.stacks.pop();
  3489. }
  3490. currentFlags() {
  3491. return this.stacks[this.stacks.length - 1];
  3492. }
  3493. get hasAwait() {
  3494. return (this.currentFlags() & 2) > 0;
  3495. }
  3496. get hasYield() {
  3497. return (this.currentFlags() & 1) > 0;
  3498. }
  3499. get hasReturn() {
  3500. return (this.currentFlags() & 4) > 0;
  3501. }
  3502. get hasIn() {
  3503. return (this.currentFlags() & 8) > 0;
  3504. }
  3505. }
  3506. function functionFlags(isAsync, isGenerator) {
  3507. return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0);
  3508. }
  3509. class UtilParser extends Tokenizer {
  3510. addExtra(node, key, value, enumerable = true) {
  3511. if (!node) return;
  3512. let {
  3513. extra
  3514. } = node;
  3515. if (extra == null) {
  3516. extra = {};
  3517. node.extra = extra;
  3518. }
  3519. if (enumerable) {
  3520. extra[key] = value;
  3521. } else {
  3522. Object.defineProperty(extra, key, {
  3523. enumerable,
  3524. value
  3525. });
  3526. }
  3527. }
  3528. isContextual(token) {
  3529. return this.state.type === token && !this.state.containsEsc;
  3530. }
  3531. isUnparsedContextual(nameStart, name) {
  3532. const nameEnd = nameStart + name.length;
  3533. if (this.input.slice(nameStart, nameEnd) === name) {
  3534. const nextCh = this.input.charCodeAt(nameEnd);
  3535. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  3536. }
  3537. return false;
  3538. }
  3539. isLookaheadContextual(name) {
  3540. const next = this.nextTokenStart();
  3541. return this.isUnparsedContextual(next, name);
  3542. }
  3543. eatContextual(token) {
  3544. if (this.isContextual(token)) {
  3545. this.next();
  3546. return true;
  3547. }
  3548. return false;
  3549. }
  3550. expectContextual(token, toParseError) {
  3551. if (!this.eatContextual(token)) {
  3552. if (toParseError != null) {
  3553. throw this.raise(toParseError, this.state.startLoc);
  3554. }
  3555. this.unexpected(null, token);
  3556. }
  3557. }
  3558. canInsertSemicolon() {
  3559. return this.match(139) || this.match(8) || this.hasPrecedingLineBreak();
  3560. }
  3561. hasPrecedingLineBreak() {
  3562. return hasNewLine(this.input, this.state.lastTokEndLoc.index, this.state.start);
  3563. }
  3564. hasFollowingLineBreak() {
  3565. return hasNewLine(this.input, this.state.end, this.nextTokenStart());
  3566. }
  3567. isLineTerminator() {
  3568. return this.eat(13) || this.canInsertSemicolon();
  3569. }
  3570. semicolon(allowAsi = true) {
  3571. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3572. this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);
  3573. }
  3574. expect(type, loc) {
  3575. if (!this.eat(type)) {
  3576. this.unexpected(loc, type);
  3577. }
  3578. }
  3579. tryParse(fn, oldState = this.state.clone()) {
  3580. const abortSignal = {
  3581. node: null
  3582. };
  3583. try {
  3584. const node = fn((node = null) => {
  3585. abortSignal.node = node;
  3586. throw abortSignal;
  3587. });
  3588. if (this.state.errors.length > oldState.errors.length) {
  3589. const failState = this.state;
  3590. this.state = oldState;
  3591. this.state.tokensLength = failState.tokensLength;
  3592. return {
  3593. node,
  3594. error: failState.errors[oldState.errors.length],
  3595. thrown: false,
  3596. aborted: false,
  3597. failState
  3598. };
  3599. }
  3600. return {
  3601. node,
  3602. error: null,
  3603. thrown: false,
  3604. aborted: false,
  3605. failState: null
  3606. };
  3607. } catch (error) {
  3608. const failState = this.state;
  3609. this.state = oldState;
  3610. if (error instanceof SyntaxError) {
  3611. return {
  3612. node: null,
  3613. error,
  3614. thrown: true,
  3615. aborted: false,
  3616. failState
  3617. };
  3618. }
  3619. if (error === abortSignal) {
  3620. return {
  3621. node: abortSignal.node,
  3622. error: null,
  3623. thrown: false,
  3624. aborted: true,
  3625. failState
  3626. };
  3627. }
  3628. throw error;
  3629. }
  3630. }
  3631. checkExpressionErrors(refExpressionErrors, andThrow) {
  3632. if (!refExpressionErrors) return false;
  3633. const {
  3634. shorthandAssignLoc,
  3635. doubleProtoLoc,
  3636. privateKeyLoc,
  3637. optionalParametersLoc
  3638. } = refExpressionErrors;
  3639. const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc;
  3640. if (!andThrow) {
  3641. return hasErrors;
  3642. }
  3643. if (shorthandAssignLoc != null) {
  3644. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  3645. }
  3646. if (doubleProtoLoc != null) {
  3647. this.raise(Errors.DuplicateProto, doubleProtoLoc);
  3648. }
  3649. if (privateKeyLoc != null) {
  3650. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  3651. }
  3652. if (optionalParametersLoc != null) {
  3653. this.unexpected(optionalParametersLoc);
  3654. }
  3655. }
  3656. isLiteralPropertyName() {
  3657. return tokenIsLiteralPropertyName(this.state.type);
  3658. }
  3659. isPrivateName(node) {
  3660. return node.type === "PrivateName";
  3661. }
  3662. getPrivateNameSV(node) {
  3663. return node.id.name;
  3664. }
  3665. hasPropertyAsPrivateName(node) {
  3666. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3667. }
  3668. isObjectProperty(node) {
  3669. return node.type === "ObjectProperty";
  3670. }
  3671. isObjectMethod(node) {
  3672. return node.type === "ObjectMethod";
  3673. }
  3674. initializeScopes(inModule = this.options.sourceType === "module") {
  3675. const oldLabels = this.state.labels;
  3676. this.state.labels = [];
  3677. const oldExportedIdentifiers = this.exportedIdentifiers;
  3678. this.exportedIdentifiers = new Set();
  3679. const oldInModule = this.inModule;
  3680. this.inModule = inModule;
  3681. const oldScope = this.scope;
  3682. const ScopeHandler = this.getScopeHandler();
  3683. this.scope = new ScopeHandler(this, inModule);
  3684. const oldProdParam = this.prodParam;
  3685. this.prodParam = new ProductionParameterHandler();
  3686. const oldClassScope = this.classScope;
  3687. this.classScope = new ClassScopeHandler(this);
  3688. const oldExpressionScope = this.expressionScope;
  3689. this.expressionScope = new ExpressionScopeHandler(this);
  3690. return () => {
  3691. this.state.labels = oldLabels;
  3692. this.exportedIdentifiers = oldExportedIdentifiers;
  3693. this.inModule = oldInModule;
  3694. this.scope = oldScope;
  3695. this.prodParam = oldProdParam;
  3696. this.classScope = oldClassScope;
  3697. this.expressionScope = oldExpressionScope;
  3698. };
  3699. }
  3700. enterInitialScopes() {
  3701. let paramFlags = 0;
  3702. if (this.inModule) {
  3703. paramFlags |= 2;
  3704. }
  3705. this.scope.enter(1);
  3706. this.prodParam.enter(paramFlags);
  3707. }
  3708. checkDestructuringPrivate(refExpressionErrors) {
  3709. const {
  3710. privateKeyLoc
  3711. } = refExpressionErrors;
  3712. if (privateKeyLoc !== null) {
  3713. this.expectPlugin("destructuringPrivate", privateKeyLoc);
  3714. }
  3715. }
  3716. }
  3717. class ExpressionErrors {
  3718. constructor() {
  3719. this.shorthandAssignLoc = null;
  3720. this.doubleProtoLoc = null;
  3721. this.privateKeyLoc = null;
  3722. this.optionalParametersLoc = null;
  3723. }
  3724. }
  3725. class Node {
  3726. constructor(parser, pos, loc) {
  3727. this.type = "";
  3728. this.start = pos;
  3729. this.end = 0;
  3730. this.loc = new SourceLocation(loc);
  3731. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  3732. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  3733. }
  3734. }
  3735. const NodePrototype = Node.prototype;
  3736. {
  3737. NodePrototype.__clone = function () {
  3738. const newNode = new Node(undefined, this.start, this.loc.start);
  3739. const keys = Object.keys(this);
  3740. for (let i = 0, length = keys.length; i < length; i++) {
  3741. const key = keys[i];
  3742. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  3743. newNode[key] = this[key];
  3744. }
  3745. }
  3746. return newNode;
  3747. };
  3748. }
  3749. function clonePlaceholder(node) {
  3750. return cloneIdentifier(node);
  3751. }
  3752. function cloneIdentifier(node) {
  3753. const {
  3754. type,
  3755. start,
  3756. end,
  3757. loc,
  3758. range,
  3759. extra,
  3760. name
  3761. } = node;
  3762. const cloned = Object.create(NodePrototype);
  3763. cloned.type = type;
  3764. cloned.start = start;
  3765. cloned.end = end;
  3766. cloned.loc = loc;
  3767. cloned.range = range;
  3768. cloned.extra = extra;
  3769. cloned.name = name;
  3770. if (type === "Placeholder") {
  3771. cloned.expectedNode = node.expectedNode;
  3772. }
  3773. return cloned;
  3774. }
  3775. function cloneStringLiteral(node) {
  3776. const {
  3777. type,
  3778. start,
  3779. end,
  3780. loc,
  3781. range,
  3782. extra
  3783. } = node;
  3784. if (type === "Placeholder") {
  3785. return clonePlaceholder(node);
  3786. }
  3787. const cloned = Object.create(NodePrototype);
  3788. cloned.type = type;
  3789. cloned.start = start;
  3790. cloned.end = end;
  3791. cloned.loc = loc;
  3792. cloned.range = range;
  3793. if (node.raw !== undefined) {
  3794. cloned.raw = node.raw;
  3795. } else {
  3796. cloned.extra = extra;
  3797. }
  3798. cloned.value = node.value;
  3799. return cloned;
  3800. }
  3801. class NodeUtils extends UtilParser {
  3802. startNode() {
  3803. const loc = this.state.startLoc;
  3804. return new Node(this, loc.index, loc);
  3805. }
  3806. startNodeAt(loc) {
  3807. return new Node(this, loc.index, loc);
  3808. }
  3809. startNodeAtNode(type) {
  3810. return this.startNodeAt(type.loc.start);
  3811. }
  3812. finishNode(node, type) {
  3813. return this.finishNodeAt(node, type, this.state.lastTokEndLoc);
  3814. }
  3815. finishNodeAt(node, type, endLoc) {
  3816. node.type = type;
  3817. node.end = endLoc.index;
  3818. node.loc.end = endLoc;
  3819. if (this.options.ranges) node.range[1] = endLoc.index;
  3820. if (this.options.attachComment) this.processComment(node);
  3821. return node;
  3822. }
  3823. resetStartLocation(node, startLoc) {
  3824. node.start = startLoc.index;
  3825. node.loc.start = startLoc;
  3826. if (this.options.ranges) node.range[0] = startLoc.index;
  3827. }
  3828. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  3829. node.end = endLoc.index;
  3830. node.loc.end = endLoc;
  3831. if (this.options.ranges) node.range[1] = endLoc.index;
  3832. }
  3833. resetStartLocationFromNode(node, locationNode) {
  3834. this.resetStartLocation(node, locationNode.loc.start);
  3835. }
  3836. }
  3837. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  3838. const FlowErrors = ParseErrorEnum`flow`({
  3839. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  3840. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",
  3841. AssignReservedType: ({
  3842. reservedType
  3843. }) => `Cannot overwrite reserved type ${reservedType}.`,
  3844. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  3845. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  3846. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  3847. EnumBooleanMemberNotInitialized: ({
  3848. memberName,
  3849. enumName
  3850. }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  3851. EnumDuplicateMemberName: ({
  3852. memberName,
  3853. enumName
  3854. }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  3855. EnumInconsistentMemberValues: ({
  3856. enumName
  3857. }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  3858. EnumInvalidExplicitType: ({
  3859. invalidEnumType,
  3860. enumName
  3861. }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3862. EnumInvalidExplicitTypeUnknownSupplied: ({
  3863. enumName
  3864. }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  3865. EnumInvalidMemberInitializerPrimaryType: ({
  3866. enumName,
  3867. memberName,
  3868. explicitType
  3869. }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  3870. EnumInvalidMemberInitializerSymbolType: ({
  3871. enumName,
  3872. memberName
  3873. }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  3874. EnumInvalidMemberInitializerUnknownType: ({
  3875. enumName,
  3876. memberName
  3877. }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  3878. EnumInvalidMemberName: ({
  3879. enumName,
  3880. memberName,
  3881. suggestion
  3882. }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  3883. EnumNumberMemberNotInitialized: ({
  3884. enumName,
  3885. memberName
  3886. }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  3887. EnumStringMemberInconsistentlyInitialized: ({
  3888. enumName
  3889. }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  3890. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  3891. ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  3892. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",
  3893. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  3894. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  3895. InexactVariance: "Explicit inexact syntax cannot have variance.",
  3896. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  3897. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  3898. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  3899. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  3900. PatternIsOptional: Object.assign({
  3901. message: "A binding pattern parameter cannot be optional in an implementation signature."
  3902. }, {
  3903. reasonCode: "OptionalBindingPattern"
  3904. }),
  3905. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  3906. SpreadVariance: "Spread properties cannot have variance.",
  3907. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  3908. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  3909. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  3910. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  3911. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  3912. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  3913. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  3914. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  3915. UnexpectedReservedType: ({
  3916. reservedType
  3917. }) => `Unexpected reserved type ${reservedType}.`,
  3918. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  3919. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  3920. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  3921. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  3922. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  3923. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  3924. UnsupportedDeclareExportKind: ({
  3925. unsupportedExportKind,
  3926. suggestion
  3927. }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  3928. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  3929. UnterminatedFlowComment: "Unterminated flow-comment."
  3930. });
  3931. function isEsModuleType(bodyElement) {
  3932. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  3933. }
  3934. function hasTypeImportKind(node) {
  3935. return node.importKind === "type" || node.importKind === "typeof";
  3936. }
  3937. const exportSuggestions = {
  3938. const: "declare export var",
  3939. let: "declare export var",
  3940. type: "export type",
  3941. interface: "export interface"
  3942. };
  3943. function partition(list, test) {
  3944. const list1 = [];
  3945. const list2 = [];
  3946. for (let i = 0; i < list.length; i++) {
  3947. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  3948. }
  3949. return [list1, list2];
  3950. }
  3951. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  3952. var flow = superClass => class FlowParserMixin extends superClass {
  3953. constructor(...args) {
  3954. super(...args);
  3955. this.flowPragma = undefined;
  3956. }
  3957. getScopeHandler() {
  3958. return FlowScopeHandler;
  3959. }
  3960. shouldParseTypes() {
  3961. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  3962. }
  3963. shouldParseEnums() {
  3964. return !!this.getPluginOption("flow", "enums");
  3965. }
  3966. finishToken(type, val) {
  3967. if (type !== 133 && type !== 13 && type !== 28) {
  3968. if (this.flowPragma === undefined) {
  3969. this.flowPragma = null;
  3970. }
  3971. }
  3972. super.finishToken(type, val);
  3973. }
  3974. addComment(comment) {
  3975. if (this.flowPragma === undefined) {
  3976. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  3977. if (!matches) ;else if (matches[1] === "flow") {
  3978. this.flowPragma = "flow";
  3979. } else if (matches[1] === "noflow") {
  3980. this.flowPragma = "noflow";
  3981. } else {
  3982. throw new Error("Unexpected flow pragma");
  3983. }
  3984. }
  3985. super.addComment(comment);
  3986. }
  3987. flowParseTypeInitialiser(tok) {
  3988. const oldInType = this.state.inType;
  3989. this.state.inType = true;
  3990. this.expect(tok || 14);
  3991. const type = this.flowParseType();
  3992. this.state.inType = oldInType;
  3993. return type;
  3994. }
  3995. flowParsePredicate() {
  3996. const node = this.startNode();
  3997. const moduloLoc = this.state.startLoc;
  3998. this.next();
  3999. this.expectContextual(110);
  4000. if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) {
  4001. this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);
  4002. }
  4003. if (this.eat(10)) {
  4004. node.value = super.parseExpression();
  4005. this.expect(11);
  4006. return this.finishNode(node, "DeclaredPredicate");
  4007. } else {
  4008. return this.finishNode(node, "InferredPredicate");
  4009. }
  4010. }
  4011. flowParseTypeAndPredicateInitialiser() {
  4012. const oldInType = this.state.inType;
  4013. this.state.inType = true;
  4014. this.expect(14);
  4015. let type = null;
  4016. let predicate = null;
  4017. if (this.match(54)) {
  4018. this.state.inType = oldInType;
  4019. predicate = this.flowParsePredicate();
  4020. } else {
  4021. type = this.flowParseType();
  4022. this.state.inType = oldInType;
  4023. if (this.match(54)) {
  4024. predicate = this.flowParsePredicate();
  4025. }
  4026. }
  4027. return [type, predicate];
  4028. }
  4029. flowParseDeclareClass(node) {
  4030. this.next();
  4031. this.flowParseInterfaceish(node, true);
  4032. return this.finishNode(node, "DeclareClass");
  4033. }
  4034. flowParseDeclareFunction(node) {
  4035. this.next();
  4036. const id = node.id = this.parseIdentifier();
  4037. const typeNode = this.startNode();
  4038. const typeContainer = this.startNode();
  4039. if (this.match(47)) {
  4040. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4041. } else {
  4042. typeNode.typeParameters = null;
  4043. }
  4044. this.expect(10);
  4045. const tmp = this.flowParseFunctionTypeParams();
  4046. typeNode.params = tmp.params;
  4047. typeNode.rest = tmp.rest;
  4048. typeNode.this = tmp._this;
  4049. this.expect(11);
  4050. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4051. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4052. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4053. this.resetEndLocation(id);
  4054. this.semicolon();
  4055. this.scope.declareName(node.id.name, 2048, node.id.loc.start);
  4056. return this.finishNode(node, "DeclareFunction");
  4057. }
  4058. flowParseDeclare(node, insideModule) {
  4059. if (this.match(80)) {
  4060. return this.flowParseDeclareClass(node);
  4061. } else if (this.match(68)) {
  4062. return this.flowParseDeclareFunction(node);
  4063. } else if (this.match(74)) {
  4064. return this.flowParseDeclareVariable(node);
  4065. } else if (this.eatContextual(127)) {
  4066. if (this.match(16)) {
  4067. return this.flowParseDeclareModuleExports(node);
  4068. } else {
  4069. if (insideModule) {
  4070. this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc);
  4071. }
  4072. return this.flowParseDeclareModule(node);
  4073. }
  4074. } else if (this.isContextual(130)) {
  4075. return this.flowParseDeclareTypeAlias(node);
  4076. } else if (this.isContextual(131)) {
  4077. return this.flowParseDeclareOpaqueType(node);
  4078. } else if (this.isContextual(129)) {
  4079. return this.flowParseDeclareInterface(node);
  4080. } else if (this.match(82)) {
  4081. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4082. } else {
  4083. this.unexpected();
  4084. }
  4085. }
  4086. flowParseDeclareVariable(node) {
  4087. this.next();
  4088. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4089. this.scope.declareName(node.id.name, 5, node.id.loc.start);
  4090. this.semicolon();
  4091. return this.finishNode(node, "DeclareVariable");
  4092. }
  4093. flowParseDeclareModule(node) {
  4094. this.scope.enter(0);
  4095. if (this.match(133)) {
  4096. node.id = super.parseExprAtom();
  4097. } else {
  4098. node.id = this.parseIdentifier();
  4099. }
  4100. const bodyNode = node.body = this.startNode();
  4101. const body = bodyNode.body = [];
  4102. this.expect(5);
  4103. while (!this.match(8)) {
  4104. let bodyNode = this.startNode();
  4105. if (this.match(83)) {
  4106. this.next();
  4107. if (!this.isContextual(130) && !this.match(87)) {
  4108. this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc);
  4109. }
  4110. super.parseImport(bodyNode);
  4111. } else {
  4112. this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule);
  4113. bodyNode = this.flowParseDeclare(bodyNode, true);
  4114. }
  4115. body.push(bodyNode);
  4116. }
  4117. this.scope.exit();
  4118. this.expect(8);
  4119. this.finishNode(bodyNode, "BlockStatement");
  4120. let kind = null;
  4121. let hasModuleExport = false;
  4122. body.forEach(bodyElement => {
  4123. if (isEsModuleType(bodyElement)) {
  4124. if (kind === "CommonJS") {
  4125. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  4126. }
  4127. kind = "ES";
  4128. } else if (bodyElement.type === "DeclareModuleExports") {
  4129. if (hasModuleExport) {
  4130. this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);
  4131. }
  4132. if (kind === "ES") {
  4133. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  4134. }
  4135. kind = "CommonJS";
  4136. hasModuleExport = true;
  4137. }
  4138. });
  4139. node.kind = kind || "CommonJS";
  4140. return this.finishNode(node, "DeclareModule");
  4141. }
  4142. flowParseDeclareExportDeclaration(node, insideModule) {
  4143. this.expect(82);
  4144. if (this.eat(65)) {
  4145. if (this.match(68) || this.match(80)) {
  4146. node.declaration = this.flowParseDeclare(this.startNode());
  4147. } else {
  4148. node.declaration = this.flowParseType();
  4149. this.semicolon();
  4150. }
  4151. node.default = true;
  4152. return this.finishNode(node, "DeclareExportDeclaration");
  4153. } else {
  4154. if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) {
  4155. const label = this.state.value;
  4156. throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, {
  4157. unsupportedExportKind: label,
  4158. suggestion: exportSuggestions[label]
  4159. });
  4160. }
  4161. if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) {
  4162. node.declaration = this.flowParseDeclare(this.startNode());
  4163. node.default = false;
  4164. return this.finishNode(node, "DeclareExportDeclaration");
  4165. } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) {
  4166. node = this.parseExport(node, null);
  4167. if (node.type === "ExportNamedDeclaration") {
  4168. node.type = "ExportDeclaration";
  4169. node.default = false;
  4170. delete node.exportKind;
  4171. }
  4172. node.type = "Declare" + node.type;
  4173. return node;
  4174. }
  4175. }
  4176. this.unexpected();
  4177. }
  4178. flowParseDeclareModuleExports(node) {
  4179. this.next();
  4180. this.expectContextual(111);
  4181. node.typeAnnotation = this.flowParseTypeAnnotation();
  4182. this.semicolon();
  4183. return this.finishNode(node, "DeclareModuleExports");
  4184. }
  4185. flowParseDeclareTypeAlias(node) {
  4186. this.next();
  4187. const finished = this.flowParseTypeAlias(node);
  4188. finished.type = "DeclareTypeAlias";
  4189. return finished;
  4190. }
  4191. flowParseDeclareOpaqueType(node) {
  4192. this.next();
  4193. const finished = this.flowParseOpaqueType(node, true);
  4194. finished.type = "DeclareOpaqueType";
  4195. return finished;
  4196. }
  4197. flowParseDeclareInterface(node) {
  4198. this.next();
  4199. this.flowParseInterfaceish(node, false);
  4200. return this.finishNode(node, "DeclareInterface");
  4201. }
  4202. flowParseInterfaceish(node, isClass) {
  4203. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4204. this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start);
  4205. if (this.match(47)) {
  4206. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4207. } else {
  4208. node.typeParameters = null;
  4209. }
  4210. node.extends = [];
  4211. if (this.eat(81)) {
  4212. do {
  4213. node.extends.push(this.flowParseInterfaceExtends());
  4214. } while (!isClass && this.eat(12));
  4215. }
  4216. if (isClass) {
  4217. node.implements = [];
  4218. node.mixins = [];
  4219. if (this.eatContextual(117)) {
  4220. do {
  4221. node.mixins.push(this.flowParseInterfaceExtends());
  4222. } while (this.eat(12));
  4223. }
  4224. if (this.eatContextual(113)) {
  4225. do {
  4226. node.implements.push(this.flowParseInterfaceExtends());
  4227. } while (this.eat(12));
  4228. }
  4229. }
  4230. node.body = this.flowParseObjectType({
  4231. allowStatic: isClass,
  4232. allowExact: false,
  4233. allowSpread: false,
  4234. allowProto: isClass,
  4235. allowInexact: false
  4236. });
  4237. }
  4238. flowParseInterfaceExtends() {
  4239. const node = this.startNode();
  4240. node.id = this.flowParseQualifiedTypeIdentifier();
  4241. if (this.match(47)) {
  4242. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4243. } else {
  4244. node.typeParameters = null;
  4245. }
  4246. return this.finishNode(node, "InterfaceExtends");
  4247. }
  4248. flowParseInterface(node) {
  4249. this.flowParseInterfaceish(node, false);
  4250. return this.finishNode(node, "InterfaceDeclaration");
  4251. }
  4252. checkNotUnderscore(word) {
  4253. if (word === "_") {
  4254. this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc);
  4255. }
  4256. }
  4257. checkReservedType(word, startLoc, declaration) {
  4258. if (!reservedTypes.has(word)) return;
  4259. this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, {
  4260. reservedType: word
  4261. });
  4262. }
  4263. flowParseRestrictedIdentifier(liberal, declaration) {
  4264. this.checkReservedType(this.state.value, this.state.startLoc, declaration);
  4265. return this.parseIdentifier(liberal);
  4266. }
  4267. flowParseTypeAlias(node) {
  4268. node.id = this.flowParseRestrictedIdentifier(false, true);
  4269. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  4270. if (this.match(47)) {
  4271. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4272. } else {
  4273. node.typeParameters = null;
  4274. }
  4275. node.right = this.flowParseTypeInitialiser(29);
  4276. this.semicolon();
  4277. return this.finishNode(node, "TypeAlias");
  4278. }
  4279. flowParseOpaqueType(node, declare) {
  4280. this.expectContextual(130);
  4281. node.id = this.flowParseRestrictedIdentifier(true, true);
  4282. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  4283. if (this.match(47)) {
  4284. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4285. } else {
  4286. node.typeParameters = null;
  4287. }
  4288. node.supertype = null;
  4289. if (this.match(14)) {
  4290. node.supertype = this.flowParseTypeInitialiser(14);
  4291. }
  4292. node.impltype = null;
  4293. if (!declare) {
  4294. node.impltype = this.flowParseTypeInitialiser(29);
  4295. }
  4296. this.semicolon();
  4297. return this.finishNode(node, "OpaqueType");
  4298. }
  4299. flowParseTypeParameter(requireDefault = false) {
  4300. const nodeStartLoc = this.state.startLoc;
  4301. const node = this.startNode();
  4302. const variance = this.flowParseVariance();
  4303. const ident = this.flowParseTypeAnnotatableIdentifier();
  4304. node.name = ident.name;
  4305. node.variance = variance;
  4306. node.bound = ident.typeAnnotation;
  4307. if (this.match(29)) {
  4308. this.eat(29);
  4309. node.default = this.flowParseType();
  4310. } else {
  4311. if (requireDefault) {
  4312. this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);
  4313. }
  4314. }
  4315. return this.finishNode(node, "TypeParameter");
  4316. }
  4317. flowParseTypeParameterDeclaration() {
  4318. const oldInType = this.state.inType;
  4319. const node = this.startNode();
  4320. node.params = [];
  4321. this.state.inType = true;
  4322. if (this.match(47) || this.match(142)) {
  4323. this.next();
  4324. } else {
  4325. this.unexpected();
  4326. }
  4327. let defaultRequired = false;
  4328. do {
  4329. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4330. node.params.push(typeParameter);
  4331. if (typeParameter.default) {
  4332. defaultRequired = true;
  4333. }
  4334. if (!this.match(48)) {
  4335. this.expect(12);
  4336. }
  4337. } while (!this.match(48));
  4338. this.expect(48);
  4339. this.state.inType = oldInType;
  4340. return this.finishNode(node, "TypeParameterDeclaration");
  4341. }
  4342. flowParseTypeParameterInstantiation() {
  4343. const node = this.startNode();
  4344. const oldInType = this.state.inType;
  4345. node.params = [];
  4346. this.state.inType = true;
  4347. this.expect(47);
  4348. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4349. this.state.noAnonFunctionType = false;
  4350. while (!this.match(48)) {
  4351. node.params.push(this.flowParseType());
  4352. if (!this.match(48)) {
  4353. this.expect(12);
  4354. }
  4355. }
  4356. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4357. this.expect(48);
  4358. this.state.inType = oldInType;
  4359. return this.finishNode(node, "TypeParameterInstantiation");
  4360. }
  4361. flowParseTypeParameterInstantiationCallOrNew() {
  4362. const node = this.startNode();
  4363. const oldInType = this.state.inType;
  4364. node.params = [];
  4365. this.state.inType = true;
  4366. this.expect(47);
  4367. while (!this.match(48)) {
  4368. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4369. if (!this.match(48)) {
  4370. this.expect(12);
  4371. }
  4372. }
  4373. this.expect(48);
  4374. this.state.inType = oldInType;
  4375. return this.finishNode(node, "TypeParameterInstantiation");
  4376. }
  4377. flowParseInterfaceType() {
  4378. const node = this.startNode();
  4379. this.expectContextual(129);
  4380. node.extends = [];
  4381. if (this.eat(81)) {
  4382. do {
  4383. node.extends.push(this.flowParseInterfaceExtends());
  4384. } while (this.eat(12));
  4385. }
  4386. node.body = this.flowParseObjectType({
  4387. allowStatic: false,
  4388. allowExact: false,
  4389. allowSpread: false,
  4390. allowProto: false,
  4391. allowInexact: false
  4392. });
  4393. return this.finishNode(node, "InterfaceTypeAnnotation");
  4394. }
  4395. flowParseObjectPropertyKey() {
  4396. return this.match(134) || this.match(133) ? super.parseExprAtom() : this.parseIdentifier(true);
  4397. }
  4398. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4399. node.static = isStatic;
  4400. if (this.lookahead().type === 14) {
  4401. node.id = this.flowParseObjectPropertyKey();
  4402. node.key = this.flowParseTypeInitialiser();
  4403. } else {
  4404. node.id = null;
  4405. node.key = this.flowParseType();
  4406. }
  4407. this.expect(3);
  4408. node.value = this.flowParseTypeInitialiser();
  4409. node.variance = variance;
  4410. return this.finishNode(node, "ObjectTypeIndexer");
  4411. }
  4412. flowParseObjectTypeInternalSlot(node, isStatic) {
  4413. node.static = isStatic;
  4414. node.id = this.flowParseObjectPropertyKey();
  4415. this.expect(3);
  4416. this.expect(3);
  4417. if (this.match(47) || this.match(10)) {
  4418. node.method = true;
  4419. node.optional = false;
  4420. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4421. } else {
  4422. node.method = false;
  4423. if (this.eat(17)) {
  4424. node.optional = true;
  4425. }
  4426. node.value = this.flowParseTypeInitialiser();
  4427. }
  4428. return this.finishNode(node, "ObjectTypeInternalSlot");
  4429. }
  4430. flowParseObjectTypeMethodish(node) {
  4431. node.params = [];
  4432. node.rest = null;
  4433. node.typeParameters = null;
  4434. node.this = null;
  4435. if (this.match(47)) {
  4436. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4437. }
  4438. this.expect(10);
  4439. if (this.match(78)) {
  4440. node.this = this.flowParseFunctionTypeParam(true);
  4441. node.this.name = null;
  4442. if (!this.match(11)) {
  4443. this.expect(12);
  4444. }
  4445. }
  4446. while (!this.match(11) && !this.match(21)) {
  4447. node.params.push(this.flowParseFunctionTypeParam(false));
  4448. if (!this.match(11)) {
  4449. this.expect(12);
  4450. }
  4451. }
  4452. if (this.eat(21)) {
  4453. node.rest = this.flowParseFunctionTypeParam(false);
  4454. }
  4455. this.expect(11);
  4456. node.returnType = this.flowParseTypeInitialiser();
  4457. return this.finishNode(node, "FunctionTypeAnnotation");
  4458. }
  4459. flowParseObjectTypeCallProperty(node, isStatic) {
  4460. const valueNode = this.startNode();
  4461. node.static = isStatic;
  4462. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4463. return this.finishNode(node, "ObjectTypeCallProperty");
  4464. }
  4465. flowParseObjectType({
  4466. allowStatic,
  4467. allowExact,
  4468. allowSpread,
  4469. allowProto,
  4470. allowInexact
  4471. }) {
  4472. const oldInType = this.state.inType;
  4473. this.state.inType = true;
  4474. const nodeStart = this.startNode();
  4475. nodeStart.callProperties = [];
  4476. nodeStart.properties = [];
  4477. nodeStart.indexers = [];
  4478. nodeStart.internalSlots = [];
  4479. let endDelim;
  4480. let exact;
  4481. let inexact = false;
  4482. if (allowExact && this.match(6)) {
  4483. this.expect(6);
  4484. endDelim = 9;
  4485. exact = true;
  4486. } else {
  4487. this.expect(5);
  4488. endDelim = 8;
  4489. exact = false;
  4490. }
  4491. nodeStart.exact = exact;
  4492. while (!this.match(endDelim)) {
  4493. let isStatic = false;
  4494. let protoStartLoc = null;
  4495. let inexactStartLoc = null;
  4496. const node = this.startNode();
  4497. if (allowProto && this.isContextual(118)) {
  4498. const lookahead = this.lookahead();
  4499. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4500. this.next();
  4501. protoStartLoc = this.state.startLoc;
  4502. allowStatic = false;
  4503. }
  4504. }
  4505. if (allowStatic && this.isContextual(106)) {
  4506. const lookahead = this.lookahead();
  4507. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4508. this.next();
  4509. isStatic = true;
  4510. }
  4511. }
  4512. const variance = this.flowParseVariance();
  4513. if (this.eat(0)) {
  4514. if (protoStartLoc != null) {
  4515. this.unexpected(protoStartLoc);
  4516. }
  4517. if (this.eat(0)) {
  4518. if (variance) {
  4519. this.unexpected(variance.loc.start);
  4520. }
  4521. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4522. } else {
  4523. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4524. }
  4525. } else if (this.match(10) || this.match(47)) {
  4526. if (protoStartLoc != null) {
  4527. this.unexpected(protoStartLoc);
  4528. }
  4529. if (variance) {
  4530. this.unexpected(variance.loc.start);
  4531. }
  4532. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4533. } else {
  4534. let kind = "init";
  4535. if (this.isContextual(99) || this.isContextual(104)) {
  4536. const lookahead = this.lookahead();
  4537. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4538. kind = this.state.value;
  4539. this.next();
  4540. }
  4541. }
  4542. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4543. if (propOrInexact === null) {
  4544. inexact = true;
  4545. inexactStartLoc = this.state.lastTokStartLoc;
  4546. } else {
  4547. nodeStart.properties.push(propOrInexact);
  4548. }
  4549. }
  4550. this.flowObjectTypeSemicolon();
  4551. if (inexactStartLoc && !this.match(8) && !this.match(9)) {
  4552. this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc);
  4553. }
  4554. }
  4555. this.expect(endDelim);
  4556. if (allowSpread) {
  4557. nodeStart.inexact = inexact;
  4558. }
  4559. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4560. this.state.inType = oldInType;
  4561. return out;
  4562. }
  4563. flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
  4564. if (this.eat(21)) {
  4565. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4566. if (isInexactToken) {
  4567. if (!allowSpread) {
  4568. this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc);
  4569. } else if (!allowInexact) {
  4570. this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc);
  4571. }
  4572. if (variance) {
  4573. this.raise(FlowErrors.InexactVariance, variance);
  4574. }
  4575. return null;
  4576. }
  4577. if (!allowSpread) {
  4578. this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc);
  4579. }
  4580. if (protoStartLoc != null) {
  4581. this.unexpected(protoStartLoc);
  4582. }
  4583. if (variance) {
  4584. this.raise(FlowErrors.SpreadVariance, variance);
  4585. }
  4586. node.argument = this.flowParseType();
  4587. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4588. } else {
  4589. node.key = this.flowParseObjectPropertyKey();
  4590. node.static = isStatic;
  4591. node.proto = protoStartLoc != null;
  4592. node.kind = kind;
  4593. let optional = false;
  4594. if (this.match(47) || this.match(10)) {
  4595. node.method = true;
  4596. if (protoStartLoc != null) {
  4597. this.unexpected(protoStartLoc);
  4598. }
  4599. if (variance) {
  4600. this.unexpected(variance.loc.start);
  4601. }
  4602. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  4603. if (kind === "get" || kind === "set") {
  4604. this.flowCheckGetterSetterParams(node);
  4605. }
  4606. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4607. this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this);
  4608. }
  4609. } else {
  4610. if (kind !== "init") this.unexpected();
  4611. node.method = false;
  4612. if (this.eat(17)) {
  4613. optional = true;
  4614. }
  4615. node.value = this.flowParseTypeInitialiser();
  4616. node.variance = variance;
  4617. }
  4618. node.optional = optional;
  4619. return this.finishNode(node, "ObjectTypeProperty");
  4620. }
  4621. }
  4622. flowCheckGetterSetterParams(property) {
  4623. const paramCount = property.kind === "get" ? 0 : 1;
  4624. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4625. if (property.value.this) {
  4626. this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this);
  4627. }
  4628. if (length !== paramCount) {
  4629. this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property);
  4630. }
  4631. if (property.kind === "set" && property.value.rest) {
  4632. this.raise(Errors.BadSetterRestParameter, property);
  4633. }
  4634. }
  4635. flowObjectTypeSemicolon() {
  4636. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4637. this.unexpected();
  4638. }
  4639. }
  4640. flowParseQualifiedTypeIdentifier(startLoc, id) {
  4641. var _startLoc;
  4642. (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
  4643. let node = id || this.flowParseRestrictedIdentifier(true);
  4644. while (this.eat(16)) {
  4645. const node2 = this.startNodeAt(startLoc);
  4646. node2.qualification = node;
  4647. node2.id = this.flowParseRestrictedIdentifier(true);
  4648. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4649. }
  4650. return node;
  4651. }
  4652. flowParseGenericType(startLoc, id) {
  4653. const node = this.startNodeAt(startLoc);
  4654. node.typeParameters = null;
  4655. node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);
  4656. if (this.match(47)) {
  4657. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4658. }
  4659. return this.finishNode(node, "GenericTypeAnnotation");
  4660. }
  4661. flowParseTypeofType() {
  4662. const node = this.startNode();
  4663. this.expect(87);
  4664. node.argument = this.flowParsePrimaryType();
  4665. return this.finishNode(node, "TypeofTypeAnnotation");
  4666. }
  4667. flowParseTupleType() {
  4668. const node = this.startNode();
  4669. node.types = [];
  4670. this.expect(0);
  4671. while (this.state.pos < this.length && !this.match(3)) {
  4672. node.types.push(this.flowParseType());
  4673. if (this.match(3)) break;
  4674. this.expect(12);
  4675. }
  4676. this.expect(3);
  4677. return this.finishNode(node, "TupleTypeAnnotation");
  4678. }
  4679. flowParseFunctionTypeParam(first) {
  4680. let name = null;
  4681. let optional = false;
  4682. let typeAnnotation = null;
  4683. const node = this.startNode();
  4684. const lh = this.lookahead();
  4685. const isThis = this.state.type === 78;
  4686. if (lh.type === 14 || lh.type === 17) {
  4687. if (isThis && !first) {
  4688. this.raise(FlowErrors.ThisParamMustBeFirst, node);
  4689. }
  4690. name = this.parseIdentifier(isThis);
  4691. if (this.eat(17)) {
  4692. optional = true;
  4693. if (isThis) {
  4694. this.raise(FlowErrors.ThisParamMayNotBeOptional, node);
  4695. }
  4696. }
  4697. typeAnnotation = this.flowParseTypeInitialiser();
  4698. } else {
  4699. typeAnnotation = this.flowParseType();
  4700. }
  4701. node.name = name;
  4702. node.optional = optional;
  4703. node.typeAnnotation = typeAnnotation;
  4704. return this.finishNode(node, "FunctionTypeParam");
  4705. }
  4706. reinterpretTypeAsFunctionTypeParam(type) {
  4707. const node = this.startNodeAt(type.loc.start);
  4708. node.name = null;
  4709. node.optional = false;
  4710. node.typeAnnotation = type;
  4711. return this.finishNode(node, "FunctionTypeParam");
  4712. }
  4713. flowParseFunctionTypeParams(params = []) {
  4714. let rest = null;
  4715. let _this = null;
  4716. if (this.match(78)) {
  4717. _this = this.flowParseFunctionTypeParam(true);
  4718. _this.name = null;
  4719. if (!this.match(11)) {
  4720. this.expect(12);
  4721. }
  4722. }
  4723. while (!this.match(11) && !this.match(21)) {
  4724. params.push(this.flowParseFunctionTypeParam(false));
  4725. if (!this.match(11)) {
  4726. this.expect(12);
  4727. }
  4728. }
  4729. if (this.eat(21)) {
  4730. rest = this.flowParseFunctionTypeParam(false);
  4731. }
  4732. return {
  4733. params,
  4734. rest,
  4735. _this
  4736. };
  4737. }
  4738. flowIdentToTypeAnnotation(startLoc, node, id) {
  4739. switch (id.name) {
  4740. case "any":
  4741. return this.finishNode(node, "AnyTypeAnnotation");
  4742. case "bool":
  4743. case "boolean":
  4744. return this.finishNode(node, "BooleanTypeAnnotation");
  4745. case "mixed":
  4746. return this.finishNode(node, "MixedTypeAnnotation");
  4747. case "empty":
  4748. return this.finishNode(node, "EmptyTypeAnnotation");
  4749. case "number":
  4750. return this.finishNode(node, "NumberTypeAnnotation");
  4751. case "string":
  4752. return this.finishNode(node, "StringTypeAnnotation");
  4753. case "symbol":
  4754. return this.finishNode(node, "SymbolTypeAnnotation");
  4755. default:
  4756. this.checkNotUnderscore(id.name);
  4757. return this.flowParseGenericType(startLoc, id);
  4758. }
  4759. }
  4760. flowParsePrimaryType() {
  4761. const startLoc = this.state.startLoc;
  4762. const node = this.startNode();
  4763. let tmp;
  4764. let type;
  4765. let isGroupedType = false;
  4766. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4767. switch (this.state.type) {
  4768. case 5:
  4769. return this.flowParseObjectType({
  4770. allowStatic: false,
  4771. allowExact: false,
  4772. allowSpread: true,
  4773. allowProto: false,
  4774. allowInexact: true
  4775. });
  4776. case 6:
  4777. return this.flowParseObjectType({
  4778. allowStatic: false,
  4779. allowExact: true,
  4780. allowSpread: true,
  4781. allowProto: false,
  4782. allowInexact: false
  4783. });
  4784. case 0:
  4785. this.state.noAnonFunctionType = false;
  4786. type = this.flowParseTupleType();
  4787. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4788. return type;
  4789. case 47:
  4790. {
  4791. const node = this.startNode();
  4792. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4793. this.expect(10);
  4794. tmp = this.flowParseFunctionTypeParams();
  4795. node.params = tmp.params;
  4796. node.rest = tmp.rest;
  4797. node.this = tmp._this;
  4798. this.expect(11);
  4799. this.expect(19);
  4800. node.returnType = this.flowParseType();
  4801. return this.finishNode(node, "FunctionTypeAnnotation");
  4802. }
  4803. case 10:
  4804. {
  4805. const node = this.startNode();
  4806. this.next();
  4807. if (!this.match(11) && !this.match(21)) {
  4808. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  4809. const token = this.lookahead().type;
  4810. isGroupedType = token !== 17 && token !== 14;
  4811. } else {
  4812. isGroupedType = true;
  4813. }
  4814. }
  4815. if (isGroupedType) {
  4816. this.state.noAnonFunctionType = false;
  4817. type = this.flowParseType();
  4818. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4819. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  4820. this.expect(11);
  4821. return type;
  4822. } else {
  4823. this.eat(12);
  4824. }
  4825. }
  4826. if (type) {
  4827. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  4828. } else {
  4829. tmp = this.flowParseFunctionTypeParams();
  4830. }
  4831. node.params = tmp.params;
  4832. node.rest = tmp.rest;
  4833. node.this = tmp._this;
  4834. this.expect(11);
  4835. this.expect(19);
  4836. node.returnType = this.flowParseType();
  4837. node.typeParameters = null;
  4838. return this.finishNode(node, "FunctionTypeAnnotation");
  4839. }
  4840. case 133:
  4841. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  4842. case 85:
  4843. case 86:
  4844. node.value = this.match(85);
  4845. this.next();
  4846. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  4847. case 53:
  4848. if (this.state.value === "-") {
  4849. this.next();
  4850. if (this.match(134)) {
  4851. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  4852. }
  4853. if (this.match(135)) {
  4854. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  4855. }
  4856. throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc);
  4857. }
  4858. this.unexpected();
  4859. return;
  4860. case 134:
  4861. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  4862. case 135:
  4863. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  4864. case 88:
  4865. this.next();
  4866. return this.finishNode(node, "VoidTypeAnnotation");
  4867. case 84:
  4868. this.next();
  4869. return this.finishNode(node, "NullLiteralTypeAnnotation");
  4870. case 78:
  4871. this.next();
  4872. return this.finishNode(node, "ThisTypeAnnotation");
  4873. case 55:
  4874. this.next();
  4875. return this.finishNode(node, "ExistsTypeAnnotation");
  4876. case 87:
  4877. return this.flowParseTypeofType();
  4878. default:
  4879. if (tokenIsKeyword(this.state.type)) {
  4880. const label = tokenLabelName(this.state.type);
  4881. this.next();
  4882. return super.createIdentifier(node, label);
  4883. } else if (tokenIsIdentifier(this.state.type)) {
  4884. if (this.isContextual(129)) {
  4885. return this.flowParseInterfaceType();
  4886. }
  4887. return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier());
  4888. }
  4889. }
  4890. this.unexpected();
  4891. }
  4892. flowParsePostfixType() {
  4893. const startLoc = this.state.startLoc;
  4894. let type = this.flowParsePrimaryType();
  4895. let seenOptionalIndexedAccess = false;
  4896. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  4897. const node = this.startNodeAt(startLoc);
  4898. const optional = this.eat(18);
  4899. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  4900. this.expect(0);
  4901. if (!optional && this.match(3)) {
  4902. node.elementType = type;
  4903. this.next();
  4904. type = this.finishNode(node, "ArrayTypeAnnotation");
  4905. } else {
  4906. node.objectType = type;
  4907. node.indexType = this.flowParseType();
  4908. this.expect(3);
  4909. if (seenOptionalIndexedAccess) {
  4910. node.optional = optional;
  4911. type = this.finishNode(node, "OptionalIndexedAccessType");
  4912. } else {
  4913. type = this.finishNode(node, "IndexedAccessType");
  4914. }
  4915. }
  4916. }
  4917. return type;
  4918. }
  4919. flowParsePrefixType() {
  4920. const node = this.startNode();
  4921. if (this.eat(17)) {
  4922. node.typeAnnotation = this.flowParsePrefixType();
  4923. return this.finishNode(node, "NullableTypeAnnotation");
  4924. } else {
  4925. return this.flowParsePostfixType();
  4926. }
  4927. }
  4928. flowParseAnonFunctionWithoutParens() {
  4929. const param = this.flowParsePrefixType();
  4930. if (!this.state.noAnonFunctionType && this.eat(19)) {
  4931. const node = this.startNodeAt(param.loc.start);
  4932. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  4933. node.rest = null;
  4934. node.this = null;
  4935. node.returnType = this.flowParseType();
  4936. node.typeParameters = null;
  4937. return this.finishNode(node, "FunctionTypeAnnotation");
  4938. }
  4939. return param;
  4940. }
  4941. flowParseIntersectionType() {
  4942. const node = this.startNode();
  4943. this.eat(45);
  4944. const type = this.flowParseAnonFunctionWithoutParens();
  4945. node.types = [type];
  4946. while (this.eat(45)) {
  4947. node.types.push(this.flowParseAnonFunctionWithoutParens());
  4948. }
  4949. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  4950. }
  4951. flowParseUnionType() {
  4952. const node = this.startNode();
  4953. this.eat(43);
  4954. const type = this.flowParseIntersectionType();
  4955. node.types = [type];
  4956. while (this.eat(43)) {
  4957. node.types.push(this.flowParseIntersectionType());
  4958. }
  4959. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  4960. }
  4961. flowParseType() {
  4962. const oldInType = this.state.inType;
  4963. this.state.inType = true;
  4964. const type = this.flowParseUnionType();
  4965. this.state.inType = oldInType;
  4966. return type;
  4967. }
  4968. flowParseTypeOrImplicitInstantiation() {
  4969. if (this.state.type === 132 && this.state.value === "_") {
  4970. const startLoc = this.state.startLoc;
  4971. const node = this.parseIdentifier();
  4972. return this.flowParseGenericType(startLoc, node);
  4973. } else {
  4974. return this.flowParseType();
  4975. }
  4976. }
  4977. flowParseTypeAnnotation() {
  4978. const node = this.startNode();
  4979. node.typeAnnotation = this.flowParseTypeInitialiser();
  4980. return this.finishNode(node, "TypeAnnotation");
  4981. }
  4982. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  4983. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  4984. if (this.match(14)) {
  4985. ident.typeAnnotation = this.flowParseTypeAnnotation();
  4986. this.resetEndLocation(ident);
  4987. }
  4988. return ident;
  4989. }
  4990. typeCastToParameter(node) {
  4991. node.expression.typeAnnotation = node.typeAnnotation;
  4992. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  4993. return node.expression;
  4994. }
  4995. flowParseVariance() {
  4996. let variance = null;
  4997. if (this.match(53)) {
  4998. variance = this.startNode();
  4999. if (this.state.value === "+") {
  5000. variance.kind = "plus";
  5001. } else {
  5002. variance.kind = "minus";
  5003. }
  5004. this.next();
  5005. return this.finishNode(variance, "Variance");
  5006. }
  5007. return variance;
  5008. }
  5009. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5010. if (allowExpressionBody) {
  5011. this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5012. return;
  5013. }
  5014. super.parseFunctionBody(node, false, isMethod);
  5015. }
  5016. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5017. if (this.match(14)) {
  5018. const typeNode = this.startNode();
  5019. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5020. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5021. }
  5022. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  5023. }
  5024. parseStatementLike(flags) {
  5025. if (this.state.strict && this.isContextual(129)) {
  5026. const lookahead = this.lookahead();
  5027. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5028. const node = this.startNode();
  5029. this.next();
  5030. return this.flowParseInterface(node);
  5031. }
  5032. } else if (this.shouldParseEnums() && this.isContextual(126)) {
  5033. const node = this.startNode();
  5034. this.next();
  5035. return this.flowParseEnumDeclaration(node);
  5036. }
  5037. const stmt = super.parseStatementLike(flags);
  5038. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5039. this.flowPragma = null;
  5040. }
  5041. return stmt;
  5042. }
  5043. parseExpressionStatement(node, expr, decorators) {
  5044. if (expr.type === "Identifier") {
  5045. if (expr.name === "declare") {
  5046. if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
  5047. return this.flowParseDeclare(node);
  5048. }
  5049. } else if (tokenIsIdentifier(this.state.type)) {
  5050. if (expr.name === "interface") {
  5051. return this.flowParseInterface(node);
  5052. } else if (expr.name === "type") {
  5053. return this.flowParseTypeAlias(node);
  5054. } else if (expr.name === "opaque") {
  5055. return this.flowParseOpaqueType(node, false);
  5056. }
  5057. }
  5058. }
  5059. return super.parseExpressionStatement(node, expr, decorators);
  5060. }
  5061. shouldParseExportDeclaration() {
  5062. const {
  5063. type
  5064. } = this.state;
  5065. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) {
  5066. return !this.state.containsEsc;
  5067. }
  5068. return super.shouldParseExportDeclaration();
  5069. }
  5070. isExportDefaultSpecifier() {
  5071. const {
  5072. type
  5073. } = this.state;
  5074. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) {
  5075. return this.state.containsEsc;
  5076. }
  5077. return super.isExportDefaultSpecifier();
  5078. }
  5079. parseExportDefaultExpression() {
  5080. if (this.shouldParseEnums() && this.isContextual(126)) {
  5081. const node = this.startNode();
  5082. this.next();
  5083. return this.flowParseEnumDeclaration(node);
  5084. }
  5085. return super.parseExportDefaultExpression();
  5086. }
  5087. parseConditional(expr, startLoc, refExpressionErrors) {
  5088. if (!this.match(17)) return expr;
  5089. if (this.state.maybeInArrowParameters) {
  5090. const nextCh = this.lookaheadCharCode();
  5091. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  5092. this.setOptionalParametersError(refExpressionErrors);
  5093. return expr;
  5094. }
  5095. }
  5096. this.expect(17);
  5097. const state = this.state.clone();
  5098. const originalNoArrowAt = this.state.noArrowAt;
  5099. const node = this.startNodeAt(startLoc);
  5100. let {
  5101. consequent,
  5102. failed
  5103. } = this.tryParseConditionalConsequent();
  5104. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5105. if (failed || invalid.length > 0) {
  5106. const noArrowAt = [...originalNoArrowAt];
  5107. if (invalid.length > 0) {
  5108. this.state = state;
  5109. this.state.noArrowAt = noArrowAt;
  5110. for (let i = 0; i < invalid.length; i++) {
  5111. noArrowAt.push(invalid[i].start);
  5112. }
  5113. ({
  5114. consequent,
  5115. failed
  5116. } = this.tryParseConditionalConsequent());
  5117. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5118. }
  5119. if (failed && valid.length > 1) {
  5120. this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);
  5121. }
  5122. if (failed && valid.length === 1) {
  5123. this.state = state;
  5124. noArrowAt.push(valid[0].start);
  5125. this.state.noArrowAt = noArrowAt;
  5126. ({
  5127. consequent,
  5128. failed
  5129. } = this.tryParseConditionalConsequent());
  5130. }
  5131. }
  5132. this.getArrowLikeExpressions(consequent, true);
  5133. this.state.noArrowAt = originalNoArrowAt;
  5134. this.expect(14);
  5135. node.test = expr;
  5136. node.consequent = consequent;
  5137. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5138. return this.finishNode(node, "ConditionalExpression");
  5139. }
  5140. tryParseConditionalConsequent() {
  5141. this.state.noArrowParamsConversionAt.push(this.state.start);
  5142. const consequent = this.parseMaybeAssignAllowIn();
  5143. const failed = !this.match(14);
  5144. this.state.noArrowParamsConversionAt.pop();
  5145. return {
  5146. consequent,
  5147. failed
  5148. };
  5149. }
  5150. getArrowLikeExpressions(node, disallowInvalid) {
  5151. const stack = [node];
  5152. const arrows = [];
  5153. while (stack.length !== 0) {
  5154. const node = stack.pop();
  5155. if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
  5156. if (node.typeParameters || !node.returnType) {
  5157. this.finishArrowValidation(node);
  5158. } else {
  5159. arrows.push(node);
  5160. }
  5161. stack.push(node.body);
  5162. } else if (node.type === "ConditionalExpression") {
  5163. stack.push(node.consequent);
  5164. stack.push(node.alternate);
  5165. }
  5166. }
  5167. if (disallowInvalid) {
  5168. arrows.forEach(node => this.finishArrowValidation(node));
  5169. return [arrows, []];
  5170. }
  5171. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5172. }
  5173. finishArrowValidation(node) {
  5174. var _node$extra;
  5175. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
  5176. this.scope.enter(2 | 4);
  5177. super.checkParams(node, false, true);
  5178. this.scope.exit();
  5179. }
  5180. forwardNoArrowParamsConversionAt(node, parse) {
  5181. let result;
  5182. if (this.state.noArrowParamsConversionAt.includes(node.start)) {
  5183. this.state.noArrowParamsConversionAt.push(this.state.start);
  5184. result = parse();
  5185. this.state.noArrowParamsConversionAt.pop();
  5186. } else {
  5187. result = parse();
  5188. }
  5189. return result;
  5190. }
  5191. parseParenItem(node, startLoc) {
  5192. const newNode = super.parseParenItem(node, startLoc);
  5193. if (this.eat(17)) {
  5194. newNode.optional = true;
  5195. this.resetEndLocation(node);
  5196. }
  5197. if (this.match(14)) {
  5198. const typeCastNode = this.startNodeAt(startLoc);
  5199. typeCastNode.expression = newNode;
  5200. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5201. return this.finishNode(typeCastNode, "TypeCastExpression");
  5202. }
  5203. return newNode;
  5204. }
  5205. assertModuleNodeAllowed(node) {
  5206. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5207. return;
  5208. }
  5209. super.assertModuleNodeAllowed(node);
  5210. }
  5211. parseExportDeclaration(node) {
  5212. if (this.isContextual(130)) {
  5213. node.exportKind = "type";
  5214. const declarationNode = this.startNode();
  5215. this.next();
  5216. if (this.match(5)) {
  5217. node.specifiers = this.parseExportSpecifiers(true);
  5218. super.parseExportFrom(node);
  5219. return null;
  5220. } else {
  5221. return this.flowParseTypeAlias(declarationNode);
  5222. }
  5223. } else if (this.isContextual(131)) {
  5224. node.exportKind = "type";
  5225. const declarationNode = this.startNode();
  5226. this.next();
  5227. return this.flowParseOpaqueType(declarationNode, false);
  5228. } else if (this.isContextual(129)) {
  5229. node.exportKind = "type";
  5230. const declarationNode = this.startNode();
  5231. this.next();
  5232. return this.flowParseInterface(declarationNode);
  5233. } else if (this.shouldParseEnums() && this.isContextual(126)) {
  5234. node.exportKind = "value";
  5235. const declarationNode = this.startNode();
  5236. this.next();
  5237. return this.flowParseEnumDeclaration(declarationNode);
  5238. } else {
  5239. return super.parseExportDeclaration(node);
  5240. }
  5241. }
  5242. eatExportStar(node) {
  5243. if (super.eatExportStar(node)) return true;
  5244. if (this.isContextual(130) && this.lookahead().type === 55) {
  5245. node.exportKind = "type";
  5246. this.next();
  5247. this.next();
  5248. return true;
  5249. }
  5250. return false;
  5251. }
  5252. maybeParseExportNamespaceSpecifier(node) {
  5253. const {
  5254. startLoc
  5255. } = this.state;
  5256. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5257. if (hasNamespace && node.exportKind === "type") {
  5258. this.unexpected(startLoc);
  5259. }
  5260. return hasNamespace;
  5261. }
  5262. parseClassId(node, isStatement, optionalId) {
  5263. super.parseClassId(node, isStatement, optionalId);
  5264. if (this.match(47)) {
  5265. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5266. }
  5267. }
  5268. parseClassMember(classBody, member, state) {
  5269. const {
  5270. startLoc
  5271. } = this.state;
  5272. if (this.isContextual(125)) {
  5273. if (super.parseClassMemberFromModifier(classBody, member)) {
  5274. return;
  5275. }
  5276. member.declare = true;
  5277. }
  5278. super.parseClassMember(classBody, member, state);
  5279. if (member.declare) {
  5280. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5281. this.raise(FlowErrors.DeclareClassElement, startLoc);
  5282. } else if (member.value) {
  5283. this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);
  5284. }
  5285. }
  5286. }
  5287. isIterator(word) {
  5288. return word === "iterator" || word === "asyncIterator";
  5289. }
  5290. readIterator() {
  5291. const word = super.readWord1();
  5292. const fullWord = "@@" + word;
  5293. if (!this.isIterator(word) || !this.state.inType) {
  5294. this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {
  5295. identifierName: fullWord
  5296. });
  5297. }
  5298. this.finishToken(132, fullWord);
  5299. }
  5300. getTokenFromCode(code) {
  5301. const next = this.input.charCodeAt(this.state.pos + 1);
  5302. if (code === 123 && next === 124) {
  5303. this.finishOp(6, 2);
  5304. } else if (this.state.inType && (code === 62 || code === 60)) {
  5305. this.finishOp(code === 62 ? 48 : 47, 1);
  5306. } else if (this.state.inType && code === 63) {
  5307. if (next === 46) {
  5308. this.finishOp(18, 2);
  5309. } else {
  5310. this.finishOp(17, 1);
  5311. }
  5312. } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
  5313. this.state.pos += 2;
  5314. this.readIterator();
  5315. } else {
  5316. super.getTokenFromCode(code);
  5317. }
  5318. }
  5319. isAssignable(node, isBinding) {
  5320. if (node.type === "TypeCastExpression") {
  5321. return this.isAssignable(node.expression, isBinding);
  5322. } else {
  5323. return super.isAssignable(node, isBinding);
  5324. }
  5325. }
  5326. toAssignable(node, isLHS = false) {
  5327. if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") {
  5328. node.left = this.typeCastToParameter(node.left);
  5329. }
  5330. super.toAssignable(node, isLHS);
  5331. }
  5332. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  5333. for (let i = 0; i < exprList.length; i++) {
  5334. const expr = exprList[i];
  5335. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5336. exprList[i] = this.typeCastToParameter(expr);
  5337. }
  5338. }
  5339. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  5340. }
  5341. toReferencedList(exprList, isParenthesizedExpr) {
  5342. for (let i = 0; i < exprList.length; i++) {
  5343. var _expr$extra;
  5344. const expr = exprList[i];
  5345. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5346. this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);
  5347. }
  5348. }
  5349. return exprList;
  5350. }
  5351. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5352. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5353. if (canBePattern && !this.state.maybeInArrowParameters) {
  5354. this.toReferencedList(node.elements);
  5355. }
  5356. return node;
  5357. }
  5358. isValidLVal(type, isParenthesized, binding) {
  5359. return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding);
  5360. }
  5361. parseClassProperty(node) {
  5362. if (this.match(14)) {
  5363. node.typeAnnotation = this.flowParseTypeAnnotation();
  5364. }
  5365. return super.parseClassProperty(node);
  5366. }
  5367. parseClassPrivateProperty(node) {
  5368. if (this.match(14)) {
  5369. node.typeAnnotation = this.flowParseTypeAnnotation();
  5370. }
  5371. return super.parseClassPrivateProperty(node);
  5372. }
  5373. isClassMethod() {
  5374. return this.match(47) || super.isClassMethod();
  5375. }
  5376. isClassProperty() {
  5377. return this.match(14) || super.isClassProperty();
  5378. }
  5379. isNonstaticConstructor(method) {
  5380. return !this.match(14) && super.isNonstaticConstructor(method);
  5381. }
  5382. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5383. if (method.variance) {
  5384. this.unexpected(method.variance.loc.start);
  5385. }
  5386. delete method.variance;
  5387. if (this.match(47)) {
  5388. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5389. }
  5390. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5391. if (method.params && isConstructor) {
  5392. const params = method.params;
  5393. if (params.length > 0 && this.isThisParam(params[0])) {
  5394. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  5395. }
  5396. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  5397. const params = method.value.params;
  5398. if (params.length > 0 && this.isThisParam(params[0])) {
  5399. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  5400. }
  5401. }
  5402. }
  5403. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5404. if (method.variance) {
  5405. this.unexpected(method.variance.loc.start);
  5406. }
  5407. delete method.variance;
  5408. if (this.match(47)) {
  5409. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5410. }
  5411. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5412. }
  5413. parseClassSuper(node) {
  5414. super.parseClassSuper(node);
  5415. if (node.superClass && this.match(47)) {
  5416. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  5417. }
  5418. if (this.isContextual(113)) {
  5419. this.next();
  5420. const implemented = node.implements = [];
  5421. do {
  5422. const node = this.startNode();
  5423. node.id = this.flowParseRestrictedIdentifier(true);
  5424. if (this.match(47)) {
  5425. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5426. } else {
  5427. node.typeParameters = null;
  5428. }
  5429. implemented.push(this.finishNode(node, "ClassImplements"));
  5430. } while (this.eat(12));
  5431. }
  5432. }
  5433. checkGetterSetterParams(method) {
  5434. super.checkGetterSetterParams(method);
  5435. const params = this.getObjectOrClassMethodParams(method);
  5436. if (params.length > 0) {
  5437. const param = params[0];
  5438. if (this.isThisParam(param) && method.kind === "get") {
  5439. this.raise(FlowErrors.GetterMayNotHaveThisParam, param);
  5440. } else if (this.isThisParam(param)) {
  5441. this.raise(FlowErrors.SetterMayNotHaveThisParam, param);
  5442. }
  5443. }
  5444. }
  5445. parsePropertyNamePrefixOperator(node) {
  5446. node.variance = this.flowParseVariance();
  5447. }
  5448. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5449. if (prop.variance) {
  5450. this.unexpected(prop.variance.loc.start);
  5451. }
  5452. delete prop.variance;
  5453. let typeParameters;
  5454. if (this.match(47) && !isAccessor) {
  5455. typeParameters = this.flowParseTypeParameterDeclaration();
  5456. if (!this.match(10)) this.unexpected();
  5457. }
  5458. const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5459. if (typeParameters) {
  5460. (result.value || result).typeParameters = typeParameters;
  5461. }
  5462. return result;
  5463. }
  5464. parseAssignableListItemTypes(param) {
  5465. if (this.eat(17)) {
  5466. if (param.type !== "Identifier") {
  5467. this.raise(FlowErrors.PatternIsOptional, param);
  5468. }
  5469. if (this.isThisParam(param)) {
  5470. this.raise(FlowErrors.ThisParamMayNotBeOptional, param);
  5471. }
  5472. param.optional = true;
  5473. }
  5474. if (this.match(14)) {
  5475. param.typeAnnotation = this.flowParseTypeAnnotation();
  5476. } else if (this.isThisParam(param)) {
  5477. this.raise(FlowErrors.ThisParamAnnotationRequired, param);
  5478. }
  5479. if (this.match(29) && this.isThisParam(param)) {
  5480. this.raise(FlowErrors.ThisParamNoDefault, param);
  5481. }
  5482. this.resetEndLocation(param);
  5483. return param;
  5484. }
  5485. parseMaybeDefault(startLoc, left) {
  5486. const node = super.parseMaybeDefault(startLoc, left);
  5487. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5488. this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);
  5489. }
  5490. return node;
  5491. }
  5492. checkImportReflection(node) {
  5493. super.checkImportReflection(node);
  5494. if (node.module && node.importKind !== "value") {
  5495. this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  5496. }
  5497. }
  5498. parseImportSpecifierLocal(node, specifier, type) {
  5499. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5500. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  5501. }
  5502. isPotentialImportPhase(isExport) {
  5503. if (super.isPotentialImportPhase(isExport)) return true;
  5504. if (this.isContextual(130)) {
  5505. if (!isExport) return true;
  5506. const ch = this.lookaheadCharCode();
  5507. return ch === 123 || ch === 42;
  5508. }
  5509. return !isExport && this.isContextual(87);
  5510. }
  5511. applyImportPhase(node, isExport, phase, loc) {
  5512. super.applyImportPhase(node, isExport, phase, loc);
  5513. if (isExport) {
  5514. if (!phase && this.match(65)) {
  5515. return;
  5516. }
  5517. node.exportKind = phase === "type" ? phase : "value";
  5518. } else {
  5519. if (phase === "type" && this.match(55)) this.unexpected();
  5520. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  5521. }
  5522. }
  5523. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  5524. const firstIdent = specifier.imported;
  5525. let specifierTypeKind = null;
  5526. if (firstIdent.type === "Identifier") {
  5527. if (firstIdent.name === "type") {
  5528. specifierTypeKind = "type";
  5529. } else if (firstIdent.name === "typeof") {
  5530. specifierTypeKind = "typeof";
  5531. }
  5532. }
  5533. let isBinding = false;
  5534. if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
  5535. const as_ident = this.parseIdentifier(true);
  5536. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5537. specifier.imported = as_ident;
  5538. specifier.importKind = specifierTypeKind;
  5539. specifier.local = cloneIdentifier(as_ident);
  5540. } else {
  5541. specifier.imported = firstIdent;
  5542. specifier.importKind = null;
  5543. specifier.local = this.parseIdentifier();
  5544. }
  5545. } else {
  5546. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5547. specifier.imported = this.parseIdentifier(true);
  5548. specifier.importKind = specifierTypeKind;
  5549. } else {
  5550. if (importedIsString) {
  5551. throw this.raise(Errors.ImportBindingIsString, specifier, {
  5552. importName: firstIdent.value
  5553. });
  5554. }
  5555. specifier.imported = firstIdent;
  5556. specifier.importKind = null;
  5557. }
  5558. if (this.eatContextual(93)) {
  5559. specifier.local = this.parseIdentifier();
  5560. } else {
  5561. isBinding = true;
  5562. specifier.local = cloneIdentifier(specifier.imported);
  5563. }
  5564. }
  5565. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5566. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5567. this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);
  5568. }
  5569. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5570. this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
  5571. }
  5572. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5573. this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
  5574. }
  5575. return this.finishImportSpecifier(specifier, "ImportSpecifier");
  5576. }
  5577. parseBindingAtom() {
  5578. switch (this.state.type) {
  5579. case 78:
  5580. return this.parseIdentifier(true);
  5581. default:
  5582. return super.parseBindingAtom();
  5583. }
  5584. }
  5585. parseFunctionParams(node, isConstructor) {
  5586. const kind = node.kind;
  5587. if (kind !== "get" && kind !== "set" && this.match(47)) {
  5588. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5589. }
  5590. super.parseFunctionParams(node, isConstructor);
  5591. }
  5592. parseVarId(decl, kind) {
  5593. super.parseVarId(decl, kind);
  5594. if (this.match(14)) {
  5595. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5596. this.resetEndLocation(decl.id);
  5597. }
  5598. }
  5599. parseAsyncArrowFromCallExpression(node, call) {
  5600. if (this.match(14)) {
  5601. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5602. this.state.noAnonFunctionType = true;
  5603. node.returnType = this.flowParseTypeAnnotation();
  5604. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5605. }
  5606. return super.parseAsyncArrowFromCallExpression(node, call);
  5607. }
  5608. shouldParseAsyncArrow() {
  5609. return this.match(14) || super.shouldParseAsyncArrow();
  5610. }
  5611. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5612. var _jsx;
  5613. let state = null;
  5614. let jsx;
  5615. if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) {
  5616. state = this.state.clone();
  5617. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5618. if (!jsx.error) return jsx.node;
  5619. const {
  5620. context
  5621. } = this.state;
  5622. const currentContext = context[context.length - 1];
  5623. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  5624. context.pop();
  5625. }
  5626. }
  5627. if ((_jsx = jsx) != null && _jsx.error || this.match(47)) {
  5628. var _jsx2, _jsx3;
  5629. state = state || this.state.clone();
  5630. let typeParameters;
  5631. const arrow = this.tryParse(abort => {
  5632. var _arrowExpression$extr;
  5633. typeParameters = this.flowParseTypeParameterDeclaration();
  5634. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5635. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5636. this.resetStartLocationFromNode(result, typeParameters);
  5637. return result;
  5638. });
  5639. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5640. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5641. if (expr.type !== "ArrowFunctionExpression") abort();
  5642. expr.typeParameters = typeParameters;
  5643. this.resetStartLocationFromNode(expr, typeParameters);
  5644. return arrowExpression;
  5645. }, state);
  5646. let arrowExpression = null;
  5647. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5648. if (!arrow.error && !arrow.aborted) {
  5649. if (arrow.node.async) {
  5650. this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters);
  5651. }
  5652. return arrow.node;
  5653. }
  5654. arrowExpression = arrow.node;
  5655. }
  5656. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5657. this.state = jsx.failState;
  5658. return jsx.node;
  5659. }
  5660. if (arrowExpression) {
  5661. this.state = arrow.failState;
  5662. return arrowExpression;
  5663. }
  5664. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5665. if (arrow.thrown) throw arrow.error;
  5666. throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters);
  5667. }
  5668. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5669. }
  5670. parseArrow(node) {
  5671. if (this.match(14)) {
  5672. const result = this.tryParse(() => {
  5673. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5674. this.state.noAnonFunctionType = true;
  5675. const typeNode = this.startNode();
  5676. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5677. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5678. if (this.canInsertSemicolon()) this.unexpected();
  5679. if (!this.match(19)) this.unexpected();
  5680. return typeNode;
  5681. });
  5682. if (result.thrown) return null;
  5683. if (result.error) this.state = result.failState;
  5684. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5685. }
  5686. return super.parseArrow(node);
  5687. }
  5688. shouldParseArrow(params) {
  5689. return this.match(14) || super.shouldParseArrow(params);
  5690. }
  5691. setArrowFunctionParameters(node, params) {
  5692. if (this.state.noArrowParamsConversionAt.includes(node.start)) {
  5693. node.params = params;
  5694. } else {
  5695. super.setArrowFunctionParameters(node, params);
  5696. }
  5697. }
  5698. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  5699. if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(node.start)) {
  5700. return;
  5701. }
  5702. for (let i = 0; i < node.params.length; i++) {
  5703. if (this.isThisParam(node.params[i]) && i > 0) {
  5704. this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);
  5705. }
  5706. }
  5707. super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
  5708. }
  5709. parseParenAndDistinguishExpression(canBeArrow) {
  5710. return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.state.start));
  5711. }
  5712. parseSubscripts(base, startLoc, noCalls) {
  5713. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) {
  5714. this.next();
  5715. const node = this.startNodeAt(startLoc);
  5716. node.callee = base;
  5717. node.arguments = super.parseCallExpressionArguments(11, false);
  5718. base = this.finishNode(node, "CallExpression");
  5719. } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) {
  5720. const state = this.state.clone();
  5721. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
  5722. if (!arrow.error && !arrow.aborted) return arrow.node;
  5723. const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state);
  5724. if (result.node && !result.error) return result.node;
  5725. if (arrow.node) {
  5726. this.state = arrow.failState;
  5727. return arrow.node;
  5728. }
  5729. if (result.node) {
  5730. this.state = result.failState;
  5731. return result.node;
  5732. }
  5733. throw arrow.error || result.error;
  5734. }
  5735. return super.parseSubscripts(base, startLoc, noCalls);
  5736. }
  5737. parseSubscript(base, startLoc, noCalls, subscriptState) {
  5738. if (this.match(18) && this.isLookaheadToken_lt()) {
  5739. subscriptState.optionalChainMember = true;
  5740. if (noCalls) {
  5741. subscriptState.stop = true;
  5742. return base;
  5743. }
  5744. this.next();
  5745. const node = this.startNodeAt(startLoc);
  5746. node.callee = base;
  5747. node.typeArguments = this.flowParseTypeParameterInstantiation();
  5748. this.expect(10);
  5749. node.arguments = this.parseCallExpressionArguments(11, false);
  5750. node.optional = true;
  5751. return this.finishCallExpression(node, true);
  5752. } else if (!noCalls && this.shouldParseTypes() && this.match(47)) {
  5753. const node = this.startNodeAt(startLoc);
  5754. node.callee = base;
  5755. const result = this.tryParse(() => {
  5756. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5757. this.expect(10);
  5758. node.arguments = super.parseCallExpressionArguments(11, false);
  5759. if (subscriptState.optionalChainMember) {
  5760. node.optional = false;
  5761. }
  5762. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  5763. });
  5764. if (result.node) {
  5765. if (result.error) this.state = result.failState;
  5766. return result.node;
  5767. }
  5768. }
  5769. return super.parseSubscript(base, startLoc, noCalls, subscriptState);
  5770. }
  5771. parseNewCallee(node) {
  5772. super.parseNewCallee(node);
  5773. let targs = null;
  5774. if (this.shouldParseTypes() && this.match(47)) {
  5775. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  5776. }
  5777. node.typeArguments = targs;
  5778. }
  5779. parseAsyncArrowWithTypeParameters(startLoc) {
  5780. const node = this.startNodeAt(startLoc);
  5781. this.parseFunctionParams(node, false);
  5782. if (!this.parseArrow(node)) return;
  5783. return super.parseArrowExpression(node, undefined, true);
  5784. }
  5785. readToken_mult_modulo(code) {
  5786. const next = this.input.charCodeAt(this.state.pos + 1);
  5787. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  5788. this.state.hasFlowComment = false;
  5789. this.state.pos += 2;
  5790. this.nextToken();
  5791. return;
  5792. }
  5793. super.readToken_mult_modulo(code);
  5794. }
  5795. readToken_pipe_amp(code) {
  5796. const next = this.input.charCodeAt(this.state.pos + 1);
  5797. if (code === 124 && next === 125) {
  5798. this.finishOp(9, 2);
  5799. return;
  5800. }
  5801. super.readToken_pipe_amp(code);
  5802. }
  5803. parseTopLevel(file, program) {
  5804. const fileNode = super.parseTopLevel(file, program);
  5805. if (this.state.hasFlowComment) {
  5806. this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition());
  5807. }
  5808. return fileNode;
  5809. }
  5810. skipBlockComment() {
  5811. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  5812. if (this.state.hasFlowComment) {
  5813. throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);
  5814. }
  5815. this.hasFlowCommentCompletion();
  5816. const commentSkip = this.skipFlowComment();
  5817. if (commentSkip) {
  5818. this.state.pos += commentSkip;
  5819. this.state.hasFlowComment = true;
  5820. }
  5821. return;
  5822. }
  5823. return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  5824. }
  5825. skipFlowComment() {
  5826. const {
  5827. pos
  5828. } = this.state;
  5829. let shiftToFirstNonWhiteSpace = 2;
  5830. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  5831. shiftToFirstNonWhiteSpace++;
  5832. }
  5833. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  5834. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  5835. if (ch2 === 58 && ch3 === 58) {
  5836. return shiftToFirstNonWhiteSpace + 2;
  5837. }
  5838. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  5839. return shiftToFirstNonWhiteSpace + 12;
  5840. }
  5841. if (ch2 === 58 && ch3 !== 58) {
  5842. return shiftToFirstNonWhiteSpace;
  5843. }
  5844. return false;
  5845. }
  5846. hasFlowCommentCompletion() {
  5847. const end = this.input.indexOf("*/", this.state.pos);
  5848. if (end === -1) {
  5849. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  5850. }
  5851. }
  5852. flowEnumErrorBooleanMemberNotInitialized(loc, {
  5853. enumName,
  5854. memberName
  5855. }) {
  5856. this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {
  5857. memberName,
  5858. enumName
  5859. });
  5860. }
  5861. flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
  5862. return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext);
  5863. }
  5864. flowEnumErrorNumberMemberNotInitialized(loc, details) {
  5865. this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);
  5866. }
  5867. flowEnumErrorStringMemberInconsistentlyInitialized(node, details) {
  5868. this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details);
  5869. }
  5870. flowEnumMemberInit() {
  5871. const startLoc = this.state.startLoc;
  5872. const endOfInit = () => this.match(12) || this.match(8);
  5873. switch (this.state.type) {
  5874. case 134:
  5875. {
  5876. const literal = this.parseNumericLiteral(this.state.value);
  5877. if (endOfInit()) {
  5878. return {
  5879. type: "number",
  5880. loc: literal.loc.start,
  5881. value: literal
  5882. };
  5883. }
  5884. return {
  5885. type: "invalid",
  5886. loc: startLoc
  5887. };
  5888. }
  5889. case 133:
  5890. {
  5891. const literal = this.parseStringLiteral(this.state.value);
  5892. if (endOfInit()) {
  5893. return {
  5894. type: "string",
  5895. loc: literal.loc.start,
  5896. value: literal
  5897. };
  5898. }
  5899. return {
  5900. type: "invalid",
  5901. loc: startLoc
  5902. };
  5903. }
  5904. case 85:
  5905. case 86:
  5906. {
  5907. const literal = this.parseBooleanLiteral(this.match(85));
  5908. if (endOfInit()) {
  5909. return {
  5910. type: "boolean",
  5911. loc: literal.loc.start,
  5912. value: literal
  5913. };
  5914. }
  5915. return {
  5916. type: "invalid",
  5917. loc: startLoc
  5918. };
  5919. }
  5920. default:
  5921. return {
  5922. type: "invalid",
  5923. loc: startLoc
  5924. };
  5925. }
  5926. }
  5927. flowEnumMemberRaw() {
  5928. const loc = this.state.startLoc;
  5929. const id = this.parseIdentifier(true);
  5930. const init = this.eat(29) ? this.flowEnumMemberInit() : {
  5931. type: "none",
  5932. loc
  5933. };
  5934. return {
  5935. id,
  5936. init
  5937. };
  5938. }
  5939. flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
  5940. const {
  5941. explicitType
  5942. } = context;
  5943. if (explicitType === null) {
  5944. return;
  5945. }
  5946. if (explicitType !== expectedType) {
  5947. this.flowEnumErrorInvalidMemberInitializer(loc, context);
  5948. }
  5949. }
  5950. flowEnumMembers({
  5951. enumName,
  5952. explicitType
  5953. }) {
  5954. const seenNames = new Set();
  5955. const members = {
  5956. booleanMembers: [],
  5957. numberMembers: [],
  5958. stringMembers: [],
  5959. defaultedMembers: []
  5960. };
  5961. let hasUnknownMembers = false;
  5962. while (!this.match(8)) {
  5963. if (this.eat(21)) {
  5964. hasUnknownMembers = true;
  5965. break;
  5966. }
  5967. const memberNode = this.startNode();
  5968. const {
  5969. id,
  5970. init
  5971. } = this.flowEnumMemberRaw();
  5972. const memberName = id.name;
  5973. if (memberName === "") {
  5974. continue;
  5975. }
  5976. if (/^[a-z]/.test(memberName)) {
  5977. this.raise(FlowErrors.EnumInvalidMemberName, id, {
  5978. memberName,
  5979. suggestion: memberName[0].toUpperCase() + memberName.slice(1),
  5980. enumName
  5981. });
  5982. }
  5983. if (seenNames.has(memberName)) {
  5984. this.raise(FlowErrors.EnumDuplicateMemberName, id, {
  5985. memberName,
  5986. enumName
  5987. });
  5988. }
  5989. seenNames.add(memberName);
  5990. const context = {
  5991. enumName,
  5992. explicitType,
  5993. memberName
  5994. };
  5995. memberNode.id = id;
  5996. switch (init.type) {
  5997. case "boolean":
  5998. {
  5999. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean");
  6000. memberNode.init = init.value;
  6001. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6002. break;
  6003. }
  6004. case "number":
  6005. {
  6006. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number");
  6007. memberNode.init = init.value;
  6008. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6009. break;
  6010. }
  6011. case "string":
  6012. {
  6013. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string");
  6014. memberNode.init = init.value;
  6015. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6016. break;
  6017. }
  6018. case "invalid":
  6019. {
  6020. throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);
  6021. }
  6022. case "none":
  6023. {
  6024. switch (explicitType) {
  6025. case "boolean":
  6026. this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context);
  6027. break;
  6028. case "number":
  6029. this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);
  6030. break;
  6031. default:
  6032. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6033. }
  6034. }
  6035. }
  6036. if (!this.match(8)) {
  6037. this.expect(12);
  6038. }
  6039. }
  6040. return {
  6041. members,
  6042. hasUnknownMembers
  6043. };
  6044. }
  6045. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6046. enumName
  6047. }) {
  6048. if (initializedMembers.length === 0) {
  6049. return defaultedMembers;
  6050. } else if (defaultedMembers.length === 0) {
  6051. return initializedMembers;
  6052. } else if (defaultedMembers.length > initializedMembers.length) {
  6053. for (const member of initializedMembers) {
  6054. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  6055. enumName
  6056. });
  6057. }
  6058. return defaultedMembers;
  6059. } else {
  6060. for (const member of defaultedMembers) {
  6061. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  6062. enumName
  6063. });
  6064. }
  6065. return initializedMembers;
  6066. }
  6067. }
  6068. flowEnumParseExplicitType({
  6069. enumName
  6070. }) {
  6071. if (!this.eatContextual(102)) return null;
  6072. if (!tokenIsIdentifier(this.state.type)) {
  6073. throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, {
  6074. enumName
  6075. });
  6076. }
  6077. const {
  6078. value
  6079. } = this.state;
  6080. this.next();
  6081. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6082. this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {
  6083. enumName,
  6084. invalidEnumType: value
  6085. });
  6086. }
  6087. return value;
  6088. }
  6089. flowEnumBody(node, id) {
  6090. const enumName = id.name;
  6091. const nameLoc = id.loc.start;
  6092. const explicitType = this.flowEnumParseExplicitType({
  6093. enumName
  6094. });
  6095. this.expect(5);
  6096. const {
  6097. members,
  6098. hasUnknownMembers
  6099. } = this.flowEnumMembers({
  6100. enumName,
  6101. explicitType
  6102. });
  6103. node.hasUnknownMembers = hasUnknownMembers;
  6104. switch (explicitType) {
  6105. case "boolean":
  6106. node.explicitType = true;
  6107. node.members = members.booleanMembers;
  6108. this.expect(8);
  6109. return this.finishNode(node, "EnumBooleanBody");
  6110. case "number":
  6111. node.explicitType = true;
  6112. node.members = members.numberMembers;
  6113. this.expect(8);
  6114. return this.finishNode(node, "EnumNumberBody");
  6115. case "string":
  6116. node.explicitType = true;
  6117. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6118. enumName
  6119. });
  6120. this.expect(8);
  6121. return this.finishNode(node, "EnumStringBody");
  6122. case "symbol":
  6123. node.members = members.defaultedMembers;
  6124. this.expect(8);
  6125. return this.finishNode(node, "EnumSymbolBody");
  6126. default:
  6127. {
  6128. const empty = () => {
  6129. node.members = [];
  6130. this.expect(8);
  6131. return this.finishNode(node, "EnumStringBody");
  6132. };
  6133. node.explicitType = false;
  6134. const boolsLen = members.booleanMembers.length;
  6135. const numsLen = members.numberMembers.length;
  6136. const strsLen = members.stringMembers.length;
  6137. const defaultedLen = members.defaultedMembers.length;
  6138. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6139. return empty();
  6140. } else if (!boolsLen && !numsLen) {
  6141. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6142. enumName
  6143. });
  6144. this.expect(8);
  6145. return this.finishNode(node, "EnumStringBody");
  6146. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6147. for (const member of members.defaultedMembers) {
  6148. this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
  6149. enumName,
  6150. memberName: member.id.name
  6151. });
  6152. }
  6153. node.members = members.booleanMembers;
  6154. this.expect(8);
  6155. return this.finishNode(node, "EnumBooleanBody");
  6156. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6157. for (const member of members.defaultedMembers) {
  6158. this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
  6159. enumName,
  6160. memberName: member.id.name
  6161. });
  6162. }
  6163. node.members = members.numberMembers;
  6164. this.expect(8);
  6165. return this.finishNode(node, "EnumNumberBody");
  6166. } else {
  6167. this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {
  6168. enumName
  6169. });
  6170. return empty();
  6171. }
  6172. }
  6173. }
  6174. }
  6175. flowParseEnumDeclaration(node) {
  6176. const id = this.parseIdentifier();
  6177. node.id = id;
  6178. node.body = this.flowEnumBody(this.startNode(), id);
  6179. return this.finishNode(node, "EnumDeclaration");
  6180. }
  6181. isLookaheadToken_lt() {
  6182. const next = this.nextTokenStart();
  6183. if (this.input.charCodeAt(next) === 60) {
  6184. const afterNext = this.input.charCodeAt(next + 1);
  6185. return afterNext !== 60 && afterNext !== 61;
  6186. }
  6187. return false;
  6188. }
  6189. maybeUnwrapTypeCastExpression(node) {
  6190. return node.type === "TypeCastExpression" ? node.expression : node;
  6191. }
  6192. };
  6193. const entities = {
  6194. __proto__: null,
  6195. quot: "\u0022",
  6196. amp: "&",
  6197. apos: "\u0027",
  6198. lt: "<",
  6199. gt: ">",
  6200. nbsp: "\u00A0",
  6201. iexcl: "\u00A1",
  6202. cent: "\u00A2",
  6203. pound: "\u00A3",
  6204. curren: "\u00A4",
  6205. yen: "\u00A5",
  6206. brvbar: "\u00A6",
  6207. sect: "\u00A7",
  6208. uml: "\u00A8",
  6209. copy: "\u00A9",
  6210. ordf: "\u00AA",
  6211. laquo: "\u00AB",
  6212. not: "\u00AC",
  6213. shy: "\u00AD",
  6214. reg: "\u00AE",
  6215. macr: "\u00AF",
  6216. deg: "\u00B0",
  6217. plusmn: "\u00B1",
  6218. sup2: "\u00B2",
  6219. sup3: "\u00B3",
  6220. acute: "\u00B4",
  6221. micro: "\u00B5",
  6222. para: "\u00B6",
  6223. middot: "\u00B7",
  6224. cedil: "\u00B8",
  6225. sup1: "\u00B9",
  6226. ordm: "\u00BA",
  6227. raquo: "\u00BB",
  6228. frac14: "\u00BC",
  6229. frac12: "\u00BD",
  6230. frac34: "\u00BE",
  6231. iquest: "\u00BF",
  6232. Agrave: "\u00C0",
  6233. Aacute: "\u00C1",
  6234. Acirc: "\u00C2",
  6235. Atilde: "\u00C3",
  6236. Auml: "\u00C4",
  6237. Aring: "\u00C5",
  6238. AElig: "\u00C6",
  6239. Ccedil: "\u00C7",
  6240. Egrave: "\u00C8",
  6241. Eacute: "\u00C9",
  6242. Ecirc: "\u00CA",
  6243. Euml: "\u00CB",
  6244. Igrave: "\u00CC",
  6245. Iacute: "\u00CD",
  6246. Icirc: "\u00CE",
  6247. Iuml: "\u00CF",
  6248. ETH: "\u00D0",
  6249. Ntilde: "\u00D1",
  6250. Ograve: "\u00D2",
  6251. Oacute: "\u00D3",
  6252. Ocirc: "\u00D4",
  6253. Otilde: "\u00D5",
  6254. Ouml: "\u00D6",
  6255. times: "\u00D7",
  6256. Oslash: "\u00D8",
  6257. Ugrave: "\u00D9",
  6258. Uacute: "\u00DA",
  6259. Ucirc: "\u00DB",
  6260. Uuml: "\u00DC",
  6261. Yacute: "\u00DD",
  6262. THORN: "\u00DE",
  6263. szlig: "\u00DF",
  6264. agrave: "\u00E0",
  6265. aacute: "\u00E1",
  6266. acirc: "\u00E2",
  6267. atilde: "\u00E3",
  6268. auml: "\u00E4",
  6269. aring: "\u00E5",
  6270. aelig: "\u00E6",
  6271. ccedil: "\u00E7",
  6272. egrave: "\u00E8",
  6273. eacute: "\u00E9",
  6274. ecirc: "\u00EA",
  6275. euml: "\u00EB",
  6276. igrave: "\u00EC",
  6277. iacute: "\u00ED",
  6278. icirc: "\u00EE",
  6279. iuml: "\u00EF",
  6280. eth: "\u00F0",
  6281. ntilde: "\u00F1",
  6282. ograve: "\u00F2",
  6283. oacute: "\u00F3",
  6284. ocirc: "\u00F4",
  6285. otilde: "\u00F5",
  6286. ouml: "\u00F6",
  6287. divide: "\u00F7",
  6288. oslash: "\u00F8",
  6289. ugrave: "\u00F9",
  6290. uacute: "\u00FA",
  6291. ucirc: "\u00FB",
  6292. uuml: "\u00FC",
  6293. yacute: "\u00FD",
  6294. thorn: "\u00FE",
  6295. yuml: "\u00FF",
  6296. OElig: "\u0152",
  6297. oelig: "\u0153",
  6298. Scaron: "\u0160",
  6299. scaron: "\u0161",
  6300. Yuml: "\u0178",
  6301. fnof: "\u0192",
  6302. circ: "\u02C6",
  6303. tilde: "\u02DC",
  6304. Alpha: "\u0391",
  6305. Beta: "\u0392",
  6306. Gamma: "\u0393",
  6307. Delta: "\u0394",
  6308. Epsilon: "\u0395",
  6309. Zeta: "\u0396",
  6310. Eta: "\u0397",
  6311. Theta: "\u0398",
  6312. Iota: "\u0399",
  6313. Kappa: "\u039A",
  6314. Lambda: "\u039B",
  6315. Mu: "\u039C",
  6316. Nu: "\u039D",
  6317. Xi: "\u039E",
  6318. Omicron: "\u039F",
  6319. Pi: "\u03A0",
  6320. Rho: "\u03A1",
  6321. Sigma: "\u03A3",
  6322. Tau: "\u03A4",
  6323. Upsilon: "\u03A5",
  6324. Phi: "\u03A6",
  6325. Chi: "\u03A7",
  6326. Psi: "\u03A8",
  6327. Omega: "\u03A9",
  6328. alpha: "\u03B1",
  6329. beta: "\u03B2",
  6330. gamma: "\u03B3",
  6331. delta: "\u03B4",
  6332. epsilon: "\u03B5",
  6333. zeta: "\u03B6",
  6334. eta: "\u03B7",
  6335. theta: "\u03B8",
  6336. iota: "\u03B9",
  6337. kappa: "\u03BA",
  6338. lambda: "\u03BB",
  6339. mu: "\u03BC",
  6340. nu: "\u03BD",
  6341. xi: "\u03BE",
  6342. omicron: "\u03BF",
  6343. pi: "\u03C0",
  6344. rho: "\u03C1",
  6345. sigmaf: "\u03C2",
  6346. sigma: "\u03C3",
  6347. tau: "\u03C4",
  6348. upsilon: "\u03C5",
  6349. phi: "\u03C6",
  6350. chi: "\u03C7",
  6351. psi: "\u03C8",
  6352. omega: "\u03C9",
  6353. thetasym: "\u03D1",
  6354. upsih: "\u03D2",
  6355. piv: "\u03D6",
  6356. ensp: "\u2002",
  6357. emsp: "\u2003",
  6358. thinsp: "\u2009",
  6359. zwnj: "\u200C",
  6360. zwj: "\u200D",
  6361. lrm: "\u200E",
  6362. rlm: "\u200F",
  6363. ndash: "\u2013",
  6364. mdash: "\u2014",
  6365. lsquo: "\u2018",
  6366. rsquo: "\u2019",
  6367. sbquo: "\u201A",
  6368. ldquo: "\u201C",
  6369. rdquo: "\u201D",
  6370. bdquo: "\u201E",
  6371. dagger: "\u2020",
  6372. Dagger: "\u2021",
  6373. bull: "\u2022",
  6374. hellip: "\u2026",
  6375. permil: "\u2030",
  6376. prime: "\u2032",
  6377. Prime: "\u2033",
  6378. lsaquo: "\u2039",
  6379. rsaquo: "\u203A",
  6380. oline: "\u203E",
  6381. frasl: "\u2044",
  6382. euro: "\u20AC",
  6383. image: "\u2111",
  6384. weierp: "\u2118",
  6385. real: "\u211C",
  6386. trade: "\u2122",
  6387. alefsym: "\u2135",
  6388. larr: "\u2190",
  6389. uarr: "\u2191",
  6390. rarr: "\u2192",
  6391. darr: "\u2193",
  6392. harr: "\u2194",
  6393. crarr: "\u21B5",
  6394. lArr: "\u21D0",
  6395. uArr: "\u21D1",
  6396. rArr: "\u21D2",
  6397. dArr: "\u21D3",
  6398. hArr: "\u21D4",
  6399. forall: "\u2200",
  6400. part: "\u2202",
  6401. exist: "\u2203",
  6402. empty: "\u2205",
  6403. nabla: "\u2207",
  6404. isin: "\u2208",
  6405. notin: "\u2209",
  6406. ni: "\u220B",
  6407. prod: "\u220F",
  6408. sum: "\u2211",
  6409. minus: "\u2212",
  6410. lowast: "\u2217",
  6411. radic: "\u221A",
  6412. prop: "\u221D",
  6413. infin: "\u221E",
  6414. ang: "\u2220",
  6415. and: "\u2227",
  6416. or: "\u2228",
  6417. cap: "\u2229",
  6418. cup: "\u222A",
  6419. int: "\u222B",
  6420. there4: "\u2234",
  6421. sim: "\u223C",
  6422. cong: "\u2245",
  6423. asymp: "\u2248",
  6424. ne: "\u2260",
  6425. equiv: "\u2261",
  6426. le: "\u2264",
  6427. ge: "\u2265",
  6428. sub: "\u2282",
  6429. sup: "\u2283",
  6430. nsub: "\u2284",
  6431. sube: "\u2286",
  6432. supe: "\u2287",
  6433. oplus: "\u2295",
  6434. otimes: "\u2297",
  6435. perp: "\u22A5",
  6436. sdot: "\u22C5",
  6437. lceil: "\u2308",
  6438. rceil: "\u2309",
  6439. lfloor: "\u230A",
  6440. rfloor: "\u230B",
  6441. lang: "\u2329",
  6442. rang: "\u232A",
  6443. loz: "\u25CA",
  6444. spades: "\u2660",
  6445. clubs: "\u2663",
  6446. hearts: "\u2665",
  6447. diams: "\u2666"
  6448. };
  6449. const JsxErrors = ParseErrorEnum`jsx`({
  6450. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6451. MissingClosingTagElement: ({
  6452. openingTagName
  6453. }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  6454. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6455. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6456. UnexpectedToken: ({
  6457. unexpected,
  6458. HTMLEntity
  6459. }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  6460. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6461. UnterminatedJsxContent: "Unterminated JSX contents.",
  6462. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6463. });
  6464. function isFragment(object) {
  6465. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6466. }
  6467. function getQualifiedJSXName(object) {
  6468. if (object.type === "JSXIdentifier") {
  6469. return object.name;
  6470. }
  6471. if (object.type === "JSXNamespacedName") {
  6472. return object.namespace.name + ":" + object.name.name;
  6473. }
  6474. if (object.type === "JSXMemberExpression") {
  6475. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6476. }
  6477. throw new Error("Node had unexpected type: " + object.type);
  6478. }
  6479. var jsx = superClass => class JSXParserMixin extends superClass {
  6480. jsxReadToken() {
  6481. let out = "";
  6482. let chunkStart = this.state.pos;
  6483. for (;;) {
  6484. if (this.state.pos >= this.length) {
  6485. throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc);
  6486. }
  6487. const ch = this.input.charCodeAt(this.state.pos);
  6488. switch (ch) {
  6489. case 60:
  6490. case 123:
  6491. if (this.state.pos === this.state.start) {
  6492. if (ch === 60 && this.state.canStartJSXElement) {
  6493. ++this.state.pos;
  6494. this.finishToken(142);
  6495. } else {
  6496. super.getTokenFromCode(ch);
  6497. }
  6498. return;
  6499. }
  6500. out += this.input.slice(chunkStart, this.state.pos);
  6501. this.finishToken(141, out);
  6502. return;
  6503. case 38:
  6504. out += this.input.slice(chunkStart, this.state.pos);
  6505. out += this.jsxReadEntity();
  6506. chunkStart = this.state.pos;
  6507. break;
  6508. case 62:
  6509. case 125:
  6510. default:
  6511. if (isNewLine(ch)) {
  6512. out += this.input.slice(chunkStart, this.state.pos);
  6513. out += this.jsxReadNewLine(true);
  6514. chunkStart = this.state.pos;
  6515. } else {
  6516. ++this.state.pos;
  6517. }
  6518. }
  6519. }
  6520. }
  6521. jsxReadNewLine(normalizeCRLF) {
  6522. const ch = this.input.charCodeAt(this.state.pos);
  6523. let out;
  6524. ++this.state.pos;
  6525. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6526. ++this.state.pos;
  6527. out = normalizeCRLF ? "\n" : "\r\n";
  6528. } else {
  6529. out = String.fromCharCode(ch);
  6530. }
  6531. ++this.state.curLine;
  6532. this.state.lineStart = this.state.pos;
  6533. return out;
  6534. }
  6535. jsxReadString(quote) {
  6536. let out = "";
  6537. let chunkStart = ++this.state.pos;
  6538. for (;;) {
  6539. if (this.state.pos >= this.length) {
  6540. throw this.raise(Errors.UnterminatedString, this.state.startLoc);
  6541. }
  6542. const ch = this.input.charCodeAt(this.state.pos);
  6543. if (ch === quote) break;
  6544. if (ch === 38) {
  6545. out += this.input.slice(chunkStart, this.state.pos);
  6546. out += this.jsxReadEntity();
  6547. chunkStart = this.state.pos;
  6548. } else if (isNewLine(ch)) {
  6549. out += this.input.slice(chunkStart, this.state.pos);
  6550. out += this.jsxReadNewLine(false);
  6551. chunkStart = this.state.pos;
  6552. } else {
  6553. ++this.state.pos;
  6554. }
  6555. }
  6556. out += this.input.slice(chunkStart, this.state.pos++);
  6557. this.finishToken(133, out);
  6558. }
  6559. jsxReadEntity() {
  6560. const startPos = ++this.state.pos;
  6561. if (this.codePointAtPos(this.state.pos) === 35) {
  6562. ++this.state.pos;
  6563. let radix = 10;
  6564. if (this.codePointAtPos(this.state.pos) === 120) {
  6565. radix = 16;
  6566. ++this.state.pos;
  6567. }
  6568. const codePoint = this.readInt(radix, undefined, false, "bail");
  6569. if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
  6570. ++this.state.pos;
  6571. return String.fromCodePoint(codePoint);
  6572. }
  6573. } else {
  6574. let count = 0;
  6575. let semi = false;
  6576. while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) {
  6577. ++this.state.pos;
  6578. }
  6579. if (semi) {
  6580. const desc = this.input.slice(startPos, this.state.pos);
  6581. const entity = entities[desc];
  6582. ++this.state.pos;
  6583. if (entity) {
  6584. return entity;
  6585. }
  6586. }
  6587. }
  6588. this.state.pos = startPos;
  6589. return "&";
  6590. }
  6591. jsxReadWord() {
  6592. let ch;
  6593. const start = this.state.pos;
  6594. do {
  6595. ch = this.input.charCodeAt(++this.state.pos);
  6596. } while (isIdentifierChar(ch) || ch === 45);
  6597. this.finishToken(140, this.input.slice(start, this.state.pos));
  6598. }
  6599. jsxParseIdentifier() {
  6600. const node = this.startNode();
  6601. if (this.match(140)) {
  6602. node.name = this.state.value;
  6603. } else if (tokenIsKeyword(this.state.type)) {
  6604. node.name = tokenLabelName(this.state.type);
  6605. } else {
  6606. this.unexpected();
  6607. }
  6608. this.next();
  6609. return this.finishNode(node, "JSXIdentifier");
  6610. }
  6611. jsxParseNamespacedName() {
  6612. const startLoc = this.state.startLoc;
  6613. const name = this.jsxParseIdentifier();
  6614. if (!this.eat(14)) return name;
  6615. const node = this.startNodeAt(startLoc);
  6616. node.namespace = name;
  6617. node.name = this.jsxParseIdentifier();
  6618. return this.finishNode(node, "JSXNamespacedName");
  6619. }
  6620. jsxParseElementName() {
  6621. const startLoc = this.state.startLoc;
  6622. let node = this.jsxParseNamespacedName();
  6623. if (node.type === "JSXNamespacedName") {
  6624. return node;
  6625. }
  6626. while (this.eat(16)) {
  6627. const newNode = this.startNodeAt(startLoc);
  6628. newNode.object = node;
  6629. newNode.property = this.jsxParseIdentifier();
  6630. node = this.finishNode(newNode, "JSXMemberExpression");
  6631. }
  6632. return node;
  6633. }
  6634. jsxParseAttributeValue() {
  6635. let node;
  6636. switch (this.state.type) {
  6637. case 5:
  6638. node = this.startNode();
  6639. this.setContext(types.brace);
  6640. this.next();
  6641. node = this.jsxParseExpressionContainer(node, types.j_oTag);
  6642. if (node.expression.type === "JSXEmptyExpression") {
  6643. this.raise(JsxErrors.AttributeIsEmpty, node);
  6644. }
  6645. return node;
  6646. case 142:
  6647. case 133:
  6648. return this.parseExprAtom();
  6649. default:
  6650. throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);
  6651. }
  6652. }
  6653. jsxParseEmptyExpression() {
  6654. const node = this.startNodeAt(this.state.lastTokEndLoc);
  6655. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
  6656. }
  6657. jsxParseSpreadChild(node) {
  6658. this.next();
  6659. node.expression = this.parseExpression();
  6660. this.setContext(types.j_expr);
  6661. this.state.canStartJSXElement = true;
  6662. this.expect(8);
  6663. return this.finishNode(node, "JSXSpreadChild");
  6664. }
  6665. jsxParseExpressionContainer(node, previousContext) {
  6666. if (this.match(8)) {
  6667. node.expression = this.jsxParseEmptyExpression();
  6668. } else {
  6669. const expression = this.parseExpression();
  6670. node.expression = expression;
  6671. }
  6672. this.setContext(previousContext);
  6673. this.state.canStartJSXElement = true;
  6674. this.expect(8);
  6675. return this.finishNode(node, "JSXExpressionContainer");
  6676. }
  6677. jsxParseAttribute() {
  6678. const node = this.startNode();
  6679. if (this.match(5)) {
  6680. this.setContext(types.brace);
  6681. this.next();
  6682. this.expect(21);
  6683. node.argument = this.parseMaybeAssignAllowIn();
  6684. this.setContext(types.j_oTag);
  6685. this.state.canStartJSXElement = true;
  6686. this.expect(8);
  6687. return this.finishNode(node, "JSXSpreadAttribute");
  6688. }
  6689. node.name = this.jsxParseNamespacedName();
  6690. node.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
  6691. return this.finishNode(node, "JSXAttribute");
  6692. }
  6693. jsxParseOpeningElementAt(startLoc) {
  6694. const node = this.startNodeAt(startLoc);
  6695. if (this.eat(143)) {
  6696. return this.finishNode(node, "JSXOpeningFragment");
  6697. }
  6698. node.name = this.jsxParseElementName();
  6699. return this.jsxParseOpeningElementAfterName(node);
  6700. }
  6701. jsxParseOpeningElementAfterName(node) {
  6702. const attributes = [];
  6703. while (!this.match(56) && !this.match(143)) {
  6704. attributes.push(this.jsxParseAttribute());
  6705. }
  6706. node.attributes = attributes;
  6707. node.selfClosing = this.eat(56);
  6708. this.expect(143);
  6709. return this.finishNode(node, "JSXOpeningElement");
  6710. }
  6711. jsxParseClosingElementAt(startLoc) {
  6712. const node = this.startNodeAt(startLoc);
  6713. if (this.eat(143)) {
  6714. return this.finishNode(node, "JSXClosingFragment");
  6715. }
  6716. node.name = this.jsxParseElementName();
  6717. this.expect(143);
  6718. return this.finishNode(node, "JSXClosingElement");
  6719. }
  6720. jsxParseElementAt(startLoc) {
  6721. const node = this.startNodeAt(startLoc);
  6722. const children = [];
  6723. const openingElement = this.jsxParseOpeningElementAt(startLoc);
  6724. let closingElement = null;
  6725. if (!openingElement.selfClosing) {
  6726. contents: for (;;) {
  6727. switch (this.state.type) {
  6728. case 142:
  6729. startLoc = this.state.startLoc;
  6730. this.next();
  6731. if (this.eat(56)) {
  6732. closingElement = this.jsxParseClosingElementAt(startLoc);
  6733. break contents;
  6734. }
  6735. children.push(this.jsxParseElementAt(startLoc));
  6736. break;
  6737. case 141:
  6738. children.push(this.parseLiteral(this.state.value, "JSXText"));
  6739. break;
  6740. case 5:
  6741. {
  6742. const node = this.startNode();
  6743. this.setContext(types.brace);
  6744. this.next();
  6745. if (this.match(21)) {
  6746. children.push(this.jsxParseSpreadChild(node));
  6747. } else {
  6748. children.push(this.jsxParseExpressionContainer(node, types.j_expr));
  6749. }
  6750. break;
  6751. }
  6752. default:
  6753. this.unexpected();
  6754. }
  6755. }
  6756. if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
  6757. this.raise(JsxErrors.MissingClosingTagFragment, closingElement);
  6758. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  6759. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  6760. openingTagName: getQualifiedJSXName(openingElement.name)
  6761. });
  6762. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  6763. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  6764. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  6765. openingTagName: getQualifiedJSXName(openingElement.name)
  6766. });
  6767. }
  6768. }
  6769. }
  6770. if (isFragment(openingElement)) {
  6771. node.openingFragment = openingElement;
  6772. node.closingFragment = closingElement;
  6773. } else {
  6774. node.openingElement = openingElement;
  6775. node.closingElement = closingElement;
  6776. }
  6777. node.children = children;
  6778. if (this.match(47)) {
  6779. throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc);
  6780. }
  6781. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  6782. }
  6783. jsxParseElement() {
  6784. const startLoc = this.state.startLoc;
  6785. this.next();
  6786. return this.jsxParseElementAt(startLoc);
  6787. }
  6788. setContext(newContext) {
  6789. const {
  6790. context
  6791. } = this.state;
  6792. context[context.length - 1] = newContext;
  6793. }
  6794. parseExprAtom(refExpressionErrors) {
  6795. if (this.match(142)) {
  6796. return this.jsxParseElement();
  6797. } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
  6798. this.replaceToken(142);
  6799. return this.jsxParseElement();
  6800. } else {
  6801. return super.parseExprAtom(refExpressionErrors);
  6802. }
  6803. }
  6804. skipSpace() {
  6805. const curContext = this.curContext();
  6806. if (!curContext.preserveSpace) super.skipSpace();
  6807. }
  6808. getTokenFromCode(code) {
  6809. const context = this.curContext();
  6810. if (context === types.j_expr) {
  6811. this.jsxReadToken();
  6812. return;
  6813. }
  6814. if (context === types.j_oTag || context === types.j_cTag) {
  6815. if (isIdentifierStart(code)) {
  6816. this.jsxReadWord();
  6817. return;
  6818. }
  6819. if (code === 62) {
  6820. ++this.state.pos;
  6821. this.finishToken(143);
  6822. return;
  6823. }
  6824. if ((code === 34 || code === 39) && context === types.j_oTag) {
  6825. this.jsxReadString(code);
  6826. return;
  6827. }
  6828. }
  6829. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  6830. ++this.state.pos;
  6831. this.finishToken(142);
  6832. return;
  6833. }
  6834. super.getTokenFromCode(code);
  6835. }
  6836. updateContext(prevType) {
  6837. const {
  6838. context,
  6839. type
  6840. } = this.state;
  6841. if (type === 56 && prevType === 142) {
  6842. context.splice(-2, 2, types.j_cTag);
  6843. this.state.canStartJSXElement = false;
  6844. } else if (type === 142) {
  6845. context.push(types.j_oTag);
  6846. } else if (type === 143) {
  6847. const out = context[context.length - 1];
  6848. if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) {
  6849. context.pop();
  6850. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  6851. } else {
  6852. this.setContext(types.j_expr);
  6853. this.state.canStartJSXElement = true;
  6854. }
  6855. } else {
  6856. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  6857. }
  6858. }
  6859. };
  6860. class TypeScriptScope extends Scope {
  6861. constructor(...args) {
  6862. super(...args);
  6863. this.tsNames = new Map();
  6864. }
  6865. }
  6866. class TypeScriptScopeHandler extends ScopeHandler {
  6867. constructor(...args) {
  6868. super(...args);
  6869. this.importsStack = [];
  6870. }
  6871. createScope(flags) {
  6872. this.importsStack.push(new Set());
  6873. return new TypeScriptScope(flags);
  6874. }
  6875. enter(flags) {
  6876. if (flags === 256) {
  6877. this.importsStack.push(new Set());
  6878. }
  6879. super.enter(flags);
  6880. }
  6881. exit() {
  6882. const flags = super.exit();
  6883. if (flags === 256) {
  6884. this.importsStack.pop();
  6885. }
  6886. return flags;
  6887. }
  6888. hasImport(name, allowShadow) {
  6889. const len = this.importsStack.length;
  6890. if (this.importsStack[len - 1].has(name)) {
  6891. return true;
  6892. }
  6893. if (!allowShadow && len > 1) {
  6894. for (let i = 0; i < len - 1; i++) {
  6895. if (this.importsStack[i].has(name)) return true;
  6896. }
  6897. }
  6898. return false;
  6899. }
  6900. declareName(name, bindingType, loc) {
  6901. if (bindingType & 4096) {
  6902. if (this.hasImport(name, true)) {
  6903. this.parser.raise(Errors.VarRedeclaration, loc, {
  6904. identifierName: name
  6905. });
  6906. }
  6907. this.importsStack[this.importsStack.length - 1].add(name);
  6908. return;
  6909. }
  6910. const scope = this.currentScope();
  6911. let type = scope.tsNames.get(name) || 0;
  6912. if (bindingType & 1024) {
  6913. this.maybeExportDefined(scope, name);
  6914. scope.tsNames.set(name, type | 16);
  6915. return;
  6916. }
  6917. super.declareName(name, bindingType, loc);
  6918. if (bindingType & 2) {
  6919. if (!(bindingType & 1)) {
  6920. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  6921. this.maybeExportDefined(scope, name);
  6922. }
  6923. type = type | 1;
  6924. }
  6925. if (bindingType & 256) {
  6926. type = type | 2;
  6927. }
  6928. if (bindingType & 512) {
  6929. type = type | 4;
  6930. }
  6931. if (bindingType & 128) {
  6932. type = type | 8;
  6933. }
  6934. if (type) scope.tsNames.set(name, type);
  6935. }
  6936. isRedeclaredInScope(scope, name, bindingType) {
  6937. const type = scope.tsNames.get(name);
  6938. if ((type & 2) > 0) {
  6939. if (bindingType & 256) {
  6940. const isConst = !!(bindingType & 512);
  6941. const wasConst = (type & 4) > 0;
  6942. return isConst !== wasConst;
  6943. }
  6944. return true;
  6945. }
  6946. if (bindingType & 128 && (type & 8) > 0) {
  6947. if (scope.names.get(name) & 2) {
  6948. return !!(bindingType & 1);
  6949. } else {
  6950. return false;
  6951. }
  6952. }
  6953. if (bindingType & 2 && (type & 1) > 0) {
  6954. return true;
  6955. }
  6956. return super.isRedeclaredInScope(scope, name, bindingType);
  6957. }
  6958. checkLocalExport(id) {
  6959. const {
  6960. name
  6961. } = id;
  6962. if (this.hasImport(name)) return;
  6963. const len = this.scopeStack.length;
  6964. for (let i = len - 1; i >= 0; i--) {
  6965. const scope = this.scopeStack[i];
  6966. const type = scope.tsNames.get(name);
  6967. if ((type & 1) > 0 || (type & 16) > 0) {
  6968. return;
  6969. }
  6970. }
  6971. super.checkLocalExport(id);
  6972. }
  6973. }
  6974. const unwrapParenthesizedExpression = node => {
  6975. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  6976. };
  6977. class LValParser extends NodeUtils {
  6978. toAssignable(node, isLHS = false) {
  6979. var _node$extra, _node$extra3;
  6980. let parenthesized = undefined;
  6981. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  6982. parenthesized = unwrapParenthesizedExpression(node);
  6983. if (isLHS) {
  6984. if (parenthesized.type === "Identifier") {
  6985. this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node);
  6986. } else if (parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) {
  6987. this.raise(Errors.InvalidParenthesizedAssignment, node);
  6988. }
  6989. } else {
  6990. this.raise(Errors.InvalidParenthesizedAssignment, node);
  6991. }
  6992. }
  6993. switch (node.type) {
  6994. case "Identifier":
  6995. case "ObjectPattern":
  6996. case "ArrayPattern":
  6997. case "AssignmentPattern":
  6998. case "RestElement":
  6999. break;
  7000. case "ObjectExpression":
  7001. node.type = "ObjectPattern";
  7002. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7003. var _node$extra2;
  7004. const prop = node.properties[i];
  7005. const isLast = i === last;
  7006. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  7007. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) {
  7008. this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc);
  7009. }
  7010. }
  7011. break;
  7012. case "ObjectProperty":
  7013. {
  7014. const {
  7015. key,
  7016. value
  7017. } = node;
  7018. if (this.isPrivateName(key)) {
  7019. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  7020. }
  7021. this.toAssignable(value, isLHS);
  7022. break;
  7023. }
  7024. case "SpreadElement":
  7025. {
  7026. throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller.");
  7027. }
  7028. case "ArrayExpression":
  7029. node.type = "ArrayPattern";
  7030. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
  7031. break;
  7032. case "AssignmentExpression":
  7033. if (node.operator !== "=") {
  7034. this.raise(Errors.MissingEqInAssignment, node.left.loc.end);
  7035. }
  7036. node.type = "AssignmentPattern";
  7037. delete node.operator;
  7038. this.toAssignable(node.left, isLHS);
  7039. break;
  7040. case "ParenthesizedExpression":
  7041. this.toAssignable(parenthesized, isLHS);
  7042. break;
  7043. }
  7044. }
  7045. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  7046. if (prop.type === "ObjectMethod") {
  7047. this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key);
  7048. } else if (prop.type === "SpreadElement") {
  7049. prop.type = "RestElement";
  7050. const arg = prop.argument;
  7051. this.checkToRestConversion(arg, false);
  7052. this.toAssignable(arg, isLHS);
  7053. if (!isLast) {
  7054. this.raise(Errors.RestTrailingComma, prop);
  7055. }
  7056. } else {
  7057. this.toAssignable(prop, isLHS);
  7058. }
  7059. }
  7060. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  7061. const end = exprList.length - 1;
  7062. for (let i = 0; i <= end; i++) {
  7063. const elt = exprList[i];
  7064. if (!elt) continue;
  7065. if (elt.type === "SpreadElement") {
  7066. elt.type = "RestElement";
  7067. const arg = elt.argument;
  7068. this.checkToRestConversion(arg, true);
  7069. this.toAssignable(arg, isLHS);
  7070. } else {
  7071. this.toAssignable(elt, isLHS);
  7072. }
  7073. if (elt.type === "RestElement") {
  7074. if (i < end) {
  7075. this.raise(Errors.RestTrailingComma, elt);
  7076. } else if (trailingCommaLoc) {
  7077. this.raise(Errors.RestTrailingComma, trailingCommaLoc);
  7078. }
  7079. }
  7080. }
  7081. }
  7082. isAssignable(node, isBinding) {
  7083. switch (node.type) {
  7084. case "Identifier":
  7085. case "ObjectPattern":
  7086. case "ArrayPattern":
  7087. case "AssignmentPattern":
  7088. case "RestElement":
  7089. return true;
  7090. case "ObjectExpression":
  7091. {
  7092. const last = node.properties.length - 1;
  7093. return node.properties.every((prop, i) => {
  7094. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  7095. });
  7096. }
  7097. case "ObjectProperty":
  7098. return this.isAssignable(node.value);
  7099. case "SpreadElement":
  7100. return this.isAssignable(node.argument);
  7101. case "ArrayExpression":
  7102. return node.elements.every(element => element === null || this.isAssignable(element));
  7103. case "AssignmentExpression":
  7104. return node.operator === "=";
  7105. case "ParenthesizedExpression":
  7106. return this.isAssignable(node.expression);
  7107. case "MemberExpression":
  7108. case "OptionalMemberExpression":
  7109. return !isBinding;
  7110. default:
  7111. return false;
  7112. }
  7113. }
  7114. toReferencedList(exprList, isParenthesizedExpr) {
  7115. return exprList;
  7116. }
  7117. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7118. this.toReferencedList(exprList, isParenthesizedExpr);
  7119. for (const expr of exprList) {
  7120. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  7121. this.toReferencedListDeep(expr.elements);
  7122. }
  7123. }
  7124. }
  7125. parseSpread(refExpressionErrors) {
  7126. const node = this.startNode();
  7127. this.next();
  7128. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined);
  7129. return this.finishNode(node, "SpreadElement");
  7130. }
  7131. parseRestBinding() {
  7132. const node = this.startNode();
  7133. this.next();
  7134. node.argument = this.parseBindingAtom();
  7135. return this.finishNode(node, "RestElement");
  7136. }
  7137. parseBindingAtom() {
  7138. switch (this.state.type) {
  7139. case 0:
  7140. {
  7141. const node = this.startNode();
  7142. this.next();
  7143. node.elements = this.parseBindingList(3, 93, 1);
  7144. return this.finishNode(node, "ArrayPattern");
  7145. }
  7146. case 5:
  7147. return this.parseObjectLike(8, true);
  7148. }
  7149. return this.parseIdentifier();
  7150. }
  7151. parseBindingList(close, closeCharCode, flags) {
  7152. const allowEmpty = flags & 1;
  7153. const elts = [];
  7154. let first = true;
  7155. while (!this.eat(close)) {
  7156. if (first) {
  7157. first = false;
  7158. } else {
  7159. this.expect(12);
  7160. }
  7161. if (allowEmpty && this.match(12)) {
  7162. elts.push(null);
  7163. } else if (this.eat(close)) {
  7164. break;
  7165. } else if (this.match(21)) {
  7166. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding(), flags));
  7167. if (!this.checkCommaAfterRest(closeCharCode)) {
  7168. this.expect(close);
  7169. break;
  7170. }
  7171. } else {
  7172. const decorators = [];
  7173. if (this.match(26) && this.hasPlugin("decorators")) {
  7174. this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc);
  7175. }
  7176. while (this.match(26)) {
  7177. decorators.push(this.parseDecorator());
  7178. }
  7179. elts.push(this.parseAssignableListItem(flags, decorators));
  7180. }
  7181. }
  7182. return elts;
  7183. }
  7184. parseBindingRestProperty(prop) {
  7185. this.next();
  7186. prop.argument = this.parseIdentifier();
  7187. this.checkCommaAfterRest(125);
  7188. return this.finishNode(prop, "RestElement");
  7189. }
  7190. parseBindingProperty() {
  7191. const {
  7192. type,
  7193. startLoc
  7194. } = this.state;
  7195. if (type === 21) {
  7196. return this.parseBindingRestProperty(this.startNode());
  7197. }
  7198. const prop = this.startNode();
  7199. if (type === 138) {
  7200. this.expectPlugin("destructuringPrivate", startLoc);
  7201. this.classScope.usePrivateName(this.state.value, startLoc);
  7202. prop.key = this.parsePrivateName();
  7203. } else {
  7204. this.parsePropertyName(prop);
  7205. }
  7206. prop.method = false;
  7207. return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  7208. }
  7209. parseAssignableListItem(flags, decorators) {
  7210. const left = this.parseMaybeDefault();
  7211. this.parseAssignableListItemTypes(left, flags);
  7212. const elt = this.parseMaybeDefault(left.loc.start, left);
  7213. if (decorators.length) {
  7214. left.decorators = decorators;
  7215. }
  7216. return elt;
  7217. }
  7218. parseAssignableListItemTypes(param, flags) {
  7219. return param;
  7220. }
  7221. parseMaybeDefault(startLoc, left) {
  7222. var _startLoc, _left;
  7223. (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
  7224. left = (_left = left) != null ? _left : this.parseBindingAtom();
  7225. if (!this.eat(29)) return left;
  7226. const node = this.startNodeAt(startLoc);
  7227. node.left = left;
  7228. node.right = this.parseMaybeAssignAllowIn();
  7229. return this.finishNode(node, "AssignmentPattern");
  7230. }
  7231. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  7232. switch (type) {
  7233. case "AssignmentPattern":
  7234. return "left";
  7235. case "RestElement":
  7236. return "argument";
  7237. case "ObjectProperty":
  7238. return "value";
  7239. case "ParenthesizedExpression":
  7240. return "expression";
  7241. case "ArrayPattern":
  7242. return "elements";
  7243. case "ObjectPattern":
  7244. return "properties";
  7245. }
  7246. return false;
  7247. }
  7248. isOptionalMemberExpression(expression) {
  7249. return expression.type === "OptionalMemberExpression";
  7250. }
  7251. checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false) {
  7252. var _expression$extra;
  7253. const type = expression.type;
  7254. if (this.isObjectMethod(expression)) return;
  7255. const isOptionalMemberExpression = this.isOptionalMemberExpression(expression);
  7256. if (isOptionalMemberExpression || type === "MemberExpression") {
  7257. if (isOptionalMemberExpression) {
  7258. this.expectPlugin("optionalChainingAssign", expression.loc.start);
  7259. if (ancestor.type !== "AssignmentExpression") {
  7260. this.raise(Errors.InvalidLhsOptionalChaining, expression, {
  7261. ancestor
  7262. });
  7263. }
  7264. }
  7265. if (binding !== 64) {
  7266. this.raise(Errors.InvalidPropertyBindingPattern, expression);
  7267. }
  7268. return;
  7269. }
  7270. if (type === "Identifier") {
  7271. this.checkIdentifier(expression, binding, strictModeChanged);
  7272. const {
  7273. name
  7274. } = expression;
  7275. if (checkClashes) {
  7276. if (checkClashes.has(name)) {
  7277. this.raise(Errors.ParamDupe, expression);
  7278. } else {
  7279. checkClashes.add(name);
  7280. }
  7281. }
  7282. return;
  7283. }
  7284. const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
  7285. if (validity === true) return;
  7286. if (validity === false) {
  7287. const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
  7288. this.raise(ParseErrorClass, expression, {
  7289. ancestor
  7290. });
  7291. return;
  7292. }
  7293. let key, isParenthesizedExpression;
  7294. if (typeof validity === "string") {
  7295. key = validity;
  7296. isParenthesizedExpression = type === "ParenthesizedExpression";
  7297. } else {
  7298. [key, isParenthesizedExpression] = validity;
  7299. }
  7300. const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? {
  7301. type
  7302. } : ancestor;
  7303. const val = expression[key];
  7304. if (Array.isArray(val)) {
  7305. for (const child of val) {
  7306. if (child) {
  7307. this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression);
  7308. }
  7309. }
  7310. } else if (val) {
  7311. this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression);
  7312. }
  7313. }
  7314. checkIdentifier(at, bindingType, strictModeChanged = false) {
  7315. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
  7316. if (bindingType === 64) {
  7317. this.raise(Errors.StrictEvalArguments, at, {
  7318. referenceName: at.name
  7319. });
  7320. } else {
  7321. this.raise(Errors.StrictEvalArgumentsBinding, at, {
  7322. bindingName: at.name
  7323. });
  7324. }
  7325. }
  7326. if (bindingType & 8192 && at.name === "let") {
  7327. this.raise(Errors.LetInLexicalBinding, at);
  7328. }
  7329. if (!(bindingType & 64)) {
  7330. this.declareNameFromIdentifier(at, bindingType);
  7331. }
  7332. }
  7333. declareNameFromIdentifier(identifier, binding) {
  7334. this.scope.declareName(identifier.name, binding, identifier.loc.start);
  7335. }
  7336. checkToRestConversion(node, allowPattern) {
  7337. switch (node.type) {
  7338. case "ParenthesizedExpression":
  7339. this.checkToRestConversion(node.expression, allowPattern);
  7340. break;
  7341. case "Identifier":
  7342. case "MemberExpression":
  7343. break;
  7344. case "ArrayExpression":
  7345. case "ObjectExpression":
  7346. if (allowPattern) break;
  7347. default:
  7348. this.raise(Errors.InvalidRestAssignmentPattern, node);
  7349. }
  7350. }
  7351. checkCommaAfterRest(close) {
  7352. if (!this.match(12)) {
  7353. return false;
  7354. }
  7355. this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc);
  7356. return true;
  7357. }
  7358. }
  7359. function nonNull(x) {
  7360. if (x == null) {
  7361. throw new Error(`Unexpected ${x} value.`);
  7362. }
  7363. return x;
  7364. }
  7365. function assert(x) {
  7366. if (!x) {
  7367. throw new Error("Assert fail");
  7368. }
  7369. }
  7370. const TSErrors = ParseErrorEnum`typescript`({
  7371. AbstractMethodHasImplementation: ({
  7372. methodName
  7373. }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  7374. AbstractPropertyHasInitializer: ({
  7375. propertyName
  7376. }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  7377. AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7378. AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7379. AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  7380. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7381. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7382. ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  7383. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7384. DeclareAccessor: ({
  7385. kind
  7386. }) => `'declare' is not allowed in ${kind}ters.`,
  7387. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7388. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7389. DuplicateAccessibilityModifier: ({
  7390. modifier
  7391. }) => `Accessibility modifier already seen.`,
  7392. DuplicateModifier: ({
  7393. modifier
  7394. }) => `Duplicate modifier: '${modifier}'.`,
  7395. EmptyHeritageClauseType: ({
  7396. token
  7397. }) => `'${token}' list cannot be empty.`,
  7398. EmptyTypeArguments: "Type argument list cannot be empty.",
  7399. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7400. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7401. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7402. ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  7403. IncompatibleModifiers: ({
  7404. modifiers
  7405. }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  7406. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7407. IndexSignatureHasAccessibility: ({
  7408. modifier
  7409. }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  7410. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7411. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7412. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7413. InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  7414. InvalidModifierOnTypeMember: ({
  7415. modifier
  7416. }) => `'${modifier}' modifier cannot appear on a type member.`,
  7417. InvalidModifierOnTypeParameter: ({
  7418. modifier
  7419. }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  7420. InvalidModifierOnTypeParameterPositions: ({
  7421. modifier
  7422. }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  7423. InvalidModifiersOrder: ({
  7424. orderedModifiers
  7425. }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  7426. InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  7427. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7428. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7429. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7430. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7431. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7432. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7433. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7434. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7435. PrivateElementHasAccessibility: ({
  7436. modifier
  7437. }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  7438. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7439. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7440. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7441. SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7442. SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7443. SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7444. SingleTypeParameterWithoutTrailingComma: ({
  7445. typeParameterName
  7446. }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  7447. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7448. TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",
  7449. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7450. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7451. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7452. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7453. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7454. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7455. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7456. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7457. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7458. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7459. UnsupportedSignatureParameterKind: ({
  7460. type
  7461. }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`
  7462. });
  7463. function keywordTypeFromName(value) {
  7464. switch (value) {
  7465. case "any":
  7466. return "TSAnyKeyword";
  7467. case "boolean":
  7468. return "TSBooleanKeyword";
  7469. case "bigint":
  7470. return "TSBigIntKeyword";
  7471. case "never":
  7472. return "TSNeverKeyword";
  7473. case "number":
  7474. return "TSNumberKeyword";
  7475. case "object":
  7476. return "TSObjectKeyword";
  7477. case "string":
  7478. return "TSStringKeyword";
  7479. case "symbol":
  7480. return "TSSymbolKeyword";
  7481. case "undefined":
  7482. return "TSUndefinedKeyword";
  7483. case "unknown":
  7484. return "TSUnknownKeyword";
  7485. default:
  7486. return undefined;
  7487. }
  7488. }
  7489. function tsIsAccessModifier(modifier) {
  7490. return modifier === "private" || modifier === "public" || modifier === "protected";
  7491. }
  7492. function tsIsVarianceAnnotations(modifier) {
  7493. return modifier === "in" || modifier === "out";
  7494. }
  7495. var typescript = superClass => class TypeScriptParserMixin extends superClass {
  7496. constructor(...args) {
  7497. super(...args);
  7498. this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, {
  7499. allowedModifiers: ["in", "out"],
  7500. disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"],
  7501. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  7502. });
  7503. this.tsParseConstModifier = this.tsParseModifiers.bind(this, {
  7504. allowedModifiers: ["const"],
  7505. disallowedModifiers: ["in", "out"],
  7506. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  7507. });
  7508. this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {
  7509. allowedModifiers: ["in", "out", "const"],
  7510. disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
  7511. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  7512. });
  7513. }
  7514. getScopeHandler() {
  7515. return TypeScriptScopeHandler;
  7516. }
  7517. tsIsIdentifier() {
  7518. return tokenIsIdentifier(this.state.type);
  7519. }
  7520. tsTokenCanFollowModifier() {
  7521. return (this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(138) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  7522. }
  7523. tsNextTokenCanFollowModifier() {
  7524. this.next();
  7525. return this.tsTokenCanFollowModifier();
  7526. }
  7527. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7528. if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) {
  7529. return undefined;
  7530. }
  7531. const modifier = this.state.value;
  7532. if (allowedModifiers.includes(modifier)) {
  7533. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7534. return undefined;
  7535. }
  7536. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7537. return modifier;
  7538. }
  7539. }
  7540. return undefined;
  7541. }
  7542. tsParseModifiers({
  7543. allowedModifiers,
  7544. disallowedModifiers,
  7545. stopOnStartOfClassStaticBlock,
  7546. errorTemplate = TSErrors.InvalidModifierOnTypeMember
  7547. }, modified) {
  7548. const enforceOrder = (loc, modifier, before, after) => {
  7549. if (modifier === before && modified[after]) {
  7550. this.raise(TSErrors.InvalidModifiersOrder, loc, {
  7551. orderedModifiers: [before, after]
  7552. });
  7553. }
  7554. };
  7555. const incompatible = (loc, modifier, mod1, mod2) => {
  7556. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7557. this.raise(TSErrors.IncompatibleModifiers, loc, {
  7558. modifiers: [mod1, mod2]
  7559. });
  7560. }
  7561. };
  7562. for (;;) {
  7563. const {
  7564. startLoc
  7565. } = this.state;
  7566. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7567. if (!modifier) break;
  7568. if (tsIsAccessModifier(modifier)) {
  7569. if (modified.accessibility) {
  7570. this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, {
  7571. modifier
  7572. });
  7573. } else {
  7574. enforceOrder(startLoc, modifier, modifier, "override");
  7575. enforceOrder(startLoc, modifier, modifier, "static");
  7576. enforceOrder(startLoc, modifier, modifier, "readonly");
  7577. modified.accessibility = modifier;
  7578. }
  7579. } else if (tsIsVarianceAnnotations(modifier)) {
  7580. if (modified[modifier]) {
  7581. this.raise(TSErrors.DuplicateModifier, startLoc, {
  7582. modifier
  7583. });
  7584. }
  7585. modified[modifier] = true;
  7586. enforceOrder(startLoc, modifier, "in", "out");
  7587. } else {
  7588. if (hasOwnProperty.call(modified, modifier)) {
  7589. this.raise(TSErrors.DuplicateModifier, startLoc, {
  7590. modifier
  7591. });
  7592. } else {
  7593. enforceOrder(startLoc, modifier, "static", "readonly");
  7594. enforceOrder(startLoc, modifier, "static", "override");
  7595. enforceOrder(startLoc, modifier, "override", "readonly");
  7596. enforceOrder(startLoc, modifier, "abstract", "override");
  7597. incompatible(startLoc, modifier, "declare", "override");
  7598. incompatible(startLoc, modifier, "static", "abstract");
  7599. }
  7600. modified[modifier] = true;
  7601. }
  7602. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7603. this.raise(errorTemplate, startLoc, {
  7604. modifier
  7605. });
  7606. }
  7607. }
  7608. }
  7609. tsIsListTerminator(kind) {
  7610. switch (kind) {
  7611. case "EnumMembers":
  7612. case "TypeMembers":
  7613. return this.match(8);
  7614. case "HeritageClauseElement":
  7615. return this.match(5);
  7616. case "TupleElementTypes":
  7617. return this.match(3);
  7618. case "TypeParametersOrArguments":
  7619. return this.match(48);
  7620. }
  7621. }
  7622. tsParseList(kind, parseElement) {
  7623. const result = [];
  7624. while (!this.tsIsListTerminator(kind)) {
  7625. result.push(parseElement());
  7626. }
  7627. return result;
  7628. }
  7629. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7630. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7631. }
  7632. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7633. const result = [];
  7634. let trailingCommaPos = -1;
  7635. for (;;) {
  7636. if (this.tsIsListTerminator(kind)) {
  7637. break;
  7638. }
  7639. trailingCommaPos = -1;
  7640. const element = parseElement();
  7641. if (element == null) {
  7642. return undefined;
  7643. }
  7644. result.push(element);
  7645. if (this.eat(12)) {
  7646. trailingCommaPos = this.state.lastTokStartLoc.index;
  7647. continue;
  7648. }
  7649. if (this.tsIsListTerminator(kind)) {
  7650. break;
  7651. }
  7652. if (expectSuccess) {
  7653. this.expect(12);
  7654. }
  7655. return undefined;
  7656. }
  7657. if (refTrailingCommaPos) {
  7658. refTrailingCommaPos.value = trailingCommaPos;
  7659. }
  7660. return result;
  7661. }
  7662. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7663. if (!skipFirstToken) {
  7664. if (bracket) {
  7665. this.expect(0);
  7666. } else {
  7667. this.expect(47);
  7668. }
  7669. }
  7670. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7671. if (bracket) {
  7672. this.expect(3);
  7673. } else {
  7674. this.expect(48);
  7675. }
  7676. return result;
  7677. }
  7678. tsParseImportType() {
  7679. const node = this.startNode();
  7680. this.expect(83);
  7681. this.expect(10);
  7682. if (!this.match(133)) {
  7683. this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc);
  7684. }
  7685. node.argument = super.parseExprAtom();
  7686. if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) {
  7687. node.options = null;
  7688. }
  7689. if (this.eat(12)) {
  7690. this.expectImportAttributesPlugin();
  7691. if (!this.match(11)) {
  7692. node.options = super.parseMaybeAssignAllowIn();
  7693. this.eat(12);
  7694. }
  7695. }
  7696. this.expect(11);
  7697. if (this.eat(16)) {
  7698. node.qualifier = this.tsParseEntityName();
  7699. }
  7700. if (this.match(47)) {
  7701. node.typeParameters = this.tsParseTypeArguments();
  7702. }
  7703. return this.finishNode(node, "TSImportType");
  7704. }
  7705. tsParseEntityName(allowReservedWords = true) {
  7706. let entity = this.parseIdentifier(allowReservedWords);
  7707. while (this.eat(16)) {
  7708. const node = this.startNodeAtNode(entity);
  7709. node.left = entity;
  7710. node.right = this.parseIdentifier(allowReservedWords);
  7711. entity = this.finishNode(node, "TSQualifiedName");
  7712. }
  7713. return entity;
  7714. }
  7715. tsParseTypeReference() {
  7716. const node = this.startNode();
  7717. node.typeName = this.tsParseEntityName();
  7718. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7719. node.typeParameters = this.tsParseTypeArguments();
  7720. }
  7721. return this.finishNode(node, "TSTypeReference");
  7722. }
  7723. tsParseThisTypePredicate(lhs) {
  7724. this.next();
  7725. const node = this.startNodeAtNode(lhs);
  7726. node.parameterName = lhs;
  7727. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7728. node.asserts = false;
  7729. return this.finishNode(node, "TSTypePredicate");
  7730. }
  7731. tsParseThisTypeNode() {
  7732. const node = this.startNode();
  7733. this.next();
  7734. return this.finishNode(node, "TSThisType");
  7735. }
  7736. tsParseTypeQuery() {
  7737. const node = this.startNode();
  7738. this.expect(87);
  7739. if (this.match(83)) {
  7740. node.exprName = this.tsParseImportType();
  7741. } else {
  7742. node.exprName = this.tsParseEntityName();
  7743. }
  7744. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  7745. node.typeParameters = this.tsParseTypeArguments();
  7746. }
  7747. return this.finishNode(node, "TSTypeQuery");
  7748. }
  7749. tsParseTypeParameter(parseModifiers) {
  7750. const node = this.startNode();
  7751. parseModifiers(node);
  7752. node.name = this.tsParseTypeParameterName();
  7753. node.constraint = this.tsEatThenParseType(81);
  7754. node.default = this.tsEatThenParseType(29);
  7755. return this.finishNode(node, "TSTypeParameter");
  7756. }
  7757. tsTryParseTypeParameters(parseModifiers) {
  7758. if (this.match(47)) {
  7759. return this.tsParseTypeParameters(parseModifiers);
  7760. }
  7761. }
  7762. tsParseTypeParameters(parseModifiers) {
  7763. const node = this.startNode();
  7764. if (this.match(47) || this.match(142)) {
  7765. this.next();
  7766. } else {
  7767. this.unexpected();
  7768. }
  7769. const refTrailingCommaPos = {
  7770. value: -1
  7771. };
  7772. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
  7773. if (node.params.length === 0) {
  7774. this.raise(TSErrors.EmptyTypeParameters, node);
  7775. }
  7776. if (refTrailingCommaPos.value !== -1) {
  7777. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7778. }
  7779. return this.finishNode(node, "TSTypeParameterDeclaration");
  7780. }
  7781. tsFillSignature(returnToken, signature) {
  7782. const returnTokenRequired = returnToken === 19;
  7783. const paramsKey = "parameters";
  7784. const returnTypeKey = "typeAnnotation";
  7785. signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  7786. this.expect(10);
  7787. signature[paramsKey] = this.tsParseBindingListForSignature();
  7788. if (returnTokenRequired) {
  7789. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7790. } else if (this.match(returnToken)) {
  7791. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7792. }
  7793. }
  7794. tsParseBindingListForSignature() {
  7795. const list = super.parseBindingList(11, 41, 2);
  7796. for (const pattern of list) {
  7797. const {
  7798. type
  7799. } = pattern;
  7800. if (type === "AssignmentPattern" || type === "TSParameterProperty") {
  7801. this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, {
  7802. type
  7803. });
  7804. }
  7805. }
  7806. return list;
  7807. }
  7808. tsParseTypeMemberSemicolon() {
  7809. if (!this.eat(12) && !this.isLineTerminator()) {
  7810. this.expect(13);
  7811. }
  7812. }
  7813. tsParseSignatureMember(kind, node) {
  7814. this.tsFillSignature(14, node);
  7815. this.tsParseTypeMemberSemicolon();
  7816. return this.finishNode(node, kind);
  7817. }
  7818. tsIsUnambiguouslyIndexSignature() {
  7819. this.next();
  7820. if (tokenIsIdentifier(this.state.type)) {
  7821. this.next();
  7822. return this.match(14);
  7823. }
  7824. return false;
  7825. }
  7826. tsTryParseIndexSignature(node) {
  7827. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  7828. return;
  7829. }
  7830. this.expect(0);
  7831. const id = this.parseIdentifier();
  7832. id.typeAnnotation = this.tsParseTypeAnnotation();
  7833. this.resetEndLocation(id);
  7834. this.expect(3);
  7835. node.parameters = [id];
  7836. const type = this.tsTryParseTypeAnnotation();
  7837. if (type) node.typeAnnotation = type;
  7838. this.tsParseTypeMemberSemicolon();
  7839. return this.finishNode(node, "TSIndexSignature");
  7840. }
  7841. tsParsePropertyOrMethodSignature(node, readonly) {
  7842. if (this.eat(17)) node.optional = true;
  7843. const nodeAny = node;
  7844. if (this.match(10) || this.match(47)) {
  7845. if (readonly) {
  7846. this.raise(TSErrors.ReadonlyForMethodSignature, node);
  7847. }
  7848. const method = nodeAny;
  7849. if (method.kind && this.match(47)) {
  7850. this.raise(TSErrors.AccesorCannotHaveTypeParameters, this.state.curPosition());
  7851. }
  7852. this.tsFillSignature(14, method);
  7853. this.tsParseTypeMemberSemicolon();
  7854. const paramsKey = "parameters";
  7855. const returnTypeKey = "typeAnnotation";
  7856. if (method.kind === "get") {
  7857. if (method[paramsKey].length > 0) {
  7858. this.raise(Errors.BadGetterArity, this.state.curPosition());
  7859. if (this.isThisParam(method[paramsKey][0])) {
  7860. this.raise(TSErrors.AccesorCannotDeclareThisParameter, this.state.curPosition());
  7861. }
  7862. }
  7863. } else if (method.kind === "set") {
  7864. if (method[paramsKey].length !== 1) {
  7865. this.raise(Errors.BadSetterArity, this.state.curPosition());
  7866. } else {
  7867. const firstParameter = method[paramsKey][0];
  7868. if (this.isThisParam(firstParameter)) {
  7869. this.raise(TSErrors.AccesorCannotDeclareThisParameter, this.state.curPosition());
  7870. }
  7871. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  7872. this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, this.state.curPosition());
  7873. }
  7874. if (firstParameter.type === "RestElement") {
  7875. this.raise(TSErrors.SetAccesorCannotHaveRestParameter, this.state.curPosition());
  7876. }
  7877. }
  7878. if (method[returnTypeKey]) {
  7879. this.raise(TSErrors.SetAccesorCannotHaveReturnType, method[returnTypeKey]);
  7880. }
  7881. } else {
  7882. method.kind = "method";
  7883. }
  7884. return this.finishNode(method, "TSMethodSignature");
  7885. } else {
  7886. const property = nodeAny;
  7887. if (readonly) property.readonly = true;
  7888. const type = this.tsTryParseTypeAnnotation();
  7889. if (type) property.typeAnnotation = type;
  7890. this.tsParseTypeMemberSemicolon();
  7891. return this.finishNode(property, "TSPropertySignature");
  7892. }
  7893. }
  7894. tsParseTypeMember() {
  7895. const node = this.startNode();
  7896. if (this.match(10) || this.match(47)) {
  7897. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  7898. }
  7899. if (this.match(77)) {
  7900. const id = this.startNode();
  7901. this.next();
  7902. if (this.match(10) || this.match(47)) {
  7903. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  7904. } else {
  7905. node.key = this.createIdentifier(id, "new");
  7906. return this.tsParsePropertyOrMethodSignature(node, false);
  7907. }
  7908. }
  7909. this.tsParseModifiers({
  7910. allowedModifiers: ["readonly"],
  7911. disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
  7912. }, node);
  7913. const idx = this.tsTryParseIndexSignature(node);
  7914. if (idx) {
  7915. return idx;
  7916. }
  7917. super.parsePropertyName(node);
  7918. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  7919. node.kind = node.key.name;
  7920. super.parsePropertyName(node);
  7921. }
  7922. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  7923. }
  7924. tsParseTypeLiteral() {
  7925. const node = this.startNode();
  7926. node.members = this.tsParseObjectTypeMembers();
  7927. return this.finishNode(node, "TSTypeLiteral");
  7928. }
  7929. tsParseObjectTypeMembers() {
  7930. this.expect(5);
  7931. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  7932. this.expect(8);
  7933. return members;
  7934. }
  7935. tsIsStartOfMappedType() {
  7936. this.next();
  7937. if (this.eat(53)) {
  7938. return this.isContextual(122);
  7939. }
  7940. if (this.isContextual(122)) {
  7941. this.next();
  7942. }
  7943. if (!this.match(0)) {
  7944. return false;
  7945. }
  7946. this.next();
  7947. if (!this.tsIsIdentifier()) {
  7948. return false;
  7949. }
  7950. this.next();
  7951. return this.match(58);
  7952. }
  7953. tsParseMappedTypeParameter() {
  7954. const node = this.startNode();
  7955. node.name = this.tsParseTypeParameterName();
  7956. node.constraint = this.tsExpectThenParseType(58);
  7957. return this.finishNode(node, "TSTypeParameter");
  7958. }
  7959. tsParseMappedType() {
  7960. const node = this.startNode();
  7961. this.expect(5);
  7962. if (this.match(53)) {
  7963. node.readonly = this.state.value;
  7964. this.next();
  7965. this.expectContextual(122);
  7966. } else if (this.eatContextual(122)) {
  7967. node.readonly = true;
  7968. }
  7969. this.expect(0);
  7970. node.typeParameter = this.tsParseMappedTypeParameter();
  7971. node.nameType = this.eatContextual(93) ? this.tsParseType() : null;
  7972. this.expect(3);
  7973. if (this.match(53)) {
  7974. node.optional = this.state.value;
  7975. this.next();
  7976. this.expect(17);
  7977. } else if (this.eat(17)) {
  7978. node.optional = true;
  7979. }
  7980. node.typeAnnotation = this.tsTryParseType();
  7981. this.semicolon();
  7982. this.expect(8);
  7983. return this.finishNode(node, "TSMappedType");
  7984. }
  7985. tsParseTupleType() {
  7986. const node = this.startNode();
  7987. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  7988. let seenOptionalElement = false;
  7989. node.elementTypes.forEach(elementNode => {
  7990. const {
  7991. type
  7992. } = elementNode;
  7993. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  7994. this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode);
  7995. }
  7996. seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
  7997. });
  7998. return this.finishNode(node, "TSTupleType");
  7999. }
  8000. tsParseTupleElementType() {
  8001. const {
  8002. startLoc
  8003. } = this.state;
  8004. const rest = this.eat(21);
  8005. let labeled;
  8006. let label;
  8007. let optional;
  8008. let type;
  8009. const isWord = tokenIsKeywordOrIdentifier(this.state.type);
  8010. const chAfterWord = isWord ? this.lookaheadCharCode() : null;
  8011. if (chAfterWord === 58) {
  8012. labeled = true;
  8013. optional = false;
  8014. label = this.parseIdentifier(true);
  8015. this.expect(14);
  8016. type = this.tsParseType();
  8017. } else if (chAfterWord === 63) {
  8018. optional = true;
  8019. const startLoc = this.state.startLoc;
  8020. const wordName = this.state.value;
  8021. const typeOrLabel = this.tsParseNonArrayType();
  8022. if (this.lookaheadCharCode() === 58) {
  8023. labeled = true;
  8024. label = this.createIdentifier(this.startNodeAt(startLoc), wordName);
  8025. this.expect(17);
  8026. this.expect(14);
  8027. type = this.tsParseType();
  8028. } else {
  8029. labeled = false;
  8030. type = typeOrLabel;
  8031. this.expect(17);
  8032. }
  8033. } else {
  8034. type = this.tsParseType();
  8035. optional = this.eat(17);
  8036. labeled = this.eat(14);
  8037. }
  8038. if (labeled) {
  8039. let labeledNode;
  8040. if (label) {
  8041. labeledNode = this.startNodeAtNode(label);
  8042. labeledNode.optional = optional;
  8043. labeledNode.label = label;
  8044. labeledNode.elementType = type;
  8045. if (this.eat(17)) {
  8046. labeledNode.optional = true;
  8047. this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc);
  8048. }
  8049. } else {
  8050. labeledNode = this.startNodeAtNode(type);
  8051. labeledNode.optional = optional;
  8052. this.raise(TSErrors.InvalidTupleMemberLabel, type);
  8053. labeledNode.label = type;
  8054. labeledNode.elementType = this.tsParseType();
  8055. }
  8056. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  8057. } else if (optional) {
  8058. const optionalTypeNode = this.startNodeAtNode(type);
  8059. optionalTypeNode.typeAnnotation = type;
  8060. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  8061. }
  8062. if (rest) {
  8063. const restNode = this.startNodeAt(startLoc);
  8064. restNode.typeAnnotation = type;
  8065. type = this.finishNode(restNode, "TSRestType");
  8066. }
  8067. return type;
  8068. }
  8069. tsParseParenthesizedType() {
  8070. const node = this.startNode();
  8071. this.expect(10);
  8072. node.typeAnnotation = this.tsParseType();
  8073. this.expect(11);
  8074. return this.finishNode(node, "TSParenthesizedType");
  8075. }
  8076. tsParseFunctionOrConstructorType(type, abstract) {
  8077. const node = this.startNode();
  8078. if (type === "TSConstructorType") {
  8079. node.abstract = !!abstract;
  8080. if (abstract) this.next();
  8081. this.next();
  8082. }
  8083. this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node));
  8084. return this.finishNode(node, type);
  8085. }
  8086. tsParseLiteralTypeNode() {
  8087. const node = this.startNode();
  8088. switch (this.state.type) {
  8089. case 134:
  8090. case 135:
  8091. case 133:
  8092. case 85:
  8093. case 86:
  8094. node.literal = super.parseExprAtom();
  8095. break;
  8096. default:
  8097. this.unexpected();
  8098. }
  8099. return this.finishNode(node, "TSLiteralType");
  8100. }
  8101. tsParseTemplateLiteralType() {
  8102. const node = this.startNode();
  8103. node.literal = super.parseTemplate(false);
  8104. return this.finishNode(node, "TSLiteralType");
  8105. }
  8106. parseTemplateSubstitution() {
  8107. if (this.state.inType) return this.tsParseType();
  8108. return super.parseTemplateSubstitution();
  8109. }
  8110. tsParseThisTypeOrThisTypePredicate() {
  8111. const thisKeyword = this.tsParseThisTypeNode();
  8112. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  8113. return this.tsParseThisTypePredicate(thisKeyword);
  8114. } else {
  8115. return thisKeyword;
  8116. }
  8117. }
  8118. tsParseNonArrayType() {
  8119. switch (this.state.type) {
  8120. case 133:
  8121. case 134:
  8122. case 135:
  8123. case 85:
  8124. case 86:
  8125. return this.tsParseLiteralTypeNode();
  8126. case 53:
  8127. if (this.state.value === "-") {
  8128. const node = this.startNode();
  8129. const nextToken = this.lookahead();
  8130. if (nextToken.type !== 134 && nextToken.type !== 135) {
  8131. this.unexpected();
  8132. }
  8133. node.literal = this.parseMaybeUnary();
  8134. return this.finishNode(node, "TSLiteralType");
  8135. }
  8136. break;
  8137. case 78:
  8138. return this.tsParseThisTypeOrThisTypePredicate();
  8139. case 87:
  8140. return this.tsParseTypeQuery();
  8141. case 83:
  8142. return this.tsParseImportType();
  8143. case 5:
  8144. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  8145. case 0:
  8146. return this.tsParseTupleType();
  8147. case 10:
  8148. return this.tsParseParenthesizedType();
  8149. case 25:
  8150. case 24:
  8151. return this.tsParseTemplateLiteralType();
  8152. default:
  8153. {
  8154. const {
  8155. type
  8156. } = this.state;
  8157. if (tokenIsIdentifier(type) || type === 88 || type === 84) {
  8158. const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  8159. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  8160. const node = this.startNode();
  8161. this.next();
  8162. return this.finishNode(node, nodeType);
  8163. }
  8164. return this.tsParseTypeReference();
  8165. }
  8166. }
  8167. }
  8168. this.unexpected();
  8169. }
  8170. tsParseArrayTypeOrHigher() {
  8171. let type = this.tsParseNonArrayType();
  8172. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  8173. if (this.match(3)) {
  8174. const node = this.startNodeAtNode(type);
  8175. node.elementType = type;
  8176. this.expect(3);
  8177. type = this.finishNode(node, "TSArrayType");
  8178. } else {
  8179. const node = this.startNodeAtNode(type);
  8180. node.objectType = type;
  8181. node.indexType = this.tsParseType();
  8182. this.expect(3);
  8183. type = this.finishNode(node, "TSIndexedAccessType");
  8184. }
  8185. }
  8186. return type;
  8187. }
  8188. tsParseTypeOperator() {
  8189. const node = this.startNode();
  8190. const operator = this.state.value;
  8191. this.next();
  8192. node.operator = operator;
  8193. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  8194. if (operator === "readonly") {
  8195. this.tsCheckTypeAnnotationForReadOnly(node);
  8196. }
  8197. return this.finishNode(node, "TSTypeOperator");
  8198. }
  8199. tsCheckTypeAnnotationForReadOnly(node) {
  8200. switch (node.typeAnnotation.type) {
  8201. case "TSTupleType":
  8202. case "TSArrayType":
  8203. return;
  8204. default:
  8205. this.raise(TSErrors.UnexpectedReadonly, node);
  8206. }
  8207. }
  8208. tsParseInferType() {
  8209. const node = this.startNode();
  8210. this.expectContextual(115);
  8211. const typeParameter = this.startNode();
  8212. typeParameter.name = this.tsParseTypeParameterName();
  8213. typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
  8214. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  8215. return this.finishNode(node, "TSInferType");
  8216. }
  8217. tsParseConstraintForInferType() {
  8218. if (this.eat(81)) {
  8219. const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
  8220. if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
  8221. return constraint;
  8222. }
  8223. }
  8224. }
  8225. tsParseTypeOperatorOrHigher() {
  8226. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  8227. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  8228. }
  8229. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  8230. const node = this.startNode();
  8231. const hasLeadingOperator = this.eat(operator);
  8232. const types = [];
  8233. do {
  8234. types.push(parseConstituentType());
  8235. } while (this.eat(operator));
  8236. if (types.length === 1 && !hasLeadingOperator) {
  8237. return types[0];
  8238. }
  8239. node.types = types;
  8240. return this.finishNode(node, kind);
  8241. }
  8242. tsParseIntersectionTypeOrHigher() {
  8243. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  8244. }
  8245. tsParseUnionTypeOrHigher() {
  8246. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  8247. }
  8248. tsIsStartOfFunctionType() {
  8249. if (this.match(47)) {
  8250. return true;
  8251. }
  8252. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  8253. }
  8254. tsSkipParameterStart() {
  8255. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  8256. this.next();
  8257. return true;
  8258. }
  8259. if (this.match(5)) {
  8260. const {
  8261. errors
  8262. } = this.state;
  8263. const previousErrorCount = errors.length;
  8264. try {
  8265. this.parseObjectLike(8, true);
  8266. return errors.length === previousErrorCount;
  8267. } catch (_unused) {
  8268. return false;
  8269. }
  8270. }
  8271. if (this.match(0)) {
  8272. this.next();
  8273. const {
  8274. errors
  8275. } = this.state;
  8276. const previousErrorCount = errors.length;
  8277. try {
  8278. super.parseBindingList(3, 93, 1);
  8279. return errors.length === previousErrorCount;
  8280. } catch (_unused2) {
  8281. return false;
  8282. }
  8283. }
  8284. return false;
  8285. }
  8286. tsIsUnambiguouslyStartOfFunctionType() {
  8287. this.next();
  8288. if (this.match(11) || this.match(21)) {
  8289. return true;
  8290. }
  8291. if (this.tsSkipParameterStart()) {
  8292. if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
  8293. return true;
  8294. }
  8295. if (this.match(11)) {
  8296. this.next();
  8297. if (this.match(19)) {
  8298. return true;
  8299. }
  8300. }
  8301. }
  8302. return false;
  8303. }
  8304. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  8305. return this.tsInType(() => {
  8306. const t = this.startNode();
  8307. this.expect(returnToken);
  8308. const node = this.startNode();
  8309. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  8310. if (asserts && this.match(78)) {
  8311. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  8312. if (thisTypePredicate.type === "TSThisType") {
  8313. node.parameterName = thisTypePredicate;
  8314. node.asserts = true;
  8315. node.typeAnnotation = null;
  8316. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  8317. } else {
  8318. this.resetStartLocationFromNode(thisTypePredicate, node);
  8319. thisTypePredicate.asserts = true;
  8320. }
  8321. t.typeAnnotation = thisTypePredicate;
  8322. return this.finishNode(t, "TSTypeAnnotation");
  8323. }
  8324. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  8325. if (!typePredicateVariable) {
  8326. if (!asserts) {
  8327. return this.tsParseTypeAnnotation(false, t);
  8328. }
  8329. node.parameterName = this.parseIdentifier();
  8330. node.asserts = asserts;
  8331. node.typeAnnotation = null;
  8332. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8333. return this.finishNode(t, "TSTypeAnnotation");
  8334. }
  8335. const type = this.tsParseTypeAnnotation(false);
  8336. node.parameterName = typePredicateVariable;
  8337. node.typeAnnotation = type;
  8338. node.asserts = asserts;
  8339. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8340. return this.finishNode(t, "TSTypeAnnotation");
  8341. });
  8342. }
  8343. tsTryParseTypeOrTypePredicateAnnotation() {
  8344. if (this.match(14)) {
  8345. return this.tsParseTypeOrTypePredicateAnnotation(14);
  8346. }
  8347. }
  8348. tsTryParseTypeAnnotation() {
  8349. if (this.match(14)) {
  8350. return this.tsParseTypeAnnotation();
  8351. }
  8352. }
  8353. tsTryParseType() {
  8354. return this.tsEatThenParseType(14);
  8355. }
  8356. tsParseTypePredicatePrefix() {
  8357. const id = this.parseIdentifier();
  8358. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  8359. this.next();
  8360. return id;
  8361. }
  8362. }
  8363. tsParseTypePredicateAsserts() {
  8364. if (this.state.type !== 109) {
  8365. return false;
  8366. }
  8367. const containsEsc = this.state.containsEsc;
  8368. this.next();
  8369. if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
  8370. return false;
  8371. }
  8372. if (containsEsc) {
  8373. this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, {
  8374. reservedWord: "asserts"
  8375. });
  8376. }
  8377. return true;
  8378. }
  8379. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8380. this.tsInType(() => {
  8381. if (eatColon) this.expect(14);
  8382. t.typeAnnotation = this.tsParseType();
  8383. });
  8384. return this.finishNode(t, "TSTypeAnnotation");
  8385. }
  8386. tsParseType() {
  8387. assert(this.state.inType);
  8388. const type = this.tsParseNonConditionalType();
  8389. if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
  8390. return type;
  8391. }
  8392. const node = this.startNodeAtNode(type);
  8393. node.checkType = type;
  8394. node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
  8395. this.expect(17);
  8396. node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8397. this.expect(14);
  8398. node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  8399. return this.finishNode(node, "TSConditionalType");
  8400. }
  8401. isAbstractConstructorSignature() {
  8402. return this.isContextual(124) && this.lookahead().type === 77;
  8403. }
  8404. tsParseNonConditionalType() {
  8405. if (this.tsIsStartOfFunctionType()) {
  8406. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8407. }
  8408. if (this.match(77)) {
  8409. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8410. } else if (this.isAbstractConstructorSignature()) {
  8411. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8412. }
  8413. return this.tsParseUnionTypeOrHigher();
  8414. }
  8415. tsParseTypeAssertion() {
  8416. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8417. this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc);
  8418. }
  8419. const node = this.startNode();
  8420. node.typeAnnotation = this.tsInType(() => {
  8421. this.next();
  8422. return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
  8423. });
  8424. this.expect(48);
  8425. node.expression = this.parseMaybeUnary();
  8426. return this.finishNode(node, "TSTypeAssertion");
  8427. }
  8428. tsParseHeritageClause(token) {
  8429. const originalStartLoc = this.state.startLoc;
  8430. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
  8431. const node = this.startNode();
  8432. node.expression = this.tsParseEntityName();
  8433. if (this.match(47)) {
  8434. node.typeParameters = this.tsParseTypeArguments();
  8435. }
  8436. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8437. });
  8438. if (!delimitedList.length) {
  8439. this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, {
  8440. token
  8441. });
  8442. }
  8443. return delimitedList;
  8444. }
  8445. tsParseInterfaceDeclaration(node, properties = {}) {
  8446. if (this.hasFollowingLineBreak()) return null;
  8447. this.expectContextual(129);
  8448. if (properties.declare) node.declare = true;
  8449. if (tokenIsIdentifier(this.state.type)) {
  8450. node.id = this.parseIdentifier();
  8451. this.checkIdentifier(node.id, 130);
  8452. } else {
  8453. node.id = null;
  8454. this.raise(TSErrors.MissingInterfaceName, this.state.startLoc);
  8455. }
  8456. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  8457. if (this.eat(81)) {
  8458. node.extends = this.tsParseHeritageClause("extends");
  8459. }
  8460. const body = this.startNode();
  8461. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8462. node.body = this.finishNode(body, "TSInterfaceBody");
  8463. return this.finishNode(node, "TSInterfaceDeclaration");
  8464. }
  8465. tsParseTypeAliasDeclaration(node) {
  8466. node.id = this.parseIdentifier();
  8467. this.checkIdentifier(node.id, 2);
  8468. node.typeAnnotation = this.tsInType(() => {
  8469. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
  8470. this.expect(29);
  8471. if (this.isContextual(114) && this.lookahead().type !== 16) {
  8472. const node = this.startNode();
  8473. this.next();
  8474. return this.finishNode(node, "TSIntrinsicKeyword");
  8475. }
  8476. return this.tsParseType();
  8477. });
  8478. this.semicolon();
  8479. return this.finishNode(node, "TSTypeAliasDeclaration");
  8480. }
  8481. tsInNoContext(cb) {
  8482. const oldContext = this.state.context;
  8483. this.state.context = [oldContext[0]];
  8484. try {
  8485. return cb();
  8486. } finally {
  8487. this.state.context = oldContext;
  8488. }
  8489. }
  8490. tsInType(cb) {
  8491. const oldInType = this.state.inType;
  8492. this.state.inType = true;
  8493. try {
  8494. return cb();
  8495. } finally {
  8496. this.state.inType = oldInType;
  8497. }
  8498. }
  8499. tsInDisallowConditionalTypesContext(cb) {
  8500. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8501. this.state.inDisallowConditionalTypesContext = true;
  8502. try {
  8503. return cb();
  8504. } finally {
  8505. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8506. }
  8507. }
  8508. tsInAllowConditionalTypesContext(cb) {
  8509. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  8510. this.state.inDisallowConditionalTypesContext = false;
  8511. try {
  8512. return cb();
  8513. } finally {
  8514. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  8515. }
  8516. }
  8517. tsEatThenParseType(token) {
  8518. if (this.match(token)) {
  8519. return this.tsNextThenParseType();
  8520. }
  8521. }
  8522. tsExpectThenParseType(token) {
  8523. return this.tsInType(() => {
  8524. this.expect(token);
  8525. return this.tsParseType();
  8526. });
  8527. }
  8528. tsNextThenParseType() {
  8529. return this.tsInType(() => {
  8530. this.next();
  8531. return this.tsParseType();
  8532. });
  8533. }
  8534. tsParseEnumMember() {
  8535. const node = this.startNode();
  8536. node.id = this.match(133) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
  8537. if (this.eat(29)) {
  8538. node.initializer = super.parseMaybeAssignAllowIn();
  8539. }
  8540. return this.finishNode(node, "TSEnumMember");
  8541. }
  8542. tsParseEnumDeclaration(node, properties = {}) {
  8543. if (properties.const) node.const = true;
  8544. if (properties.declare) node.declare = true;
  8545. this.expectContextual(126);
  8546. node.id = this.parseIdentifier();
  8547. this.checkIdentifier(node.id, node.const ? 8971 : 8459);
  8548. this.expect(5);
  8549. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8550. this.expect(8);
  8551. return this.finishNode(node, "TSEnumDeclaration");
  8552. }
  8553. tsParseModuleBlock() {
  8554. const node = this.startNode();
  8555. this.scope.enter(0);
  8556. this.expect(5);
  8557. super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8558. this.scope.exit();
  8559. return this.finishNode(node, "TSModuleBlock");
  8560. }
  8561. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8562. node.id = this.parseIdentifier();
  8563. if (!nested) {
  8564. this.checkIdentifier(node.id, 1024);
  8565. }
  8566. if (this.eat(16)) {
  8567. const inner = this.startNode();
  8568. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8569. node.body = inner;
  8570. } else {
  8571. this.scope.enter(256);
  8572. this.prodParam.enter(0);
  8573. node.body = this.tsParseModuleBlock();
  8574. this.prodParam.exit();
  8575. this.scope.exit();
  8576. }
  8577. return this.finishNode(node, "TSModuleDeclaration");
  8578. }
  8579. tsParseAmbientExternalModuleDeclaration(node) {
  8580. if (this.isContextual(112)) {
  8581. node.global = true;
  8582. node.id = this.parseIdentifier();
  8583. } else if (this.match(133)) {
  8584. node.id = super.parseStringLiteral(this.state.value);
  8585. } else {
  8586. this.unexpected();
  8587. }
  8588. if (this.match(5)) {
  8589. this.scope.enter(256);
  8590. this.prodParam.enter(0);
  8591. node.body = this.tsParseModuleBlock();
  8592. this.prodParam.exit();
  8593. this.scope.exit();
  8594. } else {
  8595. this.semicolon();
  8596. }
  8597. return this.finishNode(node, "TSModuleDeclaration");
  8598. }
  8599. tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
  8600. node.isExport = isExport || false;
  8601. node.id = maybeDefaultIdentifier || this.parseIdentifier();
  8602. this.checkIdentifier(node.id, 4096);
  8603. this.expect(29);
  8604. const moduleReference = this.tsParseModuleReference();
  8605. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8606. this.raise(TSErrors.ImportAliasHasImportType, moduleReference);
  8607. }
  8608. node.moduleReference = moduleReference;
  8609. this.semicolon();
  8610. return this.finishNode(node, "TSImportEqualsDeclaration");
  8611. }
  8612. tsIsExternalModuleReference() {
  8613. return this.isContextual(119) && this.lookaheadCharCode() === 40;
  8614. }
  8615. tsParseModuleReference() {
  8616. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  8617. }
  8618. tsParseExternalModuleReference() {
  8619. const node = this.startNode();
  8620. this.expectContextual(119);
  8621. this.expect(10);
  8622. if (!this.match(133)) {
  8623. this.unexpected();
  8624. }
  8625. node.expression = super.parseExprAtom();
  8626. this.expect(11);
  8627. this.sawUnambiguousESM = true;
  8628. return this.finishNode(node, "TSExternalModuleReference");
  8629. }
  8630. tsLookAhead(f) {
  8631. const state = this.state.clone();
  8632. const res = f();
  8633. this.state = state;
  8634. return res;
  8635. }
  8636. tsTryParseAndCatch(f) {
  8637. const result = this.tryParse(abort => f() || abort());
  8638. if (result.aborted || !result.node) return;
  8639. if (result.error) this.state = result.failState;
  8640. return result.node;
  8641. }
  8642. tsTryParse(f) {
  8643. const state = this.state.clone();
  8644. const result = f();
  8645. if (result !== undefined && result !== false) {
  8646. return result;
  8647. }
  8648. this.state = state;
  8649. }
  8650. tsTryParseDeclare(nany) {
  8651. if (this.isLineTerminator()) {
  8652. return;
  8653. }
  8654. let startType = this.state.type;
  8655. let kind;
  8656. if (this.isContextual(100)) {
  8657. startType = 74;
  8658. kind = "let";
  8659. }
  8660. return this.tsInAmbientContext(() => {
  8661. switch (startType) {
  8662. case 68:
  8663. nany.declare = true;
  8664. return super.parseFunctionStatement(nany, false, false);
  8665. case 80:
  8666. nany.declare = true;
  8667. return this.parseClass(nany, true, false);
  8668. case 126:
  8669. return this.tsParseEnumDeclaration(nany, {
  8670. declare: true
  8671. });
  8672. case 112:
  8673. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8674. case 75:
  8675. case 74:
  8676. if (!this.match(75) || !this.isLookaheadContextual("enum")) {
  8677. nany.declare = true;
  8678. return this.parseVarStatement(nany, kind || this.state.value, true);
  8679. }
  8680. this.expect(75);
  8681. return this.tsParseEnumDeclaration(nany, {
  8682. const: true,
  8683. declare: true
  8684. });
  8685. case 129:
  8686. {
  8687. const result = this.tsParseInterfaceDeclaration(nany, {
  8688. declare: true
  8689. });
  8690. if (result) return result;
  8691. }
  8692. default:
  8693. if (tokenIsIdentifier(startType)) {
  8694. return this.tsParseDeclaration(nany, this.state.value, true, null);
  8695. }
  8696. }
  8697. });
  8698. }
  8699. tsTryParseExportDeclaration() {
  8700. return this.tsParseDeclaration(this.startNode(), this.state.value, true, null);
  8701. }
  8702. tsParseExpressionStatement(node, expr, decorators) {
  8703. switch (expr.name) {
  8704. case "declare":
  8705. {
  8706. const declaration = this.tsTryParseDeclare(node);
  8707. if (declaration) {
  8708. declaration.declare = true;
  8709. }
  8710. return declaration;
  8711. }
  8712. case "global":
  8713. if (this.match(5)) {
  8714. this.scope.enter(256);
  8715. this.prodParam.enter(0);
  8716. const mod = node;
  8717. mod.global = true;
  8718. mod.id = expr;
  8719. mod.body = this.tsParseModuleBlock();
  8720. this.scope.exit();
  8721. this.prodParam.exit();
  8722. return this.finishNode(mod, "TSModuleDeclaration");
  8723. }
  8724. break;
  8725. default:
  8726. return this.tsParseDeclaration(node, expr.name, false, decorators);
  8727. }
  8728. }
  8729. tsParseDeclaration(node, value, next, decorators) {
  8730. switch (value) {
  8731. case "abstract":
  8732. if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
  8733. return this.tsParseAbstractDeclaration(node, decorators);
  8734. }
  8735. break;
  8736. case "module":
  8737. if (this.tsCheckLineTerminator(next)) {
  8738. if (this.match(133)) {
  8739. return this.tsParseAmbientExternalModuleDeclaration(node);
  8740. } else if (tokenIsIdentifier(this.state.type)) {
  8741. return this.tsParseModuleOrNamespaceDeclaration(node);
  8742. }
  8743. }
  8744. break;
  8745. case "namespace":
  8746. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8747. return this.tsParseModuleOrNamespaceDeclaration(node);
  8748. }
  8749. break;
  8750. case "type":
  8751. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8752. return this.tsParseTypeAliasDeclaration(node);
  8753. }
  8754. break;
  8755. }
  8756. }
  8757. tsCheckLineTerminator(next) {
  8758. if (next) {
  8759. if (this.hasFollowingLineBreak()) return false;
  8760. this.next();
  8761. return true;
  8762. }
  8763. return !this.isLineTerminator();
  8764. }
  8765. tsTryParseGenericAsyncArrowFunction(startLoc) {
  8766. if (!this.match(47)) return;
  8767. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8768. this.state.maybeInArrowParameters = true;
  8769. const res = this.tsTryParseAndCatch(() => {
  8770. const node = this.startNodeAt(startLoc);
  8771. node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  8772. super.parseFunctionParams(node);
  8773. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8774. this.expect(19);
  8775. return node;
  8776. });
  8777. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8778. if (!res) return;
  8779. return super.parseArrowExpression(res, null, true);
  8780. }
  8781. tsParseTypeArgumentsInExpression() {
  8782. if (this.reScan_lt() !== 47) return;
  8783. return this.tsParseTypeArguments();
  8784. }
  8785. tsParseTypeArguments() {
  8786. const node = this.startNode();
  8787. node.params = this.tsInType(() => this.tsInNoContext(() => {
  8788. this.expect(47);
  8789. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  8790. }));
  8791. if (node.params.length === 0) {
  8792. this.raise(TSErrors.EmptyTypeArguments, node);
  8793. } else if (!this.state.inType && this.curContext() === types.brace) {
  8794. this.reScan_lt_gt();
  8795. }
  8796. this.expect(48);
  8797. return this.finishNode(node, "TSTypeParameterInstantiation");
  8798. }
  8799. tsIsDeclarationStart() {
  8800. return tokenIsTSDeclarationStart(this.state.type);
  8801. }
  8802. isExportDefaultSpecifier() {
  8803. if (this.tsIsDeclarationStart()) return false;
  8804. return super.isExportDefaultSpecifier();
  8805. }
  8806. parseAssignableListItem(flags, decorators) {
  8807. const startLoc = this.state.startLoc;
  8808. const modified = {};
  8809. this.tsParseModifiers({
  8810. allowedModifiers: ["public", "private", "protected", "override", "readonly"]
  8811. }, modified);
  8812. const accessibility = modified.accessibility;
  8813. const override = modified.override;
  8814. const readonly = modified.readonly;
  8815. if (!(flags & 4) && (accessibility || readonly || override)) {
  8816. this.raise(TSErrors.UnexpectedParameterModifier, startLoc);
  8817. }
  8818. const left = this.parseMaybeDefault();
  8819. this.parseAssignableListItemTypes(left, flags);
  8820. const elt = this.parseMaybeDefault(left.loc.start, left);
  8821. if (accessibility || readonly || override) {
  8822. const pp = this.startNodeAt(startLoc);
  8823. if (decorators.length) {
  8824. pp.decorators = decorators;
  8825. }
  8826. if (accessibility) pp.accessibility = accessibility;
  8827. if (readonly) pp.readonly = readonly;
  8828. if (override) pp.override = override;
  8829. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  8830. this.raise(TSErrors.UnsupportedParameterPropertyKind, pp);
  8831. }
  8832. pp.parameter = elt;
  8833. return this.finishNode(pp, "TSParameterProperty");
  8834. }
  8835. if (decorators.length) {
  8836. left.decorators = decorators;
  8837. }
  8838. return elt;
  8839. }
  8840. isSimpleParameter(node) {
  8841. return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node);
  8842. }
  8843. tsDisallowOptionalPattern(node) {
  8844. for (const param of node.params) {
  8845. if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) {
  8846. this.raise(TSErrors.PatternIsOptional, param);
  8847. }
  8848. }
  8849. }
  8850. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  8851. super.setArrowFunctionParameters(node, params, trailingCommaLoc);
  8852. this.tsDisallowOptionalPattern(node);
  8853. }
  8854. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8855. if (this.match(14)) {
  8856. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  8857. }
  8858. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  8859. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  8860. return this.finishNode(node, bodilessType);
  8861. }
  8862. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  8863. this.raise(TSErrors.DeclareFunctionHasImplementation, node);
  8864. if (node.declare) {
  8865. return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  8866. }
  8867. }
  8868. this.tsDisallowOptionalPattern(node);
  8869. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  8870. }
  8871. registerFunctionStatementId(node) {
  8872. if (!node.body && node.id) {
  8873. this.checkIdentifier(node.id, 1024);
  8874. } else {
  8875. super.registerFunctionStatementId(node);
  8876. }
  8877. }
  8878. tsCheckForInvalidTypeCasts(items) {
  8879. items.forEach(node => {
  8880. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  8881. this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation);
  8882. }
  8883. });
  8884. }
  8885. toReferencedList(exprList, isInParens) {
  8886. this.tsCheckForInvalidTypeCasts(exprList);
  8887. return exprList;
  8888. }
  8889. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  8890. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  8891. if (node.type === "ArrayExpression") {
  8892. this.tsCheckForInvalidTypeCasts(node.elements);
  8893. }
  8894. return node;
  8895. }
  8896. parseSubscript(base, startLoc, noCalls, state) {
  8897. if (!this.hasPrecedingLineBreak() && this.match(35)) {
  8898. this.state.canStartJSXElement = false;
  8899. this.next();
  8900. const nonNullExpression = this.startNodeAt(startLoc);
  8901. nonNullExpression.expression = base;
  8902. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  8903. }
  8904. let isOptionalCall = false;
  8905. if (this.match(18) && this.lookaheadCharCode() === 60) {
  8906. if (noCalls) {
  8907. state.stop = true;
  8908. return base;
  8909. }
  8910. state.optionalChainMember = isOptionalCall = true;
  8911. this.next();
  8912. }
  8913. if (this.match(47) || this.match(51)) {
  8914. let missingParenErrorLoc;
  8915. const result = this.tsTryParseAndCatch(() => {
  8916. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  8917. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
  8918. if (asyncArrowFn) {
  8919. return asyncArrowFn;
  8920. }
  8921. }
  8922. const typeArguments = this.tsParseTypeArgumentsInExpression();
  8923. if (!typeArguments) return;
  8924. if (isOptionalCall && !this.match(10)) {
  8925. missingParenErrorLoc = this.state.curPosition();
  8926. return;
  8927. }
  8928. if (tokenIsTemplate(this.state.type)) {
  8929. const result = super.parseTaggedTemplateExpression(base, startLoc, state);
  8930. result.typeParameters = typeArguments;
  8931. return result;
  8932. }
  8933. if (!noCalls && this.eat(10)) {
  8934. const node = this.startNodeAt(startLoc);
  8935. node.callee = base;
  8936. node.arguments = this.parseCallExpressionArguments(11, false);
  8937. this.tsCheckForInvalidTypeCasts(node.arguments);
  8938. node.typeParameters = typeArguments;
  8939. if (state.optionalChainMember) {
  8940. node.optional = isOptionalCall;
  8941. }
  8942. return this.finishCallExpression(node, state.optionalChainMember);
  8943. }
  8944. const tokenType = this.state.type;
  8945. if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
  8946. return;
  8947. }
  8948. const node = this.startNodeAt(startLoc);
  8949. node.expression = base;
  8950. node.typeParameters = typeArguments;
  8951. return this.finishNode(node, "TSInstantiationExpression");
  8952. });
  8953. if (missingParenErrorLoc) {
  8954. this.unexpected(missingParenErrorLoc, 10);
  8955. }
  8956. if (result) {
  8957. if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) {
  8958. this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc);
  8959. }
  8960. return result;
  8961. }
  8962. }
  8963. return super.parseSubscript(base, startLoc, noCalls, state);
  8964. }
  8965. parseNewCallee(node) {
  8966. var _callee$extra;
  8967. super.parseNewCallee(node);
  8968. const {
  8969. callee
  8970. } = node;
  8971. if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
  8972. node.typeParameters = callee.typeParameters;
  8973. node.callee = callee.expression;
  8974. }
  8975. }
  8976. parseExprOp(left, leftStartLoc, minPrec) {
  8977. let isSatisfies;
  8978. if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) {
  8979. const node = this.startNodeAt(leftStartLoc);
  8980. node.expression = left;
  8981. node.typeAnnotation = this.tsInType(() => {
  8982. this.next();
  8983. if (this.match(75)) {
  8984. if (isSatisfies) {
  8985. this.raise(Errors.UnexpectedKeyword, this.state.startLoc, {
  8986. keyword: "const"
  8987. });
  8988. }
  8989. return this.tsParseTypeReference();
  8990. }
  8991. return this.tsParseType();
  8992. });
  8993. this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
  8994. this.reScan_lt_gt();
  8995. return this.parseExprOp(node, leftStartLoc, minPrec);
  8996. }
  8997. return super.parseExprOp(left, leftStartLoc, minPrec);
  8998. }
  8999. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9000. if (!this.state.isAmbientContext) {
  9001. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  9002. }
  9003. }
  9004. checkImportReflection(node) {
  9005. super.checkImportReflection(node);
  9006. if (node.module && node.importKind !== "value") {
  9007. this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  9008. }
  9009. }
  9010. checkDuplicateExports() {}
  9011. isPotentialImportPhase(isExport) {
  9012. if (super.isPotentialImportPhase(isExport)) return true;
  9013. if (this.isContextual(130)) {
  9014. const ch = this.lookaheadCharCode();
  9015. return isExport ? ch === 123 || ch === 42 : ch !== 61;
  9016. }
  9017. return !isExport && this.isContextual(87);
  9018. }
  9019. applyImportPhase(node, isExport, phase, loc) {
  9020. super.applyImportPhase(node, isExport, phase, loc);
  9021. if (isExport) {
  9022. node.exportKind = phase === "type" ? "type" : "value";
  9023. } else {
  9024. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  9025. }
  9026. }
  9027. parseImport(node) {
  9028. if (this.match(133)) {
  9029. node.importKind = "value";
  9030. return super.parseImport(node);
  9031. }
  9032. let importNode;
  9033. if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) {
  9034. node.importKind = "value";
  9035. return this.tsParseImportEqualsDeclaration(node);
  9036. } else if (this.isContextual(130)) {
  9037. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false);
  9038. if (this.lookaheadCharCode() === 61) {
  9039. return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier);
  9040. } else {
  9041. importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier);
  9042. }
  9043. } else {
  9044. importNode = super.parseImport(node);
  9045. }
  9046. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  9047. this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode);
  9048. }
  9049. return importNode;
  9050. }
  9051. parseExport(node, decorators) {
  9052. if (this.match(83)) {
  9053. this.next();
  9054. const nodeImportEquals = node;
  9055. let maybeDefaultIdentifier = null;
  9056. if (this.isContextual(130) && this.isPotentialImportPhase(false)) {
  9057. maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false);
  9058. } else {
  9059. nodeImportEquals.importKind = "value";
  9060. }
  9061. return this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true);
  9062. } else if (this.eat(29)) {
  9063. const assign = node;
  9064. assign.expression = super.parseExpression();
  9065. this.semicolon();
  9066. this.sawUnambiguousESM = true;
  9067. return this.finishNode(assign, "TSExportAssignment");
  9068. } else if (this.eatContextual(93)) {
  9069. const decl = node;
  9070. this.expectContextual(128);
  9071. decl.id = this.parseIdentifier();
  9072. this.semicolon();
  9073. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  9074. } else {
  9075. return super.parseExport(node, decorators);
  9076. }
  9077. }
  9078. isAbstractClass() {
  9079. return this.isContextual(124) && this.lookahead().type === 80;
  9080. }
  9081. parseExportDefaultExpression() {
  9082. if (this.isAbstractClass()) {
  9083. const cls = this.startNode();
  9084. this.next();
  9085. cls.abstract = true;
  9086. return this.parseClass(cls, true, true);
  9087. }
  9088. if (this.match(129)) {
  9089. const result = this.tsParseInterfaceDeclaration(this.startNode());
  9090. if (result) return result;
  9091. }
  9092. return super.parseExportDefaultExpression();
  9093. }
  9094. parseVarStatement(node, kind, allowMissingInitializer = false) {
  9095. const {
  9096. isAmbientContext
  9097. } = this.state;
  9098. const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext);
  9099. if (!isAmbientContext) return declaration;
  9100. for (const {
  9101. id,
  9102. init
  9103. } of declaration.declarations) {
  9104. if (!init) continue;
  9105. if (kind !== "const" || !!id.typeAnnotation) {
  9106. this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init);
  9107. } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) {
  9108. this.raise(TSErrors.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference, init);
  9109. }
  9110. }
  9111. return declaration;
  9112. }
  9113. parseStatementContent(flags, decorators) {
  9114. if (this.match(75) && this.isLookaheadContextual("enum")) {
  9115. const node = this.startNode();
  9116. this.expect(75);
  9117. return this.tsParseEnumDeclaration(node, {
  9118. const: true
  9119. });
  9120. }
  9121. if (this.isContextual(126)) {
  9122. return this.tsParseEnumDeclaration(this.startNode());
  9123. }
  9124. if (this.isContextual(129)) {
  9125. const result = this.tsParseInterfaceDeclaration(this.startNode());
  9126. if (result) return result;
  9127. }
  9128. return super.parseStatementContent(flags, decorators);
  9129. }
  9130. parseAccessModifier() {
  9131. return this.tsParseModifier(["public", "protected", "private"]);
  9132. }
  9133. tsHasSomeModifiers(member, modifiers) {
  9134. return modifiers.some(modifier => {
  9135. if (tsIsAccessModifier(modifier)) {
  9136. return member.accessibility === modifier;
  9137. }
  9138. return !!member[modifier];
  9139. });
  9140. }
  9141. tsIsStartOfStaticBlocks() {
  9142. return this.isContextual(106) && this.lookaheadCharCode() === 123;
  9143. }
  9144. parseClassMember(classBody, member, state) {
  9145. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  9146. this.tsParseModifiers({
  9147. allowedModifiers: modifiers,
  9148. disallowedModifiers: ["in", "out"],
  9149. stopOnStartOfClassStaticBlock: true,
  9150. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  9151. }, member);
  9152. const callParseClassMemberWithIsStatic = () => {
  9153. if (this.tsIsStartOfStaticBlocks()) {
  9154. this.next();
  9155. this.next();
  9156. if (this.tsHasSomeModifiers(member, modifiers)) {
  9157. this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition());
  9158. }
  9159. super.parseClassStaticBlock(classBody, member);
  9160. } else {
  9161. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  9162. }
  9163. };
  9164. if (member.declare) {
  9165. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  9166. } else {
  9167. callParseClassMemberWithIsStatic();
  9168. }
  9169. }
  9170. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  9171. const idx = this.tsTryParseIndexSignature(member);
  9172. if (idx) {
  9173. classBody.body.push(idx);
  9174. if (member.abstract) {
  9175. this.raise(TSErrors.IndexSignatureHasAbstract, member);
  9176. }
  9177. if (member.accessibility) {
  9178. this.raise(TSErrors.IndexSignatureHasAccessibility, member, {
  9179. modifier: member.accessibility
  9180. });
  9181. }
  9182. if (member.declare) {
  9183. this.raise(TSErrors.IndexSignatureHasDeclare, member);
  9184. }
  9185. if (member.override) {
  9186. this.raise(TSErrors.IndexSignatureHasOverride, member);
  9187. }
  9188. return;
  9189. }
  9190. if (!this.state.inAbstractClass && member.abstract) {
  9191. this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member);
  9192. }
  9193. if (member.override) {
  9194. if (!state.hadSuperClass) {
  9195. this.raise(TSErrors.OverrideNotInSubClass, member);
  9196. }
  9197. }
  9198. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  9199. }
  9200. parsePostMemberNameModifiers(methodOrProp) {
  9201. const optional = this.eat(17);
  9202. if (optional) methodOrProp.optional = true;
  9203. if (methodOrProp.readonly && this.match(10)) {
  9204. this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp);
  9205. }
  9206. if (methodOrProp.declare && this.match(10)) {
  9207. this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp);
  9208. }
  9209. }
  9210. parseExpressionStatement(node, expr, decorators) {
  9211. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr, decorators) : undefined;
  9212. return decl || super.parseExpressionStatement(node, expr, decorators);
  9213. }
  9214. shouldParseExportDeclaration() {
  9215. if (this.tsIsDeclarationStart()) return true;
  9216. return super.shouldParseExportDeclaration();
  9217. }
  9218. parseConditional(expr, startLoc, refExpressionErrors) {
  9219. if (!this.state.maybeInArrowParameters || !this.match(17)) {
  9220. return super.parseConditional(expr, startLoc, refExpressionErrors);
  9221. }
  9222. const result = this.tryParse(() => super.parseConditional(expr, startLoc));
  9223. if (!result.node) {
  9224. if (result.error) {
  9225. super.setOptionalParametersError(refExpressionErrors, result.error);
  9226. }
  9227. return expr;
  9228. }
  9229. if (result.error) this.state = result.failState;
  9230. return result.node;
  9231. }
  9232. parseParenItem(node, startLoc) {
  9233. const newNode = super.parseParenItem(node, startLoc);
  9234. if (this.eat(17)) {
  9235. newNode.optional = true;
  9236. this.resetEndLocation(node);
  9237. }
  9238. if (this.match(14)) {
  9239. const typeCastNode = this.startNodeAt(startLoc);
  9240. typeCastNode.expression = node;
  9241. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  9242. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  9243. }
  9244. return node;
  9245. }
  9246. parseExportDeclaration(node) {
  9247. if (!this.state.isAmbientContext && this.isContextual(125)) {
  9248. return this.tsInAmbientContext(() => this.parseExportDeclaration(node));
  9249. }
  9250. const startLoc = this.state.startLoc;
  9251. const isDeclare = this.eatContextual(125);
  9252. if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) {
  9253. throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc);
  9254. }
  9255. const isIdentifier = tokenIsIdentifier(this.state.type);
  9256. const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node);
  9257. if (!declaration) return null;
  9258. if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) {
  9259. node.exportKind = "type";
  9260. }
  9261. if (isDeclare) {
  9262. this.resetStartLocation(declaration, startLoc);
  9263. declaration.declare = true;
  9264. }
  9265. return declaration;
  9266. }
  9267. parseClassId(node, isStatement, optionalId, bindingType) {
  9268. if ((!isStatement || optionalId) && this.isContextual(113)) {
  9269. return;
  9270. }
  9271. super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331);
  9272. const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  9273. if (typeParameters) node.typeParameters = typeParameters;
  9274. }
  9275. parseClassPropertyAnnotation(node) {
  9276. if (!node.optional) {
  9277. if (this.eat(35)) {
  9278. node.definite = true;
  9279. } else if (this.eat(17)) {
  9280. node.optional = true;
  9281. }
  9282. }
  9283. const type = this.tsTryParseTypeAnnotation();
  9284. if (type) node.typeAnnotation = type;
  9285. }
  9286. parseClassProperty(node) {
  9287. this.parseClassPropertyAnnotation(node);
  9288. if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) {
  9289. this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc);
  9290. }
  9291. if (node.abstract && this.match(29)) {
  9292. const {
  9293. key
  9294. } = node;
  9295. this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, {
  9296. propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`
  9297. });
  9298. }
  9299. return super.parseClassProperty(node);
  9300. }
  9301. parseClassPrivateProperty(node) {
  9302. if (node.abstract) {
  9303. this.raise(TSErrors.PrivateElementHasAbstract, node);
  9304. }
  9305. if (node.accessibility) {
  9306. this.raise(TSErrors.PrivateElementHasAccessibility, node, {
  9307. modifier: node.accessibility
  9308. });
  9309. }
  9310. this.parseClassPropertyAnnotation(node);
  9311. return super.parseClassPrivateProperty(node);
  9312. }
  9313. parseClassAccessorProperty(node) {
  9314. this.parseClassPropertyAnnotation(node);
  9315. if (node.optional) {
  9316. this.raise(TSErrors.AccessorCannotBeOptional, node);
  9317. }
  9318. return super.parseClassAccessorProperty(node);
  9319. }
  9320. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9321. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9322. if (typeParameters && isConstructor) {
  9323. this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters);
  9324. }
  9325. const {
  9326. declare = false,
  9327. kind
  9328. } = method;
  9329. if (declare && (kind === "get" || kind === "set")) {
  9330. this.raise(TSErrors.DeclareAccessor, method, {
  9331. kind
  9332. });
  9333. }
  9334. if (typeParameters) method.typeParameters = typeParameters;
  9335. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  9336. }
  9337. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9338. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9339. if (typeParameters) method.typeParameters = typeParameters;
  9340. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  9341. }
  9342. declareClassPrivateMethodInScope(node, kind) {
  9343. if (node.type === "TSDeclareMethod") return;
  9344. if (node.type === "MethodDefinition" && !hasOwnProperty.call(node.value, "body")) {
  9345. return;
  9346. }
  9347. super.declareClassPrivateMethodInScope(node, kind);
  9348. }
  9349. parseClassSuper(node) {
  9350. super.parseClassSuper(node);
  9351. if (node.superClass && (this.match(47) || this.match(51))) {
  9352. node.superTypeParameters = this.tsParseTypeArgumentsInExpression();
  9353. }
  9354. if (this.eatContextual(113)) {
  9355. node.implements = this.tsParseHeritageClause("implements");
  9356. }
  9357. }
  9358. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9359. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9360. if (typeParameters) prop.typeParameters = typeParameters;
  9361. return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  9362. }
  9363. parseFunctionParams(node, isConstructor) {
  9364. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  9365. if (typeParameters) node.typeParameters = typeParameters;
  9366. super.parseFunctionParams(node, isConstructor);
  9367. }
  9368. parseVarId(decl, kind) {
  9369. super.parseVarId(decl, kind);
  9370. if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
  9371. decl.definite = true;
  9372. }
  9373. const type = this.tsTryParseTypeAnnotation();
  9374. if (type) {
  9375. decl.id.typeAnnotation = type;
  9376. this.resetEndLocation(decl.id);
  9377. }
  9378. }
  9379. parseAsyncArrowFromCallExpression(node, call) {
  9380. if (this.match(14)) {
  9381. node.returnType = this.tsParseTypeAnnotation();
  9382. }
  9383. return super.parseAsyncArrowFromCallExpression(node, call);
  9384. }
  9385. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  9386. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2;
  9387. let state;
  9388. let jsx;
  9389. let typeCast;
  9390. if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) {
  9391. state = this.state.clone();
  9392. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9393. if (!jsx.error) return jsx.node;
  9394. const {
  9395. context
  9396. } = this.state;
  9397. const currentContext = context[context.length - 1];
  9398. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  9399. context.pop();
  9400. }
  9401. }
  9402. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) {
  9403. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9404. }
  9405. if (!state || state === this.state) state = this.state.clone();
  9406. let typeParameters;
  9407. const arrow = this.tryParse(abort => {
  9408. var _expr$extra, _typeParameters;
  9409. typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  9410. const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  9411. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  9412. abort();
  9413. }
  9414. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  9415. this.resetStartLocationFromNode(expr, typeParameters);
  9416. }
  9417. expr.typeParameters = typeParameters;
  9418. return expr;
  9419. }, state);
  9420. if (!arrow.error && !arrow.aborted) {
  9421. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9422. return arrow.node;
  9423. }
  9424. if (!jsx) {
  9425. assert(!this.hasPlugin("jsx"));
  9426. typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  9427. if (!typeCast.error) return typeCast.node;
  9428. }
  9429. if ((_jsx2 = jsx) != null && _jsx2.node) {
  9430. this.state = jsx.failState;
  9431. return jsx.node;
  9432. }
  9433. if (arrow.node) {
  9434. this.state = arrow.failState;
  9435. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  9436. return arrow.node;
  9437. }
  9438. if ((_typeCast = typeCast) != null && _typeCast.node) {
  9439. this.state = typeCast.failState;
  9440. return typeCast.node;
  9441. }
  9442. throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error);
  9443. }
  9444. reportReservedArrowTypeParam(node) {
  9445. var _node$extra;
  9446. if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  9447. this.raise(TSErrors.ReservedArrowTypeParam, node);
  9448. }
  9449. }
  9450. parseMaybeUnary(refExpressionErrors, sawUnary) {
  9451. if (!this.hasPlugin("jsx") && this.match(47)) {
  9452. return this.tsParseTypeAssertion();
  9453. }
  9454. return super.parseMaybeUnary(refExpressionErrors, sawUnary);
  9455. }
  9456. parseArrow(node) {
  9457. if (this.match(14)) {
  9458. const result = this.tryParse(abort => {
  9459. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9460. if (this.canInsertSemicolon() || !this.match(19)) abort();
  9461. return returnType;
  9462. });
  9463. if (result.aborted) return;
  9464. if (!result.thrown) {
  9465. if (result.error) this.state = result.failState;
  9466. node.returnType = result.node;
  9467. }
  9468. }
  9469. return super.parseArrow(node);
  9470. }
  9471. parseAssignableListItemTypes(param, flags) {
  9472. if (!(flags & 2)) return param;
  9473. if (this.eat(17)) {
  9474. param.optional = true;
  9475. }
  9476. const type = this.tsTryParseTypeAnnotation();
  9477. if (type) param.typeAnnotation = type;
  9478. this.resetEndLocation(param);
  9479. return param;
  9480. }
  9481. isAssignable(node, isBinding) {
  9482. switch (node.type) {
  9483. case "TSTypeCastExpression":
  9484. return this.isAssignable(node.expression, isBinding);
  9485. case "TSParameterProperty":
  9486. return true;
  9487. default:
  9488. return super.isAssignable(node, isBinding);
  9489. }
  9490. }
  9491. toAssignable(node, isLHS = false) {
  9492. switch (node.type) {
  9493. case "ParenthesizedExpression":
  9494. this.toAssignableParenthesizedExpression(node, isLHS);
  9495. break;
  9496. case "TSAsExpression":
  9497. case "TSSatisfiesExpression":
  9498. case "TSNonNullExpression":
  9499. case "TSTypeAssertion":
  9500. if (isLHS) {
  9501. this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node);
  9502. } else {
  9503. this.raise(TSErrors.UnexpectedTypeCastInParameter, node);
  9504. }
  9505. this.toAssignable(node.expression, isLHS);
  9506. break;
  9507. case "AssignmentExpression":
  9508. if (!isLHS && node.left.type === "TSTypeCastExpression") {
  9509. node.left = this.typeCastToParameter(node.left);
  9510. }
  9511. default:
  9512. super.toAssignable(node, isLHS);
  9513. }
  9514. }
  9515. toAssignableParenthesizedExpression(node, isLHS) {
  9516. switch (node.expression.type) {
  9517. case "TSAsExpression":
  9518. case "TSSatisfiesExpression":
  9519. case "TSNonNullExpression":
  9520. case "TSTypeAssertion":
  9521. case "ParenthesizedExpression":
  9522. this.toAssignable(node.expression, isLHS);
  9523. break;
  9524. default:
  9525. super.toAssignable(node, isLHS);
  9526. }
  9527. }
  9528. checkToRestConversion(node, allowPattern) {
  9529. switch (node.type) {
  9530. case "TSAsExpression":
  9531. case "TSSatisfiesExpression":
  9532. case "TSTypeAssertion":
  9533. case "TSNonNullExpression":
  9534. this.checkToRestConversion(node.expression, false);
  9535. break;
  9536. default:
  9537. super.checkToRestConversion(node, allowPattern);
  9538. }
  9539. }
  9540. isValidLVal(type, isUnparenthesizedInAssign, binding) {
  9541. switch (type) {
  9542. case "TSTypeCastExpression":
  9543. return true;
  9544. case "TSParameterProperty":
  9545. return "parameter";
  9546. case "TSNonNullExpression":
  9547. case "TSInstantiationExpression":
  9548. return "expression";
  9549. case "TSAsExpression":
  9550. case "TSSatisfiesExpression":
  9551. case "TSTypeAssertion":
  9552. return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true];
  9553. default:
  9554. return super.isValidLVal(type, isUnparenthesizedInAssign, binding);
  9555. }
  9556. }
  9557. parseBindingAtom() {
  9558. if (this.state.type === 78) {
  9559. return this.parseIdentifier(true);
  9560. }
  9561. return super.parseBindingAtom();
  9562. }
  9563. parseMaybeDecoratorArguments(expr) {
  9564. if (this.match(47) || this.match(51)) {
  9565. const typeArguments = this.tsParseTypeArgumentsInExpression();
  9566. if (this.match(10)) {
  9567. const call = super.parseMaybeDecoratorArguments(expr);
  9568. call.typeParameters = typeArguments;
  9569. return call;
  9570. }
  9571. this.unexpected(null, 10);
  9572. }
  9573. return super.parseMaybeDecoratorArguments(expr);
  9574. }
  9575. checkCommaAfterRest(close) {
  9576. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9577. this.next();
  9578. return false;
  9579. }
  9580. return super.checkCommaAfterRest(close);
  9581. }
  9582. isClassMethod() {
  9583. return this.match(47) || super.isClassMethod();
  9584. }
  9585. isClassProperty() {
  9586. return this.match(35) || this.match(14) || super.isClassProperty();
  9587. }
  9588. parseMaybeDefault(startLoc, left) {
  9589. const node = super.parseMaybeDefault(startLoc, left);
  9590. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9591. this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation);
  9592. }
  9593. return node;
  9594. }
  9595. getTokenFromCode(code) {
  9596. if (this.state.inType) {
  9597. if (code === 62) {
  9598. this.finishOp(48, 1);
  9599. return;
  9600. }
  9601. if (code === 60) {
  9602. this.finishOp(47, 1);
  9603. return;
  9604. }
  9605. }
  9606. super.getTokenFromCode(code);
  9607. }
  9608. reScan_lt_gt() {
  9609. const {
  9610. type
  9611. } = this.state;
  9612. if (type === 47) {
  9613. this.state.pos -= 1;
  9614. this.readToken_lt();
  9615. } else if (type === 48) {
  9616. this.state.pos -= 1;
  9617. this.readToken_gt();
  9618. }
  9619. }
  9620. reScan_lt() {
  9621. const {
  9622. type
  9623. } = this.state;
  9624. if (type === 51) {
  9625. this.state.pos -= 2;
  9626. this.finishOp(47, 1);
  9627. return 47;
  9628. }
  9629. return type;
  9630. }
  9631. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  9632. for (let i = 0; i < exprList.length; i++) {
  9633. const expr = exprList[i];
  9634. if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") {
  9635. exprList[i] = this.typeCastToParameter(expr);
  9636. }
  9637. }
  9638. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  9639. }
  9640. typeCastToParameter(node) {
  9641. node.expression.typeAnnotation = node.typeAnnotation;
  9642. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  9643. return node.expression;
  9644. }
  9645. shouldParseArrow(params) {
  9646. if (this.match(14)) {
  9647. return params.every(expr => this.isAssignable(expr, true));
  9648. }
  9649. return super.shouldParseArrow(params);
  9650. }
  9651. shouldParseAsyncArrow() {
  9652. return this.match(14) || super.shouldParseAsyncArrow();
  9653. }
  9654. canHaveLeadingDecorator() {
  9655. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9656. }
  9657. jsxParseOpeningElementAfterName(node) {
  9658. if (this.match(47) || this.match(51)) {
  9659. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression());
  9660. if (typeArguments) node.typeParameters = typeArguments;
  9661. }
  9662. return super.jsxParseOpeningElementAfterName(node);
  9663. }
  9664. getGetterSetterExpectedParamCount(method) {
  9665. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9666. const params = this.getObjectOrClassMethodParams(method);
  9667. const firstParam = params[0];
  9668. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9669. return hasContextParam ? baseCount + 1 : baseCount;
  9670. }
  9671. parseCatchClauseParam() {
  9672. const param = super.parseCatchClauseParam();
  9673. const type = this.tsTryParseTypeAnnotation();
  9674. if (type) {
  9675. param.typeAnnotation = type;
  9676. this.resetEndLocation(param);
  9677. }
  9678. return param;
  9679. }
  9680. tsInAmbientContext(cb) {
  9681. const {
  9682. isAmbientContext: oldIsAmbientContext,
  9683. strict: oldStrict
  9684. } = this.state;
  9685. this.state.isAmbientContext = true;
  9686. this.state.strict = false;
  9687. try {
  9688. return cb();
  9689. } finally {
  9690. this.state.isAmbientContext = oldIsAmbientContext;
  9691. this.state.strict = oldStrict;
  9692. }
  9693. }
  9694. parseClass(node, isStatement, optionalId) {
  9695. const oldInAbstractClass = this.state.inAbstractClass;
  9696. this.state.inAbstractClass = !!node.abstract;
  9697. try {
  9698. return super.parseClass(node, isStatement, optionalId);
  9699. } finally {
  9700. this.state.inAbstractClass = oldInAbstractClass;
  9701. }
  9702. }
  9703. tsParseAbstractDeclaration(node, decorators) {
  9704. if (this.match(80)) {
  9705. node.abstract = true;
  9706. return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false));
  9707. } else if (this.isContextual(129)) {
  9708. if (!this.hasFollowingLineBreak()) {
  9709. node.abstract = true;
  9710. this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, node);
  9711. return this.tsParseInterfaceDeclaration(node);
  9712. }
  9713. } else {
  9714. this.unexpected(null, 80);
  9715. }
  9716. }
  9717. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
  9718. const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  9719. if (method.abstract) {
  9720. const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
  9721. if (hasBody) {
  9722. const {
  9723. key
  9724. } = method;
  9725. this.raise(TSErrors.AbstractMethodHasImplementation, method, {
  9726. methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`
  9727. });
  9728. }
  9729. }
  9730. return method;
  9731. }
  9732. tsParseTypeParameterName() {
  9733. const typeName = this.parseIdentifier();
  9734. return typeName.name;
  9735. }
  9736. shouldParseAsAmbientContext() {
  9737. return !!this.getPluginOption("typescript", "dts");
  9738. }
  9739. parse() {
  9740. if (this.shouldParseAsAmbientContext()) {
  9741. this.state.isAmbientContext = true;
  9742. }
  9743. return super.parse();
  9744. }
  9745. getExpression() {
  9746. if (this.shouldParseAsAmbientContext()) {
  9747. this.state.isAmbientContext = true;
  9748. }
  9749. return super.getExpression();
  9750. }
  9751. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9752. if (!isString && isMaybeTypeOnly) {
  9753. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9754. return this.finishNode(node, "ExportSpecifier");
  9755. }
  9756. node.exportKind = "value";
  9757. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9758. }
  9759. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  9760. if (!importedIsString && isMaybeTypeOnly) {
  9761. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  9762. return this.finishNode(specifier, "ImportSpecifier");
  9763. }
  9764. specifier.importKind = "value";
  9765. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096);
  9766. }
  9767. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  9768. const leftOfAsKey = isImport ? "imported" : "local";
  9769. const rightOfAsKey = isImport ? "local" : "exported";
  9770. let leftOfAs = node[leftOfAsKey];
  9771. let rightOfAs;
  9772. let hasTypeSpecifier = false;
  9773. let canParseAsKeyword = true;
  9774. const loc = leftOfAs.loc.start;
  9775. if (this.isContextual(93)) {
  9776. const firstAs = this.parseIdentifier();
  9777. if (this.isContextual(93)) {
  9778. const secondAs = this.parseIdentifier();
  9779. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9780. hasTypeSpecifier = true;
  9781. leftOfAs = firstAs;
  9782. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9783. canParseAsKeyword = false;
  9784. } else {
  9785. rightOfAs = secondAs;
  9786. canParseAsKeyword = false;
  9787. }
  9788. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9789. canParseAsKeyword = false;
  9790. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9791. } else {
  9792. hasTypeSpecifier = true;
  9793. leftOfAs = firstAs;
  9794. }
  9795. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9796. hasTypeSpecifier = true;
  9797. if (isImport) {
  9798. leftOfAs = this.parseIdentifier(true);
  9799. if (!this.isContextual(93)) {
  9800. this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
  9801. }
  9802. } else {
  9803. leftOfAs = this.parseModuleExportName();
  9804. }
  9805. }
  9806. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  9807. this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc);
  9808. }
  9809. node[leftOfAsKey] = leftOfAs;
  9810. node[rightOfAsKey] = rightOfAs;
  9811. const kindKey = isImport ? "importKind" : "exportKind";
  9812. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  9813. if (canParseAsKeyword && this.eatContextual(93)) {
  9814. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9815. }
  9816. if (!node[rightOfAsKey]) {
  9817. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  9818. }
  9819. if (isImport) {
  9820. this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096);
  9821. }
  9822. }
  9823. };
  9824. function isPossiblyLiteralEnum(expression) {
  9825. if (expression.type !== "MemberExpression") return false;
  9826. const {
  9827. computed,
  9828. property
  9829. } = expression;
  9830. if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
  9831. return false;
  9832. }
  9833. return isUncomputedMemberExpressionChain(expression.object);
  9834. }
  9835. function isValidAmbientConstInitializer(expression, estree) {
  9836. var _expression$extra;
  9837. const {
  9838. type
  9839. } = expression;
  9840. if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) {
  9841. return false;
  9842. }
  9843. if (estree) {
  9844. if (type === "Literal") {
  9845. const {
  9846. value
  9847. } = expression;
  9848. if (typeof value === "string" || typeof value === "boolean") {
  9849. return true;
  9850. }
  9851. }
  9852. } else {
  9853. if (type === "StringLiteral" || type === "BooleanLiteral") {
  9854. return true;
  9855. }
  9856. }
  9857. if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) {
  9858. return true;
  9859. }
  9860. if (type === "TemplateLiteral" && expression.expressions.length === 0) {
  9861. return true;
  9862. }
  9863. if (isPossiblyLiteralEnum(expression)) {
  9864. return true;
  9865. }
  9866. return false;
  9867. }
  9868. function isNumber(expression, estree) {
  9869. if (estree) {
  9870. return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression);
  9871. }
  9872. return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral";
  9873. }
  9874. function isNegativeNumber(expression, estree) {
  9875. if (expression.type === "UnaryExpression") {
  9876. const {
  9877. operator,
  9878. argument
  9879. } = expression;
  9880. if (operator === "-" && isNumber(argument, estree)) {
  9881. return true;
  9882. }
  9883. }
  9884. return false;
  9885. }
  9886. function isUncomputedMemberExpressionChain(expression) {
  9887. if (expression.type === "Identifier") return true;
  9888. if (expression.type !== "MemberExpression" || expression.computed) {
  9889. return false;
  9890. }
  9891. return isUncomputedMemberExpressionChain(expression.object);
  9892. }
  9893. const PlaceholderErrors = ParseErrorEnum`placeholders`({
  9894. ClassNameIsRequired: "A class name is required.",
  9895. UnexpectedSpace: "Unexpected space in placeholder."
  9896. });
  9897. var placeholders = superClass => class PlaceholdersParserMixin extends superClass {
  9898. parsePlaceholder(expectedNode) {
  9899. if (this.match(144)) {
  9900. const node = this.startNode();
  9901. this.next();
  9902. this.assertNoSpace();
  9903. node.name = super.parseIdentifier(true);
  9904. this.assertNoSpace();
  9905. this.expect(144);
  9906. return this.finishPlaceholder(node, expectedNode);
  9907. }
  9908. }
  9909. finishPlaceholder(node, expectedNode) {
  9910. let placeholder = node;
  9911. if (!placeholder.expectedNode || !placeholder.type) {
  9912. placeholder = this.finishNode(placeholder, "Placeholder");
  9913. }
  9914. placeholder.expectedNode = expectedNode;
  9915. return placeholder;
  9916. }
  9917. getTokenFromCode(code) {
  9918. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  9919. this.finishOp(144, 2);
  9920. } else {
  9921. super.getTokenFromCode(code);
  9922. }
  9923. }
  9924. parseExprAtom(refExpressionErrors) {
  9925. return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  9926. }
  9927. parseIdentifier(liberal) {
  9928. return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  9929. }
  9930. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9931. if (word !== undefined) {
  9932. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  9933. }
  9934. }
  9935. parseBindingAtom() {
  9936. return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  9937. }
  9938. isValidLVal(type, isParenthesized, binding) {
  9939. return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding);
  9940. }
  9941. toAssignable(node, isLHS) {
  9942. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  9943. node.expectedNode = "Pattern";
  9944. } else {
  9945. super.toAssignable(node, isLHS);
  9946. }
  9947. }
  9948. chStartsBindingIdentifier(ch, pos) {
  9949. if (super.chStartsBindingIdentifier(ch, pos)) {
  9950. return true;
  9951. }
  9952. const nextToken = this.lookahead();
  9953. if (nextToken.type === 144) {
  9954. return true;
  9955. }
  9956. return false;
  9957. }
  9958. verifyBreakContinue(node, isBreak) {
  9959. if (node.label && node.label.type === "Placeholder") return;
  9960. super.verifyBreakContinue(node, isBreak);
  9961. }
  9962. parseExpressionStatement(node, expr) {
  9963. var _expr$extra;
  9964. if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  9965. return super.parseExpressionStatement(node, expr);
  9966. }
  9967. if (this.match(14)) {
  9968. const stmt = node;
  9969. stmt.label = this.finishPlaceholder(expr, "Identifier");
  9970. this.next();
  9971. stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();
  9972. return this.finishNode(stmt, "LabeledStatement");
  9973. }
  9974. this.semicolon();
  9975. const stmtPlaceholder = node;
  9976. stmtPlaceholder.name = expr.name;
  9977. return this.finishPlaceholder(stmtPlaceholder, "Statement");
  9978. }
  9979. parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
  9980. return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  9981. }
  9982. parseFunctionId(requireId) {
  9983. return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  9984. }
  9985. parseClass(node, isStatement, optionalId) {
  9986. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  9987. this.next();
  9988. const oldStrict = this.state.strict;
  9989. const placeholder = this.parsePlaceholder("Identifier");
  9990. if (placeholder) {
  9991. if (this.match(81) || this.match(144) || this.match(5)) {
  9992. node.id = placeholder;
  9993. } else if (optionalId || !isStatement) {
  9994. node.id = null;
  9995. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  9996. return this.finishNode(node, type);
  9997. } else {
  9998. throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc);
  9999. }
  10000. } else {
  10001. this.parseClassId(node, isStatement, optionalId);
  10002. }
  10003. super.parseClassSuper(node);
  10004. node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict);
  10005. return this.finishNode(node, type);
  10006. }
  10007. parseExport(node, decorators) {
  10008. const placeholder = this.parsePlaceholder("Identifier");
  10009. if (!placeholder) return super.parseExport(node, decorators);
  10010. const node2 = node;
  10011. if (!this.isContextual(98) && !this.match(12)) {
  10012. node2.specifiers = [];
  10013. node2.source = null;
  10014. node2.declaration = this.finishPlaceholder(placeholder, "Declaration");
  10015. return this.finishNode(node2, "ExportNamedDeclaration");
  10016. }
  10017. this.expectPlugin("exportDefaultFrom");
  10018. const specifier = this.startNode();
  10019. specifier.exported = placeholder;
  10020. node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10021. return super.parseExport(node2, decorators);
  10022. }
  10023. isExportDefaultSpecifier() {
  10024. if (this.match(65)) {
  10025. const next = this.nextTokenStart();
  10026. if (this.isUnparsedContextual(next, "from")) {
  10027. if (this.input.startsWith(tokenLabelName(144), this.nextTokenStartSince(next + 4))) {
  10028. return true;
  10029. }
  10030. }
  10031. }
  10032. return super.isExportDefaultSpecifier();
  10033. }
  10034. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  10035. var _specifiers;
  10036. if ((_specifiers = node.specifiers) != null && _specifiers.length) {
  10037. return true;
  10038. }
  10039. return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  10040. }
  10041. checkExport(node) {
  10042. const {
  10043. specifiers
  10044. } = node;
  10045. if (specifiers != null && specifiers.length) {
  10046. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  10047. }
  10048. super.checkExport(node);
  10049. node.specifiers = specifiers;
  10050. }
  10051. parseImport(node) {
  10052. const placeholder = this.parsePlaceholder("Identifier");
  10053. if (!placeholder) return super.parseImport(node);
  10054. node.specifiers = [];
  10055. if (!this.isContextual(98) && !this.match(12)) {
  10056. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  10057. this.semicolon();
  10058. return this.finishNode(node, "ImportDeclaration");
  10059. }
  10060. const specifier = this.startNodeAtNode(placeholder);
  10061. specifier.local = placeholder;
  10062. node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
  10063. if (this.eat(12)) {
  10064. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  10065. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  10066. }
  10067. this.expectContextual(98);
  10068. node.source = this.parseImportSource();
  10069. this.semicolon();
  10070. return this.finishNode(node, "ImportDeclaration");
  10071. }
  10072. parseImportSource() {
  10073. return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  10074. }
  10075. assertNoSpace() {
  10076. if (this.state.start > this.state.lastTokEndLoc.index) {
  10077. this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc);
  10078. }
  10079. }
  10080. };
  10081. var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass {
  10082. parseV8Intrinsic() {
  10083. if (this.match(54)) {
  10084. const v8IntrinsicStartLoc = this.state.startLoc;
  10085. const node = this.startNode();
  10086. this.next();
  10087. if (tokenIsIdentifier(this.state.type)) {
  10088. const name = this.parseIdentifierName();
  10089. const identifier = this.createIdentifier(node, name);
  10090. identifier.type = "V8IntrinsicIdentifier";
  10091. if (this.match(10)) {
  10092. return identifier;
  10093. }
  10094. }
  10095. this.unexpected(v8IntrinsicStartLoc);
  10096. }
  10097. }
  10098. parseExprAtom(refExpressionErrors) {
  10099. return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  10100. }
  10101. };
  10102. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  10103. const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
  10104. function validatePlugins(pluginsMap) {
  10105. if (pluginsMap.has("decorators")) {
  10106. if (pluginsMap.has("decorators-legacy")) {
  10107. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  10108. }
  10109. const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport;
  10110. if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
  10111. throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");
  10112. }
  10113. const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized;
  10114. if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
  10115. throw new Error("'allowCallParenthesized' must be a boolean.");
  10116. }
  10117. }
  10118. if (pluginsMap.has("flow") && pluginsMap.has("typescript")) {
  10119. throw new Error("Cannot combine flow and typescript plugins.");
  10120. }
  10121. if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) {
  10122. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  10123. }
  10124. if (pluginsMap.has("pipelineOperator")) {
  10125. var _pluginsMap$get;
  10126. const proposal = pluginsMap.get("pipelineOperator").proposal;
  10127. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  10128. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  10129. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  10130. }
  10131. const tupleSyntaxIsHash = ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash";
  10132. if (proposal === "hack") {
  10133. if (pluginsMap.has("placeholders")) {
  10134. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  10135. }
  10136. if (pluginsMap.has("v8intrinsic")) {
  10137. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  10138. }
  10139. const topicToken = pluginsMap.get("pipelineOperator").topicToken;
  10140. if (!TOPIC_TOKENS.includes(topicToken)) {
  10141. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  10142. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  10143. }
  10144. if (topicToken === "#" && tupleSyntaxIsHash) {
  10145. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  10146. }
  10147. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  10148. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  10149. }
  10150. }
  10151. if (pluginsMap.has("moduleAttributes")) {
  10152. {
  10153. if (pluginsMap.has("importAttributes") || pluginsMap.has("importAssertions")) {
  10154. throw new Error("Cannot combine importAssertions, importAttributes and moduleAttributes plugins.");
  10155. }
  10156. const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version;
  10157. if (moduleAttributesVersionPluginOption !== "may-2020") {
  10158. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  10159. }
  10160. }
  10161. }
  10162. if (pluginsMap.has("importAttributes") && pluginsMap.has("importAssertions")) {
  10163. throw new Error("Cannot combine importAssertions and importAttributes plugins.");
  10164. }
  10165. if (pluginsMap.has("recordAndTuple")) {
  10166. const syntaxType = pluginsMap.get("recordAndTuple").syntaxType;
  10167. if (syntaxType != null) {
  10168. {
  10169. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  10170. if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) {
  10171. throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  10172. }
  10173. }
  10174. }
  10175. }
  10176. if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) {
  10177. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  10178. error.missingPlugins = "doExpressions";
  10179. throw error;
  10180. }
  10181. if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") {
  10182. throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'.");
  10183. }
  10184. }
  10185. const mixinPlugins = {
  10186. estree,
  10187. jsx,
  10188. flow,
  10189. typescript,
  10190. v8intrinsic,
  10191. placeholders
  10192. };
  10193. const mixinPluginNames = Object.keys(mixinPlugins);
  10194. const defaultOptions = {
  10195. sourceType: "script",
  10196. sourceFilename: undefined,
  10197. startColumn: 0,
  10198. startLine: 1,
  10199. allowAwaitOutsideFunction: false,
  10200. allowReturnOutsideFunction: false,
  10201. allowNewTargetOutsideFunction: false,
  10202. allowImportExportEverywhere: false,
  10203. allowSuperOutsideMethod: false,
  10204. allowUndeclaredExports: false,
  10205. plugins: [],
  10206. strictMode: null,
  10207. ranges: false,
  10208. tokens: false,
  10209. createImportExpressions: false,
  10210. createParenthesizedExpressions: false,
  10211. errorRecovery: false,
  10212. attachComment: true,
  10213. annexB: true
  10214. };
  10215. function getOptions(opts) {
  10216. if (opts == null) {
  10217. return Object.assign({}, defaultOptions);
  10218. }
  10219. if (opts.annexB != null && opts.annexB !== false) {
  10220. throw new Error("The `annexB` option can only be set to `false`.");
  10221. }
  10222. const options = {};
  10223. for (const key of Object.keys(defaultOptions)) {
  10224. var _opts$key;
  10225. options[key] = (_opts$key = opts[key]) != null ? _opts$key : defaultOptions[key];
  10226. }
  10227. return options;
  10228. }
  10229. class ExpressionParser extends LValParser {
  10230. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  10231. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  10232. return;
  10233. }
  10234. const key = prop.key;
  10235. const name = key.type === "Identifier" ? key.name : key.value;
  10236. if (name === "__proto__") {
  10237. if (isRecord) {
  10238. this.raise(Errors.RecordNoProto, key);
  10239. return;
  10240. }
  10241. if (protoRef.used) {
  10242. if (refExpressionErrors) {
  10243. if (refExpressionErrors.doubleProtoLoc === null) {
  10244. refExpressionErrors.doubleProtoLoc = key.loc.start;
  10245. }
  10246. } else {
  10247. this.raise(Errors.DuplicateProto, key);
  10248. }
  10249. }
  10250. protoRef.used = true;
  10251. }
  10252. }
  10253. shouldExitDescending(expr, potentialArrowAt) {
  10254. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  10255. }
  10256. getExpression() {
  10257. this.enterInitialScopes();
  10258. this.nextToken();
  10259. const expr = this.parseExpression();
  10260. if (!this.match(139)) {
  10261. this.unexpected();
  10262. }
  10263. this.finalizeRemainingComments();
  10264. expr.comments = this.comments;
  10265. expr.errors = this.state.errors;
  10266. if (this.options.tokens) {
  10267. expr.tokens = this.tokens;
  10268. }
  10269. return expr;
  10270. }
  10271. parseExpression(disallowIn, refExpressionErrors) {
  10272. if (disallowIn) {
  10273. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10274. }
  10275. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10276. }
  10277. parseExpressionBase(refExpressionErrors) {
  10278. const startLoc = this.state.startLoc;
  10279. const expr = this.parseMaybeAssign(refExpressionErrors);
  10280. if (this.match(12)) {
  10281. const node = this.startNodeAt(startLoc);
  10282. node.expressions = [expr];
  10283. while (this.eat(12)) {
  10284. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10285. }
  10286. this.toReferencedList(node.expressions);
  10287. return this.finishNode(node, "SequenceExpression");
  10288. }
  10289. return expr;
  10290. }
  10291. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10292. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10293. }
  10294. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10295. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10296. }
  10297. setOptionalParametersError(refExpressionErrors, resultError) {
  10298. var _resultError$loc;
  10299. refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc;
  10300. }
  10301. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10302. const startLoc = this.state.startLoc;
  10303. if (this.isContextual(108)) {
  10304. if (this.prodParam.hasYield) {
  10305. let left = this.parseYield();
  10306. if (afterLeftParse) {
  10307. left = afterLeftParse.call(this, left, startLoc);
  10308. }
  10309. return left;
  10310. }
  10311. }
  10312. let ownExpressionErrors;
  10313. if (refExpressionErrors) {
  10314. ownExpressionErrors = false;
  10315. } else {
  10316. refExpressionErrors = new ExpressionErrors();
  10317. ownExpressionErrors = true;
  10318. }
  10319. const {
  10320. type
  10321. } = this.state;
  10322. if (type === 10 || tokenIsIdentifier(type)) {
  10323. this.state.potentialArrowAt = this.state.start;
  10324. }
  10325. let left = this.parseMaybeConditional(refExpressionErrors);
  10326. if (afterLeftParse) {
  10327. left = afterLeftParse.call(this, left, startLoc);
  10328. }
  10329. if (tokenIsAssignment(this.state.type)) {
  10330. const node = this.startNodeAt(startLoc);
  10331. const operator = this.state.value;
  10332. node.operator = operator;
  10333. if (this.match(29)) {
  10334. this.toAssignable(left, true);
  10335. node.left = left;
  10336. const startIndex = startLoc.index;
  10337. if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
  10338. refExpressionErrors.doubleProtoLoc = null;
  10339. }
  10340. if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
  10341. refExpressionErrors.shorthandAssignLoc = null;
  10342. }
  10343. if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
  10344. this.checkDestructuringPrivate(refExpressionErrors);
  10345. refExpressionErrors.privateKeyLoc = null;
  10346. }
  10347. } else {
  10348. node.left = left;
  10349. }
  10350. this.next();
  10351. node.right = this.parseMaybeAssign();
  10352. this.checkLVal(left, this.finishNode(node, "AssignmentExpression"));
  10353. return node;
  10354. } else if (ownExpressionErrors) {
  10355. this.checkExpressionErrors(refExpressionErrors, true);
  10356. }
  10357. return left;
  10358. }
  10359. parseMaybeConditional(refExpressionErrors) {
  10360. const startLoc = this.state.startLoc;
  10361. const potentialArrowAt = this.state.potentialArrowAt;
  10362. const expr = this.parseExprOps(refExpressionErrors);
  10363. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10364. return expr;
  10365. }
  10366. return this.parseConditional(expr, startLoc, refExpressionErrors);
  10367. }
  10368. parseConditional(expr, startLoc, refExpressionErrors) {
  10369. if (this.eat(17)) {
  10370. const node = this.startNodeAt(startLoc);
  10371. node.test = expr;
  10372. node.consequent = this.parseMaybeAssignAllowIn();
  10373. this.expect(14);
  10374. node.alternate = this.parseMaybeAssign();
  10375. return this.finishNode(node, "ConditionalExpression");
  10376. }
  10377. return expr;
  10378. }
  10379. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10380. return this.match(138) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10381. }
  10382. parseExprOps(refExpressionErrors) {
  10383. const startLoc = this.state.startLoc;
  10384. const potentialArrowAt = this.state.potentialArrowAt;
  10385. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10386. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10387. return expr;
  10388. }
  10389. return this.parseExprOp(expr, startLoc, -1);
  10390. }
  10391. parseExprOp(left, leftStartLoc, minPrec) {
  10392. if (this.isPrivateName(left)) {
  10393. const value = this.getPrivateNameSV(left);
  10394. if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
  10395. this.raise(Errors.PrivateInExpectedIn, left, {
  10396. identifierName: value
  10397. });
  10398. }
  10399. this.classScope.usePrivateName(value, left.loc.start);
  10400. }
  10401. const op = this.state.type;
  10402. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
  10403. let prec = tokenOperatorPrecedence(op);
  10404. if (prec > minPrec) {
  10405. if (op === 39) {
  10406. this.expectPlugin("pipelineOperator");
  10407. if (this.state.inFSharpPipelineDirectBody) {
  10408. return left;
  10409. }
  10410. this.checkPipelineAtInfixOperator(left, leftStartLoc);
  10411. }
  10412. const node = this.startNodeAt(leftStartLoc);
  10413. node.left = left;
  10414. node.operator = this.state.value;
  10415. const logical = op === 41 || op === 42;
  10416. const coalesce = op === 40;
  10417. if (coalesce) {
  10418. prec = tokenOperatorPrecedence(42);
  10419. }
  10420. this.next();
  10421. if (op === 39 && this.hasPlugin(["pipelineOperator", {
  10422. proposal: "minimal"
  10423. }])) {
  10424. if (this.state.type === 96 && this.prodParam.hasAwait) {
  10425. throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc);
  10426. }
  10427. }
  10428. node.right = this.parseExprOpRightExpr(op, prec);
  10429. const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10430. const nextOp = this.state.type;
  10431. if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
  10432. throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc);
  10433. }
  10434. return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
  10435. }
  10436. }
  10437. return left;
  10438. }
  10439. parseExprOpRightExpr(op, prec) {
  10440. const startLoc = this.state.startLoc;
  10441. switch (op) {
  10442. case 39:
  10443. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10444. case "hack":
  10445. return this.withTopicBindingContext(() => {
  10446. return this.parseHackPipeBody();
  10447. });
  10448. case "smart":
  10449. return this.withTopicBindingContext(() => {
  10450. if (this.prodParam.hasYield && this.isContextual(108)) {
  10451. throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc);
  10452. }
  10453. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
  10454. });
  10455. case "fsharp":
  10456. return this.withSoloAwaitPermittingContext(() => {
  10457. return this.parseFSharpPipelineBody(prec);
  10458. });
  10459. }
  10460. default:
  10461. return this.parseExprOpBaseRightExpr(op, prec);
  10462. }
  10463. }
  10464. parseExprOpBaseRightExpr(op, prec) {
  10465. const startLoc = this.state.startLoc;
  10466. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10467. }
  10468. parseHackPipeBody() {
  10469. var _body$extra;
  10470. const {
  10471. startLoc
  10472. } = this.state;
  10473. const body = this.parseMaybeAssign();
  10474. const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type);
  10475. if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10476. this.raise(Errors.PipeUnparenthesizedBody, startLoc, {
  10477. type: body.type
  10478. });
  10479. }
  10480. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10481. this.raise(Errors.PipeTopicUnused, startLoc);
  10482. }
  10483. return body;
  10484. }
  10485. checkExponentialAfterUnary(node) {
  10486. if (this.match(57)) {
  10487. this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument);
  10488. }
  10489. }
  10490. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10491. const startLoc = this.state.startLoc;
  10492. const isAwait = this.isContextual(96);
  10493. if (isAwait && this.recordAwaitIfAllowed()) {
  10494. this.next();
  10495. const expr = this.parseAwait(startLoc);
  10496. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10497. return expr;
  10498. }
  10499. const update = this.match(34);
  10500. const node = this.startNode();
  10501. if (tokenIsPrefix(this.state.type)) {
  10502. node.operator = this.state.value;
  10503. node.prefix = true;
  10504. if (this.match(72)) {
  10505. this.expectPlugin("throwExpressions");
  10506. }
  10507. const isDelete = this.match(89);
  10508. this.next();
  10509. node.argument = this.parseMaybeUnary(null, true);
  10510. this.checkExpressionErrors(refExpressionErrors, true);
  10511. if (this.state.strict && isDelete) {
  10512. const arg = node.argument;
  10513. if (arg.type === "Identifier") {
  10514. this.raise(Errors.StrictDelete, node);
  10515. } else if (this.hasPropertyAsPrivateName(arg)) {
  10516. this.raise(Errors.DeletePrivateField, node);
  10517. }
  10518. }
  10519. if (!update) {
  10520. if (!sawUnary) {
  10521. this.checkExponentialAfterUnary(node);
  10522. }
  10523. return this.finishNode(node, "UnaryExpression");
  10524. }
  10525. }
  10526. const expr = this.parseUpdate(node, update, refExpressionErrors);
  10527. if (isAwait) {
  10528. const {
  10529. type
  10530. } = this.state;
  10531. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  10532. if (startsExpr && !this.isAmbiguousAwait()) {
  10533. this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc);
  10534. return this.parseAwait(startLoc);
  10535. }
  10536. }
  10537. return expr;
  10538. }
  10539. parseUpdate(node, update, refExpressionErrors) {
  10540. if (update) {
  10541. const updateExpressionNode = node;
  10542. this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression"));
  10543. return node;
  10544. }
  10545. const startLoc = this.state.startLoc;
  10546. let expr = this.parseExprSubscripts(refExpressionErrors);
  10547. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10548. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10549. const node = this.startNodeAt(startLoc);
  10550. node.operator = this.state.value;
  10551. node.prefix = false;
  10552. node.argument = expr;
  10553. this.next();
  10554. this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression"));
  10555. }
  10556. return expr;
  10557. }
  10558. parseExprSubscripts(refExpressionErrors) {
  10559. const startLoc = this.state.startLoc;
  10560. const potentialArrowAt = this.state.potentialArrowAt;
  10561. const expr = this.parseExprAtom(refExpressionErrors);
  10562. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10563. return expr;
  10564. }
  10565. return this.parseSubscripts(expr, startLoc);
  10566. }
  10567. parseSubscripts(base, startLoc, noCalls) {
  10568. const state = {
  10569. optionalChainMember: false,
  10570. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10571. stop: false
  10572. };
  10573. do {
  10574. base = this.parseSubscript(base, startLoc, noCalls, state);
  10575. state.maybeAsyncArrow = false;
  10576. } while (!state.stop);
  10577. return base;
  10578. }
  10579. parseSubscript(base, startLoc, noCalls, state) {
  10580. const {
  10581. type
  10582. } = this.state;
  10583. if (!noCalls && type === 15) {
  10584. return this.parseBind(base, startLoc, noCalls, state);
  10585. } else if (tokenIsTemplate(type)) {
  10586. return this.parseTaggedTemplateExpression(base, startLoc, state);
  10587. }
  10588. let optional = false;
  10589. if (type === 18) {
  10590. if (noCalls) {
  10591. this.raise(Errors.OptionalChainingNoNew, this.state.startLoc);
  10592. if (this.lookaheadCharCode() === 40) {
  10593. state.stop = true;
  10594. return base;
  10595. }
  10596. }
  10597. state.optionalChainMember = optional = true;
  10598. this.next();
  10599. }
  10600. if (!noCalls && this.match(10)) {
  10601. return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional);
  10602. } else {
  10603. const computed = this.eat(0);
  10604. if (computed || optional || this.eat(16)) {
  10605. return this.parseMember(base, startLoc, state, computed, optional);
  10606. } else {
  10607. state.stop = true;
  10608. return base;
  10609. }
  10610. }
  10611. }
  10612. parseMember(base, startLoc, state, computed, optional) {
  10613. const node = this.startNodeAt(startLoc);
  10614. node.object = base;
  10615. node.computed = computed;
  10616. if (computed) {
  10617. node.property = this.parseExpression();
  10618. this.expect(3);
  10619. } else if (this.match(138)) {
  10620. if (base.type === "Super") {
  10621. this.raise(Errors.SuperPrivateField, startLoc);
  10622. }
  10623. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  10624. node.property = this.parsePrivateName();
  10625. } else {
  10626. node.property = this.parseIdentifier(true);
  10627. }
  10628. if (state.optionalChainMember) {
  10629. node.optional = optional;
  10630. return this.finishNode(node, "OptionalMemberExpression");
  10631. } else {
  10632. return this.finishNode(node, "MemberExpression");
  10633. }
  10634. }
  10635. parseBind(base, startLoc, noCalls, state) {
  10636. const node = this.startNodeAt(startLoc);
  10637. node.object = base;
  10638. this.next();
  10639. node.callee = this.parseNoCallExpr();
  10640. state.stop = true;
  10641. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls);
  10642. }
  10643. parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) {
  10644. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10645. let refExpressionErrors = null;
  10646. this.state.maybeInArrowParameters = true;
  10647. this.next();
  10648. const node = this.startNodeAt(startLoc);
  10649. node.callee = base;
  10650. const {
  10651. maybeAsyncArrow,
  10652. optionalChainMember
  10653. } = state;
  10654. if (maybeAsyncArrow) {
  10655. this.expressionScope.enter(newAsyncArrowScope());
  10656. refExpressionErrors = new ExpressionErrors();
  10657. }
  10658. if (optionalChainMember) {
  10659. node.optional = optional;
  10660. }
  10661. if (optional) {
  10662. node.arguments = this.parseCallExpressionArguments(11);
  10663. } else {
  10664. node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors);
  10665. }
  10666. let finishedNode = this.finishCallExpression(node, optionalChainMember);
  10667. if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10668. state.stop = true;
  10669. this.checkDestructuringPrivate(refExpressionErrors);
  10670. this.expressionScope.validateAsPattern();
  10671. this.expressionScope.exit();
  10672. finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
  10673. } else {
  10674. if (maybeAsyncArrow) {
  10675. this.checkExpressionErrors(refExpressionErrors, true);
  10676. this.expressionScope.exit();
  10677. }
  10678. this.toReferencedArguments(finishedNode);
  10679. }
  10680. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10681. return finishedNode;
  10682. }
  10683. toReferencedArguments(node, isParenthesizedExpr) {
  10684. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10685. }
  10686. parseTaggedTemplateExpression(base, startLoc, state) {
  10687. const node = this.startNodeAt(startLoc);
  10688. node.tag = base;
  10689. node.quasi = this.parseTemplate(true);
  10690. if (state.optionalChainMember) {
  10691. this.raise(Errors.OptionalChainingNoTemplate, startLoc);
  10692. }
  10693. return this.finishNode(node, "TaggedTemplateExpression");
  10694. }
  10695. atPossibleAsyncArrow(base) {
  10696. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  10697. }
  10698. expectImportAttributesPlugin() {
  10699. if (!this.hasPlugin("importAssertions")) {
  10700. this.expectPlugin("importAttributes");
  10701. }
  10702. }
  10703. finishCallExpression(node, optional) {
  10704. if (node.callee.type === "Import") {
  10705. if (node.arguments.length === 2) {
  10706. {
  10707. if (!this.hasPlugin("moduleAttributes")) {
  10708. this.expectImportAttributesPlugin();
  10709. }
  10710. }
  10711. }
  10712. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10713. this.raise(Errors.ImportCallArity, node, {
  10714. maxArgumentCount: this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? 2 : 1
  10715. });
  10716. } else {
  10717. for (const arg of node.arguments) {
  10718. if (arg.type === "SpreadElement") {
  10719. this.raise(Errors.ImportCallSpreadArgument, arg);
  10720. }
  10721. }
  10722. }
  10723. }
  10724. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10725. }
  10726. parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10727. const elts = [];
  10728. let first = true;
  10729. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10730. this.state.inFSharpPipelineDirectBody = false;
  10731. while (!this.eat(close)) {
  10732. if (first) {
  10733. first = false;
  10734. } else {
  10735. this.expect(12);
  10736. if (this.match(close)) {
  10737. if (dynamicImport && !this.hasPlugin("importAttributes") && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  10738. this.raise(Errors.ImportCallArgumentTrailingComma, this.state.lastTokStartLoc);
  10739. }
  10740. if (nodeForExtra) {
  10741. this.addTrailingCommaExtraToNode(nodeForExtra);
  10742. }
  10743. this.next();
  10744. break;
  10745. }
  10746. }
  10747. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  10748. }
  10749. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10750. return elts;
  10751. }
  10752. shouldParseAsyncArrow() {
  10753. return this.match(19) && !this.canInsertSemicolon();
  10754. }
  10755. parseAsyncArrowFromCallExpression(node, call) {
  10756. var _call$extra;
  10757. this.resetPreviousNodeTrailingComments(call);
  10758. this.expect(19);
  10759. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
  10760. if (call.innerComments) {
  10761. setInnerComments(node, call.innerComments);
  10762. }
  10763. if (call.callee.trailingComments) {
  10764. setInnerComments(node, call.callee.trailingComments);
  10765. }
  10766. return node;
  10767. }
  10768. parseNoCallExpr() {
  10769. const startLoc = this.state.startLoc;
  10770. return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  10771. }
  10772. parseExprAtom(refExpressionErrors) {
  10773. let node;
  10774. let decorators = null;
  10775. const {
  10776. type
  10777. } = this.state;
  10778. switch (type) {
  10779. case 79:
  10780. return this.parseSuper();
  10781. case 83:
  10782. node = this.startNode();
  10783. this.next();
  10784. if (this.match(16)) {
  10785. return this.parseImportMetaProperty(node);
  10786. }
  10787. if (this.match(10)) {
  10788. if (this.options.createImportExpressions) {
  10789. return this.parseImportCall(node);
  10790. } else {
  10791. return this.finishNode(node, "Import");
  10792. }
  10793. } else {
  10794. this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc);
  10795. return this.finishNode(node, "Import");
  10796. }
  10797. case 78:
  10798. node = this.startNode();
  10799. this.next();
  10800. return this.finishNode(node, "ThisExpression");
  10801. case 90:
  10802. {
  10803. return this.parseDo(this.startNode(), false);
  10804. }
  10805. case 56:
  10806. case 31:
  10807. {
  10808. this.readRegexp();
  10809. return this.parseRegExpLiteral(this.state.value);
  10810. }
  10811. case 134:
  10812. return this.parseNumericLiteral(this.state.value);
  10813. case 135:
  10814. return this.parseBigIntLiteral(this.state.value);
  10815. case 136:
  10816. return this.parseDecimalLiteral(this.state.value);
  10817. case 133:
  10818. return this.parseStringLiteral(this.state.value);
  10819. case 84:
  10820. return this.parseNullLiteral();
  10821. case 85:
  10822. return this.parseBooleanLiteral(true);
  10823. case 86:
  10824. return this.parseBooleanLiteral(false);
  10825. case 10:
  10826. {
  10827. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10828. return this.parseParenAndDistinguishExpression(canBeArrow);
  10829. }
  10830. case 2:
  10831. case 1:
  10832. {
  10833. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  10834. }
  10835. case 0:
  10836. {
  10837. return this.parseArrayLike(3, true, false, refExpressionErrors);
  10838. }
  10839. case 6:
  10840. case 7:
  10841. {
  10842. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  10843. }
  10844. case 5:
  10845. {
  10846. return this.parseObjectLike(8, false, false, refExpressionErrors);
  10847. }
  10848. case 68:
  10849. return this.parseFunctionOrFunctionSent();
  10850. case 26:
  10851. decorators = this.parseDecorators();
  10852. case 80:
  10853. return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
  10854. case 77:
  10855. return this.parseNewOrNewTarget();
  10856. case 25:
  10857. case 24:
  10858. return this.parseTemplate(false);
  10859. case 15:
  10860. {
  10861. node = this.startNode();
  10862. this.next();
  10863. node.object = null;
  10864. const callee = node.callee = this.parseNoCallExpr();
  10865. if (callee.type === "MemberExpression") {
  10866. return this.finishNode(node, "BindExpression");
  10867. } else {
  10868. throw this.raise(Errors.UnsupportedBind, callee);
  10869. }
  10870. }
  10871. case 138:
  10872. {
  10873. this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, {
  10874. identifierName: this.state.value
  10875. });
  10876. return this.parsePrivateName();
  10877. }
  10878. case 33:
  10879. {
  10880. return this.parseTopicReferenceThenEqualsSign(54, "%");
  10881. }
  10882. case 32:
  10883. {
  10884. return this.parseTopicReferenceThenEqualsSign(44, "^");
  10885. }
  10886. case 37:
  10887. case 38:
  10888. {
  10889. return this.parseTopicReference("hack");
  10890. }
  10891. case 44:
  10892. case 54:
  10893. case 27:
  10894. {
  10895. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10896. if (pipeProposal) {
  10897. return this.parseTopicReference(pipeProposal);
  10898. }
  10899. this.unexpected();
  10900. break;
  10901. }
  10902. case 47:
  10903. {
  10904. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  10905. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  10906. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  10907. } else {
  10908. this.unexpected();
  10909. }
  10910. break;
  10911. }
  10912. default:
  10913. if (tokenIsIdentifier(type)) {
  10914. if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) {
  10915. return this.parseModuleExpression();
  10916. }
  10917. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10918. const containsEsc = this.state.containsEsc;
  10919. const id = this.parseIdentifier();
  10920. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  10921. const {
  10922. type
  10923. } = this.state;
  10924. if (type === 68) {
  10925. this.resetPreviousNodeTrailingComments(id);
  10926. this.next();
  10927. return this.parseAsyncFunctionExpression(this.startNodeAtNode(id));
  10928. } else if (tokenIsIdentifier(type)) {
  10929. if (this.lookaheadCharCode() === 61) {
  10930. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  10931. } else {
  10932. return id;
  10933. }
  10934. } else if (type === 90) {
  10935. this.resetPreviousNodeTrailingComments(id);
  10936. return this.parseDo(this.startNodeAtNode(id), true);
  10937. }
  10938. }
  10939. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  10940. this.next();
  10941. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  10942. }
  10943. return id;
  10944. } else {
  10945. this.unexpected();
  10946. }
  10947. }
  10948. }
  10949. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  10950. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10951. if (pipeProposal) {
  10952. this.state.type = topicTokenType;
  10953. this.state.value = topicTokenValue;
  10954. this.state.pos--;
  10955. this.state.end--;
  10956. this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
  10957. return this.parseTopicReference(pipeProposal);
  10958. } else {
  10959. this.unexpected();
  10960. }
  10961. }
  10962. parseTopicReference(pipeProposal) {
  10963. const node = this.startNode();
  10964. const startLoc = this.state.startLoc;
  10965. const tokenType = this.state.type;
  10966. this.next();
  10967. return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);
  10968. }
  10969. finishTopicReference(node, startLoc, pipeProposal, tokenType) {
  10970. if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
  10971. const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" : "TopicReference";
  10972. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  10973. this.raise(pipeProposal === "smart" ? Errors.PrimaryTopicNotAllowed : Errors.PipeTopicUnbound, startLoc);
  10974. }
  10975. this.registerTopicReference();
  10976. return this.finishNode(node, nodeType);
  10977. } else {
  10978. throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, {
  10979. token: tokenLabelName(tokenType)
  10980. });
  10981. }
  10982. }
  10983. testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
  10984. switch (pipeProposal) {
  10985. case "hack":
  10986. {
  10987. return this.hasPlugin(["pipelineOperator", {
  10988. topicToken: tokenLabelName(tokenType)
  10989. }]);
  10990. }
  10991. case "smart":
  10992. return tokenType === 27;
  10993. default:
  10994. throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc);
  10995. }
  10996. }
  10997. parseAsyncArrowUnaryFunction(node) {
  10998. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  10999. const params = [this.parseIdentifier()];
  11000. this.prodParam.exit();
  11001. if (this.hasPrecedingLineBreak()) {
  11002. this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition());
  11003. }
  11004. this.expect(19);
  11005. return this.parseArrowExpression(node, params, true);
  11006. }
  11007. parseDo(node, isAsync) {
  11008. this.expectPlugin("doExpressions");
  11009. if (isAsync) {
  11010. this.expectPlugin("asyncDoExpressions");
  11011. }
  11012. node.async = isAsync;
  11013. this.next();
  11014. const oldLabels = this.state.labels;
  11015. this.state.labels = [];
  11016. if (isAsync) {
  11017. this.prodParam.enter(2);
  11018. node.body = this.parseBlock();
  11019. this.prodParam.exit();
  11020. } else {
  11021. node.body = this.parseBlock();
  11022. }
  11023. this.state.labels = oldLabels;
  11024. return this.finishNode(node, "DoExpression");
  11025. }
  11026. parseSuper() {
  11027. const node = this.startNode();
  11028. this.next();
  11029. if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  11030. this.raise(Errors.SuperNotAllowed, node);
  11031. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  11032. this.raise(Errors.UnexpectedSuper, node);
  11033. }
  11034. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  11035. this.raise(Errors.UnsupportedSuper, node);
  11036. }
  11037. return this.finishNode(node, "Super");
  11038. }
  11039. parsePrivateName() {
  11040. const node = this.startNode();
  11041. const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1));
  11042. const name = this.state.value;
  11043. this.next();
  11044. node.id = this.createIdentifier(id, name);
  11045. return this.finishNode(node, "PrivateName");
  11046. }
  11047. parseFunctionOrFunctionSent() {
  11048. const node = this.startNode();
  11049. this.next();
  11050. if (this.prodParam.hasYield && this.match(16)) {
  11051. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  11052. this.next();
  11053. if (this.match(103)) {
  11054. this.expectPlugin("functionSent");
  11055. } else if (!this.hasPlugin("functionSent")) {
  11056. this.unexpected();
  11057. }
  11058. return this.parseMetaProperty(node, meta, "sent");
  11059. }
  11060. return this.parseFunction(node);
  11061. }
  11062. parseMetaProperty(node, meta, propertyName) {
  11063. node.meta = meta;
  11064. const containsEsc = this.state.containsEsc;
  11065. node.property = this.parseIdentifier(true);
  11066. if (node.property.name !== propertyName || containsEsc) {
  11067. this.raise(Errors.UnsupportedMetaProperty, node.property, {
  11068. target: meta.name,
  11069. onlyValidPropertyName: propertyName
  11070. });
  11071. }
  11072. return this.finishNode(node, "MetaProperty");
  11073. }
  11074. parseImportMetaProperty(node) {
  11075. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  11076. this.next();
  11077. if (this.isContextual(101)) {
  11078. if (!this.inModule) {
  11079. this.raise(Errors.ImportMetaOutsideModule, id);
  11080. }
  11081. this.sawUnambiguousESM = true;
  11082. } else if (this.isContextual(105) || this.isContextual(97)) {
  11083. const isSource = this.isContextual(105);
  11084. if (!isSource) this.unexpected();
  11085. this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation");
  11086. if (!this.options.createImportExpressions) {
  11087. throw this.raise(Errors.DynamicImportPhaseRequiresImportExpressions, this.state.startLoc, {
  11088. phase: this.state.value
  11089. });
  11090. }
  11091. this.next();
  11092. node.phase = isSource ? "source" : "defer";
  11093. return this.parseImportCall(node);
  11094. }
  11095. return this.parseMetaProperty(node, id, "meta");
  11096. }
  11097. parseLiteralAtNode(value, type, node) {
  11098. this.addExtra(node, "rawValue", value);
  11099. this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
  11100. node.value = value;
  11101. this.next();
  11102. return this.finishNode(node, type);
  11103. }
  11104. parseLiteral(value, type) {
  11105. const node = this.startNode();
  11106. return this.parseLiteralAtNode(value, type, node);
  11107. }
  11108. parseStringLiteral(value) {
  11109. return this.parseLiteral(value, "StringLiteral");
  11110. }
  11111. parseNumericLiteral(value) {
  11112. return this.parseLiteral(value, "NumericLiteral");
  11113. }
  11114. parseBigIntLiteral(value) {
  11115. return this.parseLiteral(value, "BigIntLiteral");
  11116. }
  11117. parseDecimalLiteral(value) {
  11118. return this.parseLiteral(value, "DecimalLiteral");
  11119. }
  11120. parseRegExpLiteral(value) {
  11121. const node = this.startNode();
  11122. this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
  11123. node.pattern = value.pattern;
  11124. node.flags = value.flags;
  11125. this.next();
  11126. return this.finishNode(node, "RegExpLiteral");
  11127. }
  11128. parseBooleanLiteral(value) {
  11129. const node = this.startNode();
  11130. node.value = value;
  11131. this.next();
  11132. return this.finishNode(node, "BooleanLiteral");
  11133. }
  11134. parseNullLiteral() {
  11135. const node = this.startNode();
  11136. this.next();
  11137. return this.finishNode(node, "NullLiteral");
  11138. }
  11139. parseParenAndDistinguishExpression(canBeArrow) {
  11140. const startLoc = this.state.startLoc;
  11141. let val;
  11142. this.next();
  11143. this.expressionScope.enter(newArrowHeadScope());
  11144. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11145. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11146. this.state.maybeInArrowParameters = true;
  11147. this.state.inFSharpPipelineDirectBody = false;
  11148. const innerStartLoc = this.state.startLoc;
  11149. const exprList = [];
  11150. const refExpressionErrors = new ExpressionErrors();
  11151. let first = true;
  11152. let spreadStartLoc;
  11153. let optionalCommaStartLoc;
  11154. while (!this.match(11)) {
  11155. if (first) {
  11156. first = false;
  11157. } else {
  11158. this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
  11159. if (this.match(11)) {
  11160. optionalCommaStartLoc = this.state.startLoc;
  11161. break;
  11162. }
  11163. }
  11164. if (this.match(21)) {
  11165. const spreadNodeStartLoc = this.state.startLoc;
  11166. spreadStartLoc = this.state.startLoc;
  11167. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
  11168. if (!this.checkCommaAfterRest(41)) {
  11169. break;
  11170. }
  11171. } else {
  11172. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  11173. }
  11174. }
  11175. const innerEndLoc = this.state.lastTokEndLoc;
  11176. this.expect(11);
  11177. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11178. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11179. let arrowNode = this.startNodeAt(startLoc);
  11180. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  11181. this.checkDestructuringPrivate(refExpressionErrors);
  11182. this.expressionScope.validateAsPattern();
  11183. this.expressionScope.exit();
  11184. this.parseArrowExpression(arrowNode, exprList, false);
  11185. return arrowNode;
  11186. }
  11187. this.expressionScope.exit();
  11188. if (!exprList.length) {
  11189. this.unexpected(this.state.lastTokStartLoc);
  11190. }
  11191. if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);
  11192. if (spreadStartLoc) this.unexpected(spreadStartLoc);
  11193. this.checkExpressionErrors(refExpressionErrors, true);
  11194. this.toReferencedListDeep(exprList, true);
  11195. if (exprList.length > 1) {
  11196. val = this.startNodeAt(innerStartLoc);
  11197. val.expressions = exprList;
  11198. this.finishNode(val, "SequenceExpression");
  11199. this.resetEndLocation(val, innerEndLoc);
  11200. } else {
  11201. val = exprList[0];
  11202. }
  11203. return this.wrapParenthesis(startLoc, val);
  11204. }
  11205. wrapParenthesis(startLoc, expression) {
  11206. if (!this.options.createParenthesizedExpressions) {
  11207. this.addExtra(expression, "parenthesized", true);
  11208. this.addExtra(expression, "parenStart", startLoc.index);
  11209. this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
  11210. return expression;
  11211. }
  11212. const parenExpression = this.startNodeAt(startLoc);
  11213. parenExpression.expression = expression;
  11214. return this.finishNode(parenExpression, "ParenthesizedExpression");
  11215. }
  11216. shouldParseArrow(params) {
  11217. return !this.canInsertSemicolon();
  11218. }
  11219. parseArrow(node) {
  11220. if (this.eat(19)) {
  11221. return node;
  11222. }
  11223. }
  11224. parseParenItem(node, startLoc) {
  11225. return node;
  11226. }
  11227. parseNewOrNewTarget() {
  11228. const node = this.startNode();
  11229. this.next();
  11230. if (this.match(16)) {
  11231. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  11232. this.next();
  11233. const metaProp = this.parseMetaProperty(node, meta, "target");
  11234. if (!this.scope.inNonArrowFunction && !this.scope.inClass && !this.options.allowNewTargetOutsideFunction) {
  11235. this.raise(Errors.UnexpectedNewTarget, metaProp);
  11236. }
  11237. return metaProp;
  11238. }
  11239. return this.parseNew(node);
  11240. }
  11241. parseNew(node) {
  11242. this.parseNewCallee(node);
  11243. if (this.eat(10)) {
  11244. const args = this.parseExprList(11);
  11245. this.toReferencedList(args);
  11246. node.arguments = args;
  11247. } else {
  11248. node.arguments = [];
  11249. }
  11250. return this.finishNode(node, "NewExpression");
  11251. }
  11252. parseNewCallee(node) {
  11253. const isImport = this.match(83);
  11254. const callee = this.parseNoCallExpr();
  11255. node.callee = callee;
  11256. if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) {
  11257. this.raise(Errors.ImportCallNotNewExpression, callee);
  11258. }
  11259. }
  11260. parseTemplateElement(isTagged) {
  11261. const {
  11262. start,
  11263. startLoc,
  11264. end,
  11265. value
  11266. } = this.state;
  11267. const elemStart = start + 1;
  11268. const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
  11269. if (value === null) {
  11270. if (!isTagged) {
  11271. this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1));
  11272. }
  11273. }
  11274. const isTail = this.match(24);
  11275. const endOffset = isTail ? -1 : -2;
  11276. const elemEnd = end + endOffset;
  11277. elem.value = {
  11278. raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
  11279. cooked: value === null ? null : value.slice(1, endOffset)
  11280. };
  11281. elem.tail = isTail;
  11282. this.next();
  11283. const finishedNode = this.finishNode(elem, "TemplateElement");
  11284. this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
  11285. return finishedNode;
  11286. }
  11287. parseTemplate(isTagged) {
  11288. const node = this.startNode();
  11289. let curElt = this.parseTemplateElement(isTagged);
  11290. const quasis = [curElt];
  11291. const substitutions = [];
  11292. while (!curElt.tail) {
  11293. substitutions.push(this.parseTemplateSubstitution());
  11294. this.readTemplateContinuation();
  11295. quasis.push(curElt = this.parseTemplateElement(isTagged));
  11296. }
  11297. node.expressions = substitutions;
  11298. node.quasis = quasis;
  11299. return this.finishNode(node, "TemplateLiteral");
  11300. }
  11301. parseTemplateSubstitution() {
  11302. return this.parseExpression();
  11303. }
  11304. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11305. if (isRecord) {
  11306. this.expectPlugin("recordAndTuple");
  11307. }
  11308. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11309. this.state.inFSharpPipelineDirectBody = false;
  11310. const propHash = Object.create(null);
  11311. let first = true;
  11312. const node = this.startNode();
  11313. node.properties = [];
  11314. this.next();
  11315. while (!this.match(close)) {
  11316. if (first) {
  11317. first = false;
  11318. } else {
  11319. this.expect(12);
  11320. if (this.match(close)) {
  11321. this.addTrailingCommaExtraToNode(node);
  11322. break;
  11323. }
  11324. }
  11325. let prop;
  11326. if (isPattern) {
  11327. prop = this.parseBindingProperty();
  11328. } else {
  11329. prop = this.parsePropertyDefinition(refExpressionErrors);
  11330. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  11331. }
  11332. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11333. this.raise(Errors.InvalidRecordProperty, prop);
  11334. }
  11335. {
  11336. if (prop.shorthand) {
  11337. this.addExtra(prop, "shorthand", true);
  11338. }
  11339. }
  11340. node.properties.push(prop);
  11341. }
  11342. this.next();
  11343. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11344. let type = "ObjectExpression";
  11345. if (isPattern) {
  11346. type = "ObjectPattern";
  11347. } else if (isRecord) {
  11348. type = "RecordExpression";
  11349. }
  11350. return this.finishNode(node, type);
  11351. }
  11352. addTrailingCommaExtraToNode(node) {
  11353. this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index);
  11354. this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  11355. }
  11356. maybeAsyncOrAccessorProp(prop) {
  11357. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  11358. }
  11359. parsePropertyDefinition(refExpressionErrors) {
  11360. let decorators = [];
  11361. if (this.match(26)) {
  11362. if (this.hasPlugin("decorators")) {
  11363. this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc);
  11364. }
  11365. while (this.match(26)) {
  11366. decorators.push(this.parseDecorator());
  11367. }
  11368. }
  11369. const prop = this.startNode();
  11370. let isAsync = false;
  11371. let isAccessor = false;
  11372. let startLoc;
  11373. if (this.match(21)) {
  11374. if (decorators.length) this.unexpected();
  11375. return this.parseSpread();
  11376. }
  11377. if (decorators.length) {
  11378. prop.decorators = decorators;
  11379. decorators = [];
  11380. }
  11381. prop.method = false;
  11382. if (refExpressionErrors) {
  11383. startLoc = this.state.startLoc;
  11384. }
  11385. let isGenerator = this.eat(55);
  11386. this.parsePropertyNamePrefixOperator(prop);
  11387. const containsEsc = this.state.containsEsc;
  11388. this.parsePropertyName(prop, refExpressionErrors);
  11389. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11390. const {
  11391. key
  11392. } = prop;
  11393. const keyName = key.name;
  11394. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11395. isAsync = true;
  11396. this.resetPreviousNodeTrailingComments(key);
  11397. isGenerator = this.eat(55);
  11398. this.parsePropertyName(prop);
  11399. }
  11400. if (keyName === "get" || keyName === "set") {
  11401. isAccessor = true;
  11402. this.resetPreviousNodeTrailingComments(key);
  11403. prop.kind = keyName;
  11404. if (this.match(55)) {
  11405. isGenerator = true;
  11406. this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), {
  11407. kind: keyName
  11408. });
  11409. this.next();
  11410. }
  11411. this.parsePropertyName(prop);
  11412. }
  11413. }
  11414. return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11415. }
  11416. getGetterSetterExpectedParamCount(method) {
  11417. return method.kind === "get" ? 0 : 1;
  11418. }
  11419. getObjectOrClassMethodParams(method) {
  11420. return method.params;
  11421. }
  11422. checkGetterSetterParams(method) {
  11423. var _params;
  11424. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11425. const params = this.getObjectOrClassMethodParams(method);
  11426. if (params.length !== paramCount) {
  11427. this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method);
  11428. }
  11429. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11430. this.raise(Errors.BadSetterRestParameter, method);
  11431. }
  11432. }
  11433. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11434. if (isAccessor) {
  11435. const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  11436. this.checkGetterSetterParams(finishedProp);
  11437. return finishedProp;
  11438. }
  11439. if (isAsync || isGenerator || this.match(10)) {
  11440. if (isPattern) this.unexpected();
  11441. prop.kind = "method";
  11442. prop.method = true;
  11443. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11444. }
  11445. }
  11446. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  11447. prop.shorthand = false;
  11448. if (this.eat(14)) {
  11449. prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11450. return this.finishNode(prop, "ObjectProperty");
  11451. }
  11452. if (!prop.computed && prop.key.type === "Identifier") {
  11453. this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
  11454. if (isPattern) {
  11455. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11456. } else if (this.match(29)) {
  11457. const shorthandAssignLoc = this.state.startLoc;
  11458. if (refExpressionErrors != null) {
  11459. if (refExpressionErrors.shorthandAssignLoc === null) {
  11460. refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
  11461. }
  11462. } else {
  11463. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  11464. }
  11465. prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
  11466. } else {
  11467. prop.value = cloneIdentifier(prop.key);
  11468. }
  11469. prop.shorthand = true;
  11470. return this.finishNode(prop, "ObjectProperty");
  11471. }
  11472. }
  11473. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11474. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  11475. if (!node) this.unexpected();
  11476. return node;
  11477. }
  11478. parsePropertyName(prop, refExpressionErrors) {
  11479. if (this.eat(0)) {
  11480. prop.computed = true;
  11481. prop.key = this.parseMaybeAssignAllowIn();
  11482. this.expect(3);
  11483. } else {
  11484. const {
  11485. type,
  11486. value
  11487. } = this.state;
  11488. let key;
  11489. if (tokenIsKeywordOrIdentifier(type)) {
  11490. key = this.parseIdentifier(true);
  11491. } else {
  11492. switch (type) {
  11493. case 134:
  11494. key = this.parseNumericLiteral(value);
  11495. break;
  11496. case 133:
  11497. key = this.parseStringLiteral(value);
  11498. break;
  11499. case 135:
  11500. key = this.parseBigIntLiteral(value);
  11501. break;
  11502. case 136:
  11503. key = this.parseDecimalLiteral(value);
  11504. break;
  11505. case 138:
  11506. {
  11507. const privateKeyLoc = this.state.startLoc;
  11508. if (refExpressionErrors != null) {
  11509. if (refExpressionErrors.privateKeyLoc === null) {
  11510. refExpressionErrors.privateKeyLoc = privateKeyLoc;
  11511. }
  11512. } else {
  11513. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  11514. }
  11515. key = this.parsePrivateName();
  11516. break;
  11517. }
  11518. default:
  11519. this.unexpected();
  11520. }
  11521. }
  11522. prop.key = key;
  11523. if (type !== 138) {
  11524. prop.computed = false;
  11525. }
  11526. }
  11527. }
  11528. initFunction(node, isAsync) {
  11529. node.id = null;
  11530. node.generator = false;
  11531. node.async = isAsync;
  11532. }
  11533. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11534. this.initFunction(node, isAsync);
  11535. node.generator = isGenerator;
  11536. this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0));
  11537. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11538. this.parseFunctionParams(node, isConstructor);
  11539. const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
  11540. this.prodParam.exit();
  11541. this.scope.exit();
  11542. return finishedNode;
  11543. }
  11544. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11545. if (isTuple) {
  11546. this.expectPlugin("recordAndTuple");
  11547. }
  11548. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11549. this.state.inFSharpPipelineDirectBody = false;
  11550. const node = this.startNode();
  11551. this.next();
  11552. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  11553. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11554. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11555. }
  11556. parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
  11557. this.scope.enter(2 | 4);
  11558. let flags = functionFlags(isAsync, false);
  11559. if (!this.match(5) && this.prodParam.hasIn) {
  11560. flags |= 8;
  11561. }
  11562. this.prodParam.enter(flags);
  11563. this.initFunction(node, isAsync);
  11564. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11565. if (params) {
  11566. this.state.maybeInArrowParameters = true;
  11567. this.setArrowFunctionParameters(node, params, trailingCommaLoc);
  11568. }
  11569. this.state.maybeInArrowParameters = false;
  11570. this.parseFunctionBody(node, true);
  11571. this.prodParam.exit();
  11572. this.scope.exit();
  11573. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11574. return this.finishNode(node, "ArrowFunctionExpression");
  11575. }
  11576. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  11577. this.toAssignableList(params, trailingCommaLoc, false);
  11578. node.params = params;
  11579. }
  11580. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11581. this.parseFunctionBody(node, false, isMethod);
  11582. return this.finishNode(node, type);
  11583. }
  11584. parseFunctionBody(node, allowExpression, isMethod = false) {
  11585. const isExpression = allowExpression && !this.match(5);
  11586. this.expressionScope.enter(newExpressionScope());
  11587. if (isExpression) {
  11588. node.body = this.parseMaybeAssign();
  11589. this.checkParams(node, false, allowExpression, false);
  11590. } else {
  11591. const oldStrict = this.state.strict;
  11592. const oldLabels = this.state.labels;
  11593. this.state.labels = [];
  11594. this.prodParam.enter(this.prodParam.currentFlags() | 4);
  11595. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  11596. const nonSimple = !this.isSimpleParamList(node.params);
  11597. if (hasStrictModeDirective && nonSimple) {
  11598. this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node);
  11599. }
  11600. const strictModeChanged = !oldStrict && this.state.strict;
  11601. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11602. if (this.state.strict && node.id) {
  11603. this.checkIdentifier(node.id, 65, strictModeChanged);
  11604. }
  11605. });
  11606. this.prodParam.exit();
  11607. this.state.labels = oldLabels;
  11608. }
  11609. this.expressionScope.exit();
  11610. }
  11611. isSimpleParameter(node) {
  11612. return node.type === "Identifier";
  11613. }
  11614. isSimpleParamList(params) {
  11615. for (let i = 0, len = params.length; i < len; i++) {
  11616. if (!this.isSimpleParameter(params[i])) return false;
  11617. }
  11618. return true;
  11619. }
  11620. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  11621. const checkClashes = !allowDuplicates && new Set();
  11622. const formalParameters = {
  11623. type: "FormalParameters"
  11624. };
  11625. for (const param of node.params) {
  11626. this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged);
  11627. }
  11628. }
  11629. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11630. const elts = [];
  11631. let first = true;
  11632. while (!this.eat(close)) {
  11633. if (first) {
  11634. first = false;
  11635. } else {
  11636. this.expect(12);
  11637. if (this.match(close)) {
  11638. if (nodeForExtra) {
  11639. this.addTrailingCommaExtraToNode(nodeForExtra);
  11640. }
  11641. this.next();
  11642. break;
  11643. }
  11644. }
  11645. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11646. }
  11647. return elts;
  11648. }
  11649. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11650. let elt;
  11651. if (this.match(12)) {
  11652. if (!allowEmpty) {
  11653. this.raise(Errors.UnexpectedToken, this.state.curPosition(), {
  11654. unexpected: ","
  11655. });
  11656. }
  11657. elt = null;
  11658. } else if (this.match(21)) {
  11659. const spreadNodeStartLoc = this.state.startLoc;
  11660. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
  11661. } else if (this.match(17)) {
  11662. this.expectPlugin("partialApplication");
  11663. if (!allowPlaceholder) {
  11664. this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc);
  11665. }
  11666. const node = this.startNode();
  11667. this.next();
  11668. elt = this.finishNode(node, "ArgumentPlaceholder");
  11669. } else {
  11670. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11671. }
  11672. return elt;
  11673. }
  11674. parseIdentifier(liberal) {
  11675. const node = this.startNode();
  11676. const name = this.parseIdentifierName(liberal);
  11677. return this.createIdentifier(node, name);
  11678. }
  11679. createIdentifier(node, name) {
  11680. node.name = name;
  11681. node.loc.identifierName = name;
  11682. return this.finishNode(node, "Identifier");
  11683. }
  11684. parseIdentifierName(liberal) {
  11685. let name;
  11686. const {
  11687. startLoc,
  11688. type
  11689. } = this.state;
  11690. if (tokenIsKeywordOrIdentifier(type)) {
  11691. name = this.state.value;
  11692. } else {
  11693. this.unexpected();
  11694. }
  11695. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  11696. if (liberal) {
  11697. if (tokenIsKeyword) {
  11698. this.replaceToken(132);
  11699. }
  11700. } else {
  11701. this.checkReservedWord(name, startLoc, tokenIsKeyword, false);
  11702. }
  11703. this.next();
  11704. return name;
  11705. }
  11706. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  11707. if (word.length > 10) {
  11708. return;
  11709. }
  11710. if (!canBeReservedWord(word)) {
  11711. return;
  11712. }
  11713. if (checkKeywords && isKeyword(word)) {
  11714. this.raise(Errors.UnexpectedKeyword, startLoc, {
  11715. keyword: word
  11716. });
  11717. return;
  11718. }
  11719. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  11720. if (reservedTest(word, this.inModule)) {
  11721. this.raise(Errors.UnexpectedReservedWord, startLoc, {
  11722. reservedWord: word
  11723. });
  11724. return;
  11725. } else if (word === "yield") {
  11726. if (this.prodParam.hasYield) {
  11727. this.raise(Errors.YieldBindingIdentifier, startLoc);
  11728. return;
  11729. }
  11730. } else if (word === "await") {
  11731. if (this.prodParam.hasAwait) {
  11732. this.raise(Errors.AwaitBindingIdentifier, startLoc);
  11733. return;
  11734. }
  11735. if (this.scope.inStaticBlock) {
  11736. this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc);
  11737. return;
  11738. }
  11739. this.expressionScope.recordAsyncArrowParametersError(startLoc);
  11740. } else if (word === "arguments") {
  11741. if (this.scope.inClassAndNotInNonArrowFunction) {
  11742. this.raise(Errors.ArgumentsInClass, startLoc);
  11743. return;
  11744. }
  11745. }
  11746. }
  11747. recordAwaitIfAllowed() {
  11748. const isAwaitAllowed = this.prodParam.hasAwait || this.options.allowAwaitOutsideFunction && !this.scope.inFunction;
  11749. if (isAwaitAllowed && !this.scope.inFunction) {
  11750. this.state.hasTopLevelAwait = true;
  11751. }
  11752. return isAwaitAllowed;
  11753. }
  11754. parseAwait(startLoc) {
  11755. const node = this.startNodeAt(startLoc);
  11756. this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node);
  11757. if (this.eat(55)) {
  11758. this.raise(Errors.ObsoleteAwaitStar, node);
  11759. }
  11760. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  11761. if (this.isAmbiguousAwait()) {
  11762. this.ambiguousScriptDifferentAst = true;
  11763. } else {
  11764. this.sawUnambiguousESM = true;
  11765. }
  11766. }
  11767. if (!this.state.soloAwait) {
  11768. node.argument = this.parseMaybeUnary(null, true);
  11769. }
  11770. return this.finishNode(node, "AwaitExpression");
  11771. }
  11772. isAmbiguousAwait() {
  11773. if (this.hasPrecedingLineBreak()) return true;
  11774. const {
  11775. type
  11776. } = this.state;
  11777. return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 137 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54;
  11778. }
  11779. parseYield() {
  11780. const node = this.startNode();
  11781. this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node);
  11782. this.next();
  11783. let delegating = false;
  11784. let argument = null;
  11785. if (!this.hasPrecedingLineBreak()) {
  11786. delegating = this.eat(55);
  11787. switch (this.state.type) {
  11788. case 13:
  11789. case 139:
  11790. case 8:
  11791. case 11:
  11792. case 3:
  11793. case 9:
  11794. case 14:
  11795. case 12:
  11796. if (!delegating) break;
  11797. default:
  11798. argument = this.parseMaybeAssign();
  11799. }
  11800. }
  11801. node.delegate = delegating;
  11802. node.argument = argument;
  11803. return this.finishNode(node, "YieldExpression");
  11804. }
  11805. parseImportCall(node) {
  11806. this.next();
  11807. node.source = this.parseMaybeAssignAllowIn();
  11808. if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) {
  11809. node.options = null;
  11810. }
  11811. if (this.eat(12)) {
  11812. this.expectImportAttributesPlugin();
  11813. if (!this.match(11)) {
  11814. node.options = this.parseMaybeAssignAllowIn();
  11815. this.eat(12);
  11816. }
  11817. }
  11818. this.expect(11);
  11819. return this.finishNode(node, "ImportExpression");
  11820. }
  11821. checkPipelineAtInfixOperator(left, leftStartLoc) {
  11822. if (this.hasPlugin(["pipelineOperator", {
  11823. proposal: "smart"
  11824. }])) {
  11825. if (left.type === "SequenceExpression") {
  11826. this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc);
  11827. }
  11828. }
  11829. }
  11830. parseSmartPipelineBodyInStyle(childExpr, startLoc) {
  11831. if (this.isSimpleReference(childExpr)) {
  11832. const bodyNode = this.startNodeAt(startLoc);
  11833. bodyNode.callee = childExpr;
  11834. return this.finishNode(bodyNode, "PipelineBareFunction");
  11835. } else {
  11836. const bodyNode = this.startNodeAt(startLoc);
  11837. this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
  11838. bodyNode.expression = childExpr;
  11839. return this.finishNode(bodyNode, "PipelineTopicExpression");
  11840. }
  11841. }
  11842. isSimpleReference(expression) {
  11843. switch (expression.type) {
  11844. case "MemberExpression":
  11845. return !expression.computed && this.isSimpleReference(expression.object);
  11846. case "Identifier":
  11847. return true;
  11848. default:
  11849. return false;
  11850. }
  11851. }
  11852. checkSmartPipeTopicBodyEarlyErrors(startLoc) {
  11853. if (this.match(19)) {
  11854. throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc);
  11855. }
  11856. if (!this.topicReferenceWasUsedInCurrentContext()) {
  11857. this.raise(Errors.PipelineTopicUnused, startLoc);
  11858. }
  11859. }
  11860. withTopicBindingContext(callback) {
  11861. const outerContextTopicState = this.state.topicContext;
  11862. this.state.topicContext = {
  11863. maxNumOfResolvableTopics: 1,
  11864. maxTopicIndex: null
  11865. };
  11866. try {
  11867. return callback();
  11868. } finally {
  11869. this.state.topicContext = outerContextTopicState;
  11870. }
  11871. }
  11872. withSmartMixTopicForbiddingContext(callback) {
  11873. if (this.hasPlugin(["pipelineOperator", {
  11874. proposal: "smart"
  11875. }])) {
  11876. const outerContextTopicState = this.state.topicContext;
  11877. this.state.topicContext = {
  11878. maxNumOfResolvableTopics: 0,
  11879. maxTopicIndex: null
  11880. };
  11881. try {
  11882. return callback();
  11883. } finally {
  11884. this.state.topicContext = outerContextTopicState;
  11885. }
  11886. } else {
  11887. return callback();
  11888. }
  11889. }
  11890. withSoloAwaitPermittingContext(callback) {
  11891. const outerContextSoloAwaitState = this.state.soloAwait;
  11892. this.state.soloAwait = true;
  11893. try {
  11894. return callback();
  11895. } finally {
  11896. this.state.soloAwait = outerContextSoloAwaitState;
  11897. }
  11898. }
  11899. allowInAnd(callback) {
  11900. const flags = this.prodParam.currentFlags();
  11901. const prodParamToSet = 8 & ~flags;
  11902. if (prodParamToSet) {
  11903. this.prodParam.enter(flags | 8);
  11904. try {
  11905. return callback();
  11906. } finally {
  11907. this.prodParam.exit();
  11908. }
  11909. }
  11910. return callback();
  11911. }
  11912. disallowInAnd(callback) {
  11913. const flags = this.prodParam.currentFlags();
  11914. const prodParamToClear = 8 & flags;
  11915. if (prodParamToClear) {
  11916. this.prodParam.enter(flags & ~8);
  11917. try {
  11918. return callback();
  11919. } finally {
  11920. this.prodParam.exit();
  11921. }
  11922. }
  11923. return callback();
  11924. }
  11925. registerTopicReference() {
  11926. this.state.topicContext.maxTopicIndex = 0;
  11927. }
  11928. topicReferenceIsAllowedInCurrentContext() {
  11929. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  11930. }
  11931. topicReferenceWasUsedInCurrentContext() {
  11932. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  11933. }
  11934. parseFSharpPipelineBody(prec) {
  11935. const startLoc = this.state.startLoc;
  11936. this.state.potentialArrowAt = this.state.start;
  11937. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11938. this.state.inFSharpPipelineDirectBody = true;
  11939. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
  11940. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11941. return ret;
  11942. }
  11943. parseModuleExpression() {
  11944. this.expectPlugin("moduleBlocks");
  11945. const node = this.startNode();
  11946. this.next();
  11947. if (!this.match(5)) {
  11948. this.unexpected(null, 5);
  11949. }
  11950. const program = this.startNodeAt(this.state.endLoc);
  11951. this.next();
  11952. const revertScopes = this.initializeScopes(true);
  11953. this.enterInitialScopes();
  11954. try {
  11955. node.body = this.parseProgram(program, 8, "module");
  11956. } finally {
  11957. revertScopes();
  11958. }
  11959. return this.finishNode(node, "ModuleExpression");
  11960. }
  11961. parsePropertyNamePrefixOperator(prop) {}
  11962. }
  11963. const loopLabel = {
  11964. kind: 1
  11965. },
  11966. switchLabel = {
  11967. kind: 2
  11968. };
  11969. const loneSurrogate = /[\uD800-\uDFFF]/u;
  11970. const keywordRelationalOperator = /in(?:stanceof)?/y;
  11971. function babel7CompatTokens(tokens, input) {
  11972. for (let i = 0; i < tokens.length; i++) {
  11973. const token = tokens[i];
  11974. const {
  11975. type
  11976. } = token;
  11977. if (typeof type === "number") {
  11978. {
  11979. if (type === 138) {
  11980. const {
  11981. loc,
  11982. start,
  11983. value,
  11984. end
  11985. } = token;
  11986. const hashEndPos = start + 1;
  11987. const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
  11988. tokens.splice(i, 1, new Token({
  11989. type: getExportedToken(27),
  11990. value: "#",
  11991. start: start,
  11992. end: hashEndPos,
  11993. startLoc: loc.start,
  11994. endLoc: hashEndLoc
  11995. }), new Token({
  11996. type: getExportedToken(132),
  11997. value: value,
  11998. start: hashEndPos,
  11999. end: end,
  12000. startLoc: hashEndLoc,
  12001. endLoc: loc.end
  12002. }));
  12003. i++;
  12004. continue;
  12005. }
  12006. if (tokenIsTemplate(type)) {
  12007. const {
  12008. loc,
  12009. start,
  12010. value,
  12011. end
  12012. } = token;
  12013. const backquoteEnd = start + 1;
  12014. const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
  12015. let startToken;
  12016. if (input.charCodeAt(start) === 96) {
  12017. startToken = new Token({
  12018. type: getExportedToken(22),
  12019. value: "`",
  12020. start: start,
  12021. end: backquoteEnd,
  12022. startLoc: loc.start,
  12023. endLoc: backquoteEndLoc
  12024. });
  12025. } else {
  12026. startToken = new Token({
  12027. type: getExportedToken(8),
  12028. value: "}",
  12029. start: start,
  12030. end: backquoteEnd,
  12031. startLoc: loc.start,
  12032. endLoc: backquoteEndLoc
  12033. });
  12034. }
  12035. let templateValue, templateElementEnd, templateElementEndLoc, endToken;
  12036. if (type === 24) {
  12037. templateElementEnd = end - 1;
  12038. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
  12039. templateValue = value === null ? null : value.slice(1, -1);
  12040. endToken = new Token({
  12041. type: getExportedToken(22),
  12042. value: "`",
  12043. start: templateElementEnd,
  12044. end: end,
  12045. startLoc: templateElementEndLoc,
  12046. endLoc: loc.end
  12047. });
  12048. } else {
  12049. templateElementEnd = end - 2;
  12050. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
  12051. templateValue = value === null ? null : value.slice(1, -2);
  12052. endToken = new Token({
  12053. type: getExportedToken(23),
  12054. value: "${",
  12055. start: templateElementEnd,
  12056. end: end,
  12057. startLoc: templateElementEndLoc,
  12058. endLoc: loc.end
  12059. });
  12060. }
  12061. tokens.splice(i, 1, startToken, new Token({
  12062. type: getExportedToken(20),
  12063. value: templateValue,
  12064. start: backquoteEnd,
  12065. end: templateElementEnd,
  12066. startLoc: backquoteEndLoc,
  12067. endLoc: templateElementEndLoc
  12068. }), endToken);
  12069. i += 2;
  12070. continue;
  12071. }
  12072. }
  12073. token.type = getExportedToken(type);
  12074. }
  12075. }
  12076. return tokens;
  12077. }
  12078. class StatementParser extends ExpressionParser {
  12079. parseTopLevel(file, program) {
  12080. file.program = this.parseProgram(program);
  12081. file.comments = this.comments;
  12082. if (this.options.tokens) {
  12083. file.tokens = babel7CompatTokens(this.tokens, this.input);
  12084. }
  12085. return this.finishNode(file, "File");
  12086. }
  12087. parseProgram(program, end = 139, sourceType = this.options.sourceType) {
  12088. program.sourceType = sourceType;
  12089. program.interpreter = this.parseInterpreterDirective();
  12090. this.parseBlockBody(program, true, true, end);
  12091. if (this.inModule) {
  12092. if (!this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  12093. for (const [localName, at] of Array.from(this.scope.undefinedExports)) {
  12094. this.raise(Errors.ModuleExportUndefined, at, {
  12095. localName
  12096. });
  12097. }
  12098. }
  12099. this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait);
  12100. }
  12101. let finishedProgram;
  12102. if (end === 139) {
  12103. finishedProgram = this.finishNode(program, "Program");
  12104. } else {
  12105. finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
  12106. }
  12107. return finishedProgram;
  12108. }
  12109. stmtToDirective(stmt) {
  12110. const directive = stmt;
  12111. directive.type = "Directive";
  12112. directive.value = directive.expression;
  12113. delete directive.expression;
  12114. const directiveLiteral = directive.value;
  12115. const expressionValue = directiveLiteral.value;
  12116. const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
  12117. const val = directiveLiteral.value = raw.slice(1, -1);
  12118. this.addExtra(directiveLiteral, "raw", raw);
  12119. this.addExtra(directiveLiteral, "rawValue", val);
  12120. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  12121. directiveLiteral.type = "DirectiveLiteral";
  12122. return directive;
  12123. }
  12124. parseInterpreterDirective() {
  12125. if (!this.match(28)) {
  12126. return null;
  12127. }
  12128. const node = this.startNode();
  12129. node.value = this.state.value;
  12130. this.next();
  12131. return this.finishNode(node, "InterpreterDirective");
  12132. }
  12133. isLet() {
  12134. if (!this.isContextual(100)) {
  12135. return false;
  12136. }
  12137. return this.hasFollowingBindingAtom();
  12138. }
  12139. chStartsBindingIdentifier(ch, pos) {
  12140. if (isIdentifierStart(ch)) {
  12141. keywordRelationalOperator.lastIndex = pos;
  12142. if (keywordRelationalOperator.test(this.input)) {
  12143. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  12144. if (!isIdentifierChar(endCh) && endCh !== 92) {
  12145. return false;
  12146. }
  12147. }
  12148. return true;
  12149. } else if (ch === 92) {
  12150. return true;
  12151. } else {
  12152. return false;
  12153. }
  12154. }
  12155. chStartsBindingPattern(ch) {
  12156. return ch === 91 || ch === 123;
  12157. }
  12158. hasFollowingBindingAtom() {
  12159. const next = this.nextTokenStart();
  12160. const nextCh = this.codePointAtPos(next);
  12161. return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  12162. }
  12163. hasInLineFollowingBindingIdentifierOrBrace() {
  12164. const next = this.nextTokenInLineStart();
  12165. const nextCh = this.codePointAtPos(next);
  12166. return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next);
  12167. }
  12168. startsUsingForOf() {
  12169. const {
  12170. type,
  12171. containsEsc
  12172. } = this.lookahead();
  12173. if (type === 102 && !containsEsc) {
  12174. return false;
  12175. } else if (tokenIsIdentifier(type) && !this.hasFollowingLineBreak()) {
  12176. this.expectPlugin("explicitResourceManagement");
  12177. return true;
  12178. }
  12179. }
  12180. startsAwaitUsing() {
  12181. let next = this.nextTokenInLineStart();
  12182. if (this.isUnparsedContextual(next, "using")) {
  12183. next = this.nextTokenInLineStartSince(next + 5);
  12184. const nextCh = this.codePointAtPos(next);
  12185. if (this.chStartsBindingIdentifier(nextCh, next)) {
  12186. this.expectPlugin("explicitResourceManagement");
  12187. return true;
  12188. }
  12189. }
  12190. return false;
  12191. }
  12192. parseModuleItem() {
  12193. return this.parseStatementLike(1 | 2 | 4 | 8);
  12194. }
  12195. parseStatementListItem() {
  12196. return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8));
  12197. }
  12198. parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) {
  12199. let flags = 0;
  12200. if (this.options.annexB && !this.state.strict) {
  12201. flags |= 4;
  12202. if (allowLabeledFunction) {
  12203. flags |= 8;
  12204. }
  12205. }
  12206. return this.parseStatementLike(flags);
  12207. }
  12208. parseStatement() {
  12209. return this.parseStatementLike(0);
  12210. }
  12211. parseStatementLike(flags) {
  12212. let decorators = null;
  12213. if (this.match(26)) {
  12214. decorators = this.parseDecorators(true);
  12215. }
  12216. return this.parseStatementContent(flags, decorators);
  12217. }
  12218. parseStatementContent(flags, decorators) {
  12219. const startType = this.state.type;
  12220. const node = this.startNode();
  12221. const allowDeclaration = !!(flags & 2);
  12222. const allowFunctionDeclaration = !!(flags & 4);
  12223. const topLevel = flags & 1;
  12224. switch (startType) {
  12225. case 60:
  12226. return this.parseBreakContinueStatement(node, true);
  12227. case 63:
  12228. return this.parseBreakContinueStatement(node, false);
  12229. case 64:
  12230. return this.parseDebuggerStatement(node);
  12231. case 90:
  12232. return this.parseDoWhileStatement(node);
  12233. case 91:
  12234. return this.parseForStatement(node);
  12235. case 68:
  12236. if (this.lookaheadCharCode() === 46) break;
  12237. if (!allowFunctionDeclaration) {
  12238. this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc);
  12239. }
  12240. return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration);
  12241. case 80:
  12242. if (!allowDeclaration) this.unexpected();
  12243. return this.parseClass(this.maybeTakeDecorators(decorators, node), true);
  12244. case 69:
  12245. return this.parseIfStatement(node);
  12246. case 70:
  12247. return this.parseReturnStatement(node);
  12248. case 71:
  12249. return this.parseSwitchStatement(node);
  12250. case 72:
  12251. return this.parseThrowStatement(node);
  12252. case 73:
  12253. return this.parseTryStatement(node);
  12254. case 96:
  12255. if (!this.state.containsEsc && this.startsAwaitUsing()) {
  12256. if (!this.recordAwaitIfAllowed()) {
  12257. this.raise(Errors.AwaitUsingNotInAsyncContext, node);
  12258. } else if (!allowDeclaration) {
  12259. this.raise(Errors.UnexpectedLexicalDeclaration, node);
  12260. }
  12261. this.next();
  12262. return this.parseVarStatement(node, "await using");
  12263. }
  12264. break;
  12265. case 107:
  12266. if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) {
  12267. break;
  12268. }
  12269. this.expectPlugin("explicitResourceManagement");
  12270. if (!this.scope.inModule && this.scope.inTopLevel) {
  12271. this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc);
  12272. } else if (!allowDeclaration) {
  12273. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  12274. }
  12275. return this.parseVarStatement(node, "using");
  12276. case 100:
  12277. {
  12278. if (this.state.containsEsc) {
  12279. break;
  12280. }
  12281. const next = this.nextTokenStart();
  12282. const nextCh = this.codePointAtPos(next);
  12283. if (nextCh !== 91) {
  12284. if (!allowDeclaration && this.hasFollowingLineBreak()) break;
  12285. if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
  12286. break;
  12287. }
  12288. }
  12289. }
  12290. case 75:
  12291. {
  12292. if (!allowDeclaration) {
  12293. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  12294. }
  12295. }
  12296. case 74:
  12297. {
  12298. const kind = this.state.value;
  12299. return this.parseVarStatement(node, kind);
  12300. }
  12301. case 92:
  12302. return this.parseWhileStatement(node);
  12303. case 76:
  12304. return this.parseWithStatement(node);
  12305. case 5:
  12306. return this.parseBlock();
  12307. case 13:
  12308. return this.parseEmptyStatement(node);
  12309. case 83:
  12310. {
  12311. const nextTokenCharCode = this.lookaheadCharCode();
  12312. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  12313. break;
  12314. }
  12315. }
  12316. case 82:
  12317. {
  12318. if (!this.options.allowImportExportEverywhere && !topLevel) {
  12319. this.raise(Errors.UnexpectedImportExport, this.state.startLoc);
  12320. }
  12321. this.next();
  12322. let result;
  12323. if (startType === 83) {
  12324. result = this.parseImport(node);
  12325. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  12326. this.sawUnambiguousESM = true;
  12327. }
  12328. } else {
  12329. result = this.parseExport(node, decorators);
  12330. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  12331. this.sawUnambiguousESM = true;
  12332. }
  12333. }
  12334. this.assertModuleNodeAllowed(result);
  12335. return result;
  12336. }
  12337. default:
  12338. {
  12339. if (this.isAsyncFunction()) {
  12340. if (!allowDeclaration) {
  12341. this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc);
  12342. }
  12343. this.next();
  12344. return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration);
  12345. }
  12346. }
  12347. }
  12348. const maybeName = this.state.value;
  12349. const expr = this.parseExpression();
  12350. if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) {
  12351. return this.parseLabeledStatement(node, maybeName, expr, flags);
  12352. } else {
  12353. return this.parseExpressionStatement(node, expr, decorators);
  12354. }
  12355. }
  12356. assertModuleNodeAllowed(node) {
  12357. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  12358. this.raise(Errors.ImportOutsideModule, node);
  12359. }
  12360. }
  12361. decoratorsEnabledBeforeExport() {
  12362. if (this.hasPlugin("decorators-legacy")) return true;
  12363. return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false;
  12364. }
  12365. maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
  12366. if (maybeDecorators) {
  12367. if (classNode.decorators && classNode.decorators.length > 0) {
  12368. if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") {
  12369. this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]);
  12370. }
  12371. classNode.decorators.unshift(...maybeDecorators);
  12372. } else {
  12373. classNode.decorators = maybeDecorators;
  12374. }
  12375. this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
  12376. if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);
  12377. }
  12378. return classNode;
  12379. }
  12380. canHaveLeadingDecorator() {
  12381. return this.match(80);
  12382. }
  12383. parseDecorators(allowExport) {
  12384. const decorators = [];
  12385. do {
  12386. decorators.push(this.parseDecorator());
  12387. } while (this.match(26));
  12388. if (this.match(82)) {
  12389. if (!allowExport) {
  12390. this.unexpected();
  12391. }
  12392. if (!this.decoratorsEnabledBeforeExport()) {
  12393. this.raise(Errors.DecoratorExportClass, this.state.startLoc);
  12394. }
  12395. } else if (!this.canHaveLeadingDecorator()) {
  12396. throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc);
  12397. }
  12398. return decorators;
  12399. }
  12400. parseDecorator() {
  12401. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12402. const node = this.startNode();
  12403. this.next();
  12404. if (this.hasPlugin("decorators")) {
  12405. const startLoc = this.state.startLoc;
  12406. let expr;
  12407. if (this.match(10)) {
  12408. const startLoc = this.state.startLoc;
  12409. this.next();
  12410. expr = this.parseExpression();
  12411. this.expect(11);
  12412. expr = this.wrapParenthesis(startLoc, expr);
  12413. const paramsStartLoc = this.state.startLoc;
  12414. node.expression = this.parseMaybeDecoratorArguments(expr);
  12415. if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) {
  12416. this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc);
  12417. }
  12418. } else {
  12419. expr = this.parseIdentifier(false);
  12420. while (this.eat(16)) {
  12421. const node = this.startNodeAt(startLoc);
  12422. node.object = expr;
  12423. if (this.match(138)) {
  12424. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  12425. node.property = this.parsePrivateName();
  12426. } else {
  12427. node.property = this.parseIdentifier(true);
  12428. }
  12429. node.computed = false;
  12430. expr = this.finishNode(node, "MemberExpression");
  12431. }
  12432. node.expression = this.parseMaybeDecoratorArguments(expr);
  12433. }
  12434. } else {
  12435. node.expression = this.parseExprSubscripts();
  12436. }
  12437. return this.finishNode(node, "Decorator");
  12438. }
  12439. parseMaybeDecoratorArguments(expr) {
  12440. if (this.eat(10)) {
  12441. const node = this.startNodeAtNode(expr);
  12442. node.callee = expr;
  12443. node.arguments = this.parseCallExpressionArguments(11, false);
  12444. this.toReferencedList(node.arguments);
  12445. return this.finishNode(node, "CallExpression");
  12446. }
  12447. return expr;
  12448. }
  12449. parseBreakContinueStatement(node, isBreak) {
  12450. this.next();
  12451. if (this.isLineTerminator()) {
  12452. node.label = null;
  12453. } else {
  12454. node.label = this.parseIdentifier();
  12455. this.semicolon();
  12456. }
  12457. this.verifyBreakContinue(node, isBreak);
  12458. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  12459. }
  12460. verifyBreakContinue(node, isBreak) {
  12461. let i;
  12462. for (i = 0; i < this.state.labels.length; ++i) {
  12463. const lab = this.state.labels[i];
  12464. if (node.label == null || lab.name === node.label.name) {
  12465. if (lab.kind != null && (isBreak || lab.kind === 1)) {
  12466. break;
  12467. }
  12468. if (node.label && isBreak) break;
  12469. }
  12470. }
  12471. if (i === this.state.labels.length) {
  12472. const type = isBreak ? "BreakStatement" : "ContinueStatement";
  12473. this.raise(Errors.IllegalBreakContinue, node, {
  12474. type
  12475. });
  12476. }
  12477. }
  12478. parseDebuggerStatement(node) {
  12479. this.next();
  12480. this.semicolon();
  12481. return this.finishNode(node, "DebuggerStatement");
  12482. }
  12483. parseHeaderExpression() {
  12484. this.expect(10);
  12485. const val = this.parseExpression();
  12486. this.expect(11);
  12487. return val;
  12488. }
  12489. parseDoWhileStatement(node) {
  12490. this.next();
  12491. this.state.labels.push(loopLabel);
  12492. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12493. this.state.labels.pop();
  12494. this.expect(92);
  12495. node.test = this.parseHeaderExpression();
  12496. this.eat(13);
  12497. return this.finishNode(node, "DoWhileStatement");
  12498. }
  12499. parseForStatement(node) {
  12500. this.next();
  12501. this.state.labels.push(loopLabel);
  12502. let awaitAt = null;
  12503. if (this.isContextual(96) && this.recordAwaitIfAllowed()) {
  12504. awaitAt = this.state.startLoc;
  12505. this.next();
  12506. }
  12507. this.scope.enter(0);
  12508. this.expect(10);
  12509. if (this.match(13)) {
  12510. if (awaitAt !== null) {
  12511. this.unexpected(awaitAt);
  12512. }
  12513. return this.parseFor(node, null);
  12514. }
  12515. const startsWithLet = this.isContextual(100);
  12516. {
  12517. const startsWithAwaitUsing = this.isContextual(96) && this.startsAwaitUsing();
  12518. const starsWithUsingDeclaration = startsWithAwaitUsing || this.isContextual(107) && this.startsUsingForOf();
  12519. const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration;
  12520. if (this.match(74) || this.match(75) || isLetOrUsing) {
  12521. const initNode = this.startNode();
  12522. let kind;
  12523. if (startsWithAwaitUsing) {
  12524. kind = "await using";
  12525. if (!this.recordAwaitIfAllowed()) {
  12526. this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc);
  12527. }
  12528. this.next();
  12529. } else {
  12530. kind = this.state.value;
  12531. }
  12532. this.next();
  12533. this.parseVar(initNode, true, kind);
  12534. const init = this.finishNode(initNode, "VariableDeclaration");
  12535. const isForIn = this.match(58);
  12536. if (isForIn && starsWithUsingDeclaration) {
  12537. this.raise(Errors.ForInUsing, init);
  12538. }
  12539. if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) {
  12540. return this.parseForIn(node, init, awaitAt);
  12541. }
  12542. if (awaitAt !== null) {
  12543. this.unexpected(awaitAt);
  12544. }
  12545. return this.parseFor(node, init);
  12546. }
  12547. }
  12548. const startsWithAsync = this.isContextual(95);
  12549. const refExpressionErrors = new ExpressionErrors();
  12550. const init = this.parseExpression(true, refExpressionErrors);
  12551. const isForOf = this.isContextual(102);
  12552. if (isForOf) {
  12553. if (startsWithLet) {
  12554. this.raise(Errors.ForOfLet, init);
  12555. }
  12556. if (awaitAt === null && startsWithAsync && init.type === "Identifier") {
  12557. this.raise(Errors.ForOfAsync, init);
  12558. }
  12559. }
  12560. if (isForOf || this.match(58)) {
  12561. this.checkDestructuringPrivate(refExpressionErrors);
  12562. this.toAssignable(init, true);
  12563. const type = isForOf ? "ForOfStatement" : "ForInStatement";
  12564. this.checkLVal(init, {
  12565. type
  12566. });
  12567. return this.parseForIn(node, init, awaitAt);
  12568. } else {
  12569. this.checkExpressionErrors(refExpressionErrors, true);
  12570. }
  12571. if (awaitAt !== null) {
  12572. this.unexpected(awaitAt);
  12573. }
  12574. return this.parseFor(node, init);
  12575. }
  12576. parseFunctionStatement(node, isAsync, isHangingDeclaration) {
  12577. this.next();
  12578. return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0));
  12579. }
  12580. parseIfStatement(node) {
  12581. this.next();
  12582. node.test = this.parseHeaderExpression();
  12583. node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();
  12584. node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null;
  12585. return this.finishNode(node, "IfStatement");
  12586. }
  12587. parseReturnStatement(node) {
  12588. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  12589. this.raise(Errors.IllegalReturn, this.state.startLoc);
  12590. }
  12591. this.next();
  12592. if (this.isLineTerminator()) {
  12593. node.argument = null;
  12594. } else {
  12595. node.argument = this.parseExpression();
  12596. this.semicolon();
  12597. }
  12598. return this.finishNode(node, "ReturnStatement");
  12599. }
  12600. parseSwitchStatement(node) {
  12601. this.next();
  12602. node.discriminant = this.parseHeaderExpression();
  12603. const cases = node.cases = [];
  12604. this.expect(5);
  12605. this.state.labels.push(switchLabel);
  12606. this.scope.enter(0);
  12607. let cur;
  12608. for (let sawDefault; !this.match(8);) {
  12609. if (this.match(61) || this.match(65)) {
  12610. const isCase = this.match(61);
  12611. if (cur) this.finishNode(cur, "SwitchCase");
  12612. cases.push(cur = this.startNode());
  12613. cur.consequent = [];
  12614. this.next();
  12615. if (isCase) {
  12616. cur.test = this.parseExpression();
  12617. } else {
  12618. if (sawDefault) {
  12619. this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc);
  12620. }
  12621. sawDefault = true;
  12622. cur.test = null;
  12623. }
  12624. this.expect(14);
  12625. } else {
  12626. if (cur) {
  12627. cur.consequent.push(this.parseStatementListItem());
  12628. } else {
  12629. this.unexpected();
  12630. }
  12631. }
  12632. }
  12633. this.scope.exit();
  12634. if (cur) this.finishNode(cur, "SwitchCase");
  12635. this.next();
  12636. this.state.labels.pop();
  12637. return this.finishNode(node, "SwitchStatement");
  12638. }
  12639. parseThrowStatement(node) {
  12640. this.next();
  12641. if (this.hasPrecedingLineBreak()) {
  12642. this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc);
  12643. }
  12644. node.argument = this.parseExpression();
  12645. this.semicolon();
  12646. return this.finishNode(node, "ThrowStatement");
  12647. }
  12648. parseCatchClauseParam() {
  12649. const param = this.parseBindingAtom();
  12650. this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0);
  12651. this.checkLVal(param, {
  12652. type: "CatchClause"
  12653. }, 9);
  12654. return param;
  12655. }
  12656. parseTryStatement(node) {
  12657. this.next();
  12658. node.block = this.parseBlock();
  12659. node.handler = null;
  12660. if (this.match(62)) {
  12661. const clause = this.startNode();
  12662. this.next();
  12663. if (this.match(10)) {
  12664. this.expect(10);
  12665. clause.param = this.parseCatchClauseParam();
  12666. this.expect(11);
  12667. } else {
  12668. clause.param = null;
  12669. this.scope.enter(0);
  12670. }
  12671. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  12672. this.scope.exit();
  12673. node.handler = this.finishNode(clause, "CatchClause");
  12674. }
  12675. node.finalizer = this.eat(67) ? this.parseBlock() : null;
  12676. if (!node.handler && !node.finalizer) {
  12677. this.raise(Errors.NoCatchOrFinally, node);
  12678. }
  12679. return this.finishNode(node, "TryStatement");
  12680. }
  12681. parseVarStatement(node, kind, allowMissingInitializer = false) {
  12682. this.next();
  12683. this.parseVar(node, false, kind, allowMissingInitializer);
  12684. this.semicolon();
  12685. return this.finishNode(node, "VariableDeclaration");
  12686. }
  12687. parseWhileStatement(node) {
  12688. this.next();
  12689. node.test = this.parseHeaderExpression();
  12690. this.state.labels.push(loopLabel);
  12691. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12692. this.state.labels.pop();
  12693. return this.finishNode(node, "WhileStatement");
  12694. }
  12695. parseWithStatement(node) {
  12696. if (this.state.strict) {
  12697. this.raise(Errors.StrictWith, this.state.startLoc);
  12698. }
  12699. this.next();
  12700. node.object = this.parseHeaderExpression();
  12701. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12702. return this.finishNode(node, "WithStatement");
  12703. }
  12704. parseEmptyStatement(node) {
  12705. this.next();
  12706. return this.finishNode(node, "EmptyStatement");
  12707. }
  12708. parseLabeledStatement(node, maybeName, expr, flags) {
  12709. for (const label of this.state.labels) {
  12710. if (label.name === maybeName) {
  12711. this.raise(Errors.LabelRedeclaration, expr, {
  12712. labelName: maybeName
  12713. });
  12714. }
  12715. }
  12716. const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null;
  12717. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  12718. const label = this.state.labels[i];
  12719. if (label.statementStart === node.start) {
  12720. label.statementStart = this.state.start;
  12721. label.kind = kind;
  12722. } else {
  12723. break;
  12724. }
  12725. }
  12726. this.state.labels.push({
  12727. name: maybeName,
  12728. kind: kind,
  12729. statementStart: this.state.start
  12730. });
  12731. node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement();
  12732. this.state.labels.pop();
  12733. node.label = expr;
  12734. return this.finishNode(node, "LabeledStatement");
  12735. }
  12736. parseExpressionStatement(node, expr, decorators) {
  12737. node.expression = expr;
  12738. this.semicolon();
  12739. return this.finishNode(node, "ExpressionStatement");
  12740. }
  12741. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  12742. const node = this.startNode();
  12743. if (allowDirectives) {
  12744. this.state.strictErrors.clear();
  12745. }
  12746. this.expect(5);
  12747. if (createNewLexicalScope) {
  12748. this.scope.enter(0);
  12749. }
  12750. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  12751. if (createNewLexicalScope) {
  12752. this.scope.exit();
  12753. }
  12754. return this.finishNode(node, "BlockStatement");
  12755. }
  12756. isValidDirective(stmt) {
  12757. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  12758. }
  12759. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  12760. const body = node.body = [];
  12761. const directives = node.directives = [];
  12762. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  12763. }
  12764. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  12765. const oldStrict = this.state.strict;
  12766. let hasStrictModeDirective = false;
  12767. let parsedNonDirective = false;
  12768. while (!this.match(end)) {
  12769. const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
  12770. if (directives && !parsedNonDirective) {
  12771. if (this.isValidDirective(stmt)) {
  12772. const directive = this.stmtToDirective(stmt);
  12773. directives.push(directive);
  12774. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  12775. hasStrictModeDirective = true;
  12776. this.setStrict(true);
  12777. }
  12778. continue;
  12779. }
  12780. parsedNonDirective = true;
  12781. this.state.strictErrors.clear();
  12782. }
  12783. body.push(stmt);
  12784. }
  12785. afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective);
  12786. if (!oldStrict) {
  12787. this.setStrict(false);
  12788. }
  12789. this.next();
  12790. }
  12791. parseFor(node, init) {
  12792. node.init = init;
  12793. this.semicolon(false);
  12794. node.test = this.match(13) ? null : this.parseExpression();
  12795. this.semicolon(false);
  12796. node.update = this.match(11) ? null : this.parseExpression();
  12797. this.expect(11);
  12798. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12799. this.scope.exit();
  12800. this.state.labels.pop();
  12801. return this.finishNode(node, "ForStatement");
  12802. }
  12803. parseForIn(node, init, awaitAt) {
  12804. const isForIn = this.match(58);
  12805. this.next();
  12806. if (isForIn) {
  12807. if (awaitAt !== null) this.unexpected(awaitAt);
  12808. } else {
  12809. node.await = awaitAt !== null;
  12810. }
  12811. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  12812. this.raise(Errors.ForInOfLoopInitializer, init, {
  12813. type: isForIn ? "ForInStatement" : "ForOfStatement"
  12814. });
  12815. }
  12816. if (init.type === "AssignmentPattern") {
  12817. this.raise(Errors.InvalidLhs, init, {
  12818. ancestor: {
  12819. type: "ForStatement"
  12820. }
  12821. });
  12822. }
  12823. node.left = init;
  12824. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  12825. this.expect(11);
  12826. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  12827. this.scope.exit();
  12828. this.state.labels.pop();
  12829. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  12830. }
  12831. parseVar(node, isFor, kind, allowMissingInitializer = false) {
  12832. const declarations = node.declarations = [];
  12833. node.kind = kind;
  12834. for (;;) {
  12835. const decl = this.startNode();
  12836. this.parseVarId(decl, kind);
  12837. decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  12838. if (decl.init === null && !allowMissingInitializer) {
  12839. if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) {
  12840. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  12841. kind: "destructuring"
  12842. });
  12843. } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) {
  12844. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  12845. kind
  12846. });
  12847. }
  12848. }
  12849. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  12850. if (!this.eat(12)) break;
  12851. }
  12852. return node;
  12853. }
  12854. parseVarId(decl, kind) {
  12855. const id = this.parseBindingAtom();
  12856. if (kind === "using" || kind === "await using") {
  12857. if (id.type === "ArrayPattern" || id.type === "ObjectPattern") {
  12858. this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);
  12859. }
  12860. }
  12861. this.checkLVal(id, {
  12862. type: "VariableDeclarator"
  12863. }, kind === "var" ? 5 : 8201);
  12864. decl.id = id;
  12865. }
  12866. parseAsyncFunctionExpression(node) {
  12867. return this.parseFunction(node, 8);
  12868. }
  12869. parseFunction(node, flags = 0) {
  12870. const hangingDeclaration = flags & 2;
  12871. const isDeclaration = !!(flags & 1);
  12872. const requireId = isDeclaration && !(flags & 4);
  12873. const isAsync = !!(flags & 8);
  12874. this.initFunction(node, isAsync);
  12875. if (this.match(55)) {
  12876. if (hangingDeclaration) {
  12877. this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc);
  12878. }
  12879. this.next();
  12880. node.generator = true;
  12881. }
  12882. if (isDeclaration) {
  12883. node.id = this.parseFunctionId(requireId);
  12884. }
  12885. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  12886. this.state.maybeInArrowParameters = false;
  12887. this.scope.enter(2);
  12888. this.prodParam.enter(functionFlags(isAsync, node.generator));
  12889. if (!isDeclaration) {
  12890. node.id = this.parseFunctionId();
  12891. }
  12892. this.parseFunctionParams(node, false);
  12893. this.withSmartMixTopicForbiddingContext(() => {
  12894. this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
  12895. });
  12896. this.prodParam.exit();
  12897. this.scope.exit();
  12898. if (isDeclaration && !hangingDeclaration) {
  12899. this.registerFunctionStatementId(node);
  12900. }
  12901. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  12902. return node;
  12903. }
  12904. parseFunctionId(requireId) {
  12905. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  12906. }
  12907. parseFunctionParams(node, isConstructor) {
  12908. this.expect(10);
  12909. this.expressionScope.enter(newParameterDeclarationScope());
  12910. node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0));
  12911. this.expressionScope.exit();
  12912. }
  12913. registerFunctionStatementId(node) {
  12914. if (!node.id) return;
  12915. this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start);
  12916. }
  12917. parseClass(node, isStatement, optionalId) {
  12918. this.next();
  12919. const oldStrict = this.state.strict;
  12920. this.state.strict = true;
  12921. this.parseClassId(node, isStatement, optionalId);
  12922. this.parseClassSuper(node);
  12923. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  12924. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  12925. }
  12926. isClassProperty() {
  12927. return this.match(29) || this.match(13) || this.match(8);
  12928. }
  12929. isClassMethod() {
  12930. return this.match(10);
  12931. }
  12932. nameIsConstructor(key) {
  12933. return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor";
  12934. }
  12935. isNonstaticConstructor(method) {
  12936. return !method.computed && !method.static && this.nameIsConstructor(method.key);
  12937. }
  12938. parseClassBody(hadSuperClass, oldStrict) {
  12939. this.classScope.enter();
  12940. const state = {
  12941. hadConstructor: false,
  12942. hadSuperClass
  12943. };
  12944. let decorators = [];
  12945. const classBody = this.startNode();
  12946. classBody.body = [];
  12947. this.expect(5);
  12948. this.withSmartMixTopicForbiddingContext(() => {
  12949. while (!this.match(8)) {
  12950. if (this.eat(13)) {
  12951. if (decorators.length > 0) {
  12952. throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc);
  12953. }
  12954. continue;
  12955. }
  12956. if (this.match(26)) {
  12957. decorators.push(this.parseDecorator());
  12958. continue;
  12959. }
  12960. const member = this.startNode();
  12961. if (decorators.length) {
  12962. member.decorators = decorators;
  12963. this.resetStartLocationFromNode(member, decorators[0]);
  12964. decorators = [];
  12965. }
  12966. this.parseClassMember(classBody, member, state);
  12967. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  12968. this.raise(Errors.DecoratorConstructor, member);
  12969. }
  12970. }
  12971. });
  12972. this.state.strict = oldStrict;
  12973. this.next();
  12974. if (decorators.length) {
  12975. throw this.raise(Errors.TrailingDecorator, this.state.startLoc);
  12976. }
  12977. this.classScope.exit();
  12978. return this.finishNode(classBody, "ClassBody");
  12979. }
  12980. parseClassMemberFromModifier(classBody, member) {
  12981. const key = this.parseIdentifier(true);
  12982. if (this.isClassMethod()) {
  12983. const method = member;
  12984. method.kind = "method";
  12985. method.computed = false;
  12986. method.key = key;
  12987. method.static = false;
  12988. this.pushClassMethod(classBody, method, false, false, false, false);
  12989. return true;
  12990. } else if (this.isClassProperty()) {
  12991. const prop = member;
  12992. prop.computed = false;
  12993. prop.key = key;
  12994. prop.static = false;
  12995. classBody.body.push(this.parseClassProperty(prop));
  12996. return true;
  12997. }
  12998. this.resetPreviousNodeTrailingComments(key);
  12999. return false;
  13000. }
  13001. parseClassMember(classBody, member, state) {
  13002. const isStatic = this.isContextual(106);
  13003. if (isStatic) {
  13004. if (this.parseClassMemberFromModifier(classBody, member)) {
  13005. return;
  13006. }
  13007. if (this.eat(5)) {
  13008. this.parseClassStaticBlock(classBody, member);
  13009. return;
  13010. }
  13011. }
  13012. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  13013. }
  13014. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  13015. const publicMethod = member;
  13016. const privateMethod = member;
  13017. const publicProp = member;
  13018. const privateProp = member;
  13019. const accessorProp = member;
  13020. const method = publicMethod;
  13021. const publicMember = publicMethod;
  13022. member.static = isStatic;
  13023. this.parsePropertyNamePrefixOperator(member);
  13024. if (this.eat(55)) {
  13025. method.kind = "method";
  13026. const isPrivateName = this.match(138);
  13027. this.parseClassElementName(method);
  13028. if (isPrivateName) {
  13029. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  13030. return;
  13031. }
  13032. if (this.isNonstaticConstructor(publicMethod)) {
  13033. this.raise(Errors.ConstructorIsGenerator, publicMethod.key);
  13034. }
  13035. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  13036. return;
  13037. }
  13038. const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type);
  13039. const key = this.parseClassElementName(member);
  13040. const maybeContextualKw = isContextual ? key.name : null;
  13041. const isPrivate = this.isPrivateName(key);
  13042. const maybeQuestionTokenStartLoc = this.state.startLoc;
  13043. this.parsePostMemberNameModifiers(publicMember);
  13044. if (this.isClassMethod()) {
  13045. method.kind = "method";
  13046. if (isPrivate) {
  13047. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13048. return;
  13049. }
  13050. const isConstructor = this.isNonstaticConstructor(publicMethod);
  13051. let allowsDirectSuper = false;
  13052. if (isConstructor) {
  13053. publicMethod.kind = "constructor";
  13054. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  13055. this.raise(Errors.DuplicateConstructor, key);
  13056. }
  13057. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  13058. this.raise(Errors.OverrideOnConstructor, key);
  13059. }
  13060. state.hadConstructor = true;
  13061. allowsDirectSuper = state.hadSuperClass;
  13062. }
  13063. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  13064. } else if (this.isClassProperty()) {
  13065. if (isPrivate) {
  13066. this.pushClassPrivateProperty(classBody, privateProp);
  13067. } else {
  13068. this.pushClassProperty(classBody, publicProp);
  13069. }
  13070. } else if (maybeContextualKw === "async" && !this.isLineTerminator()) {
  13071. this.resetPreviousNodeTrailingComments(key);
  13072. const isGenerator = this.eat(55);
  13073. if (publicMember.optional) {
  13074. this.unexpected(maybeQuestionTokenStartLoc);
  13075. }
  13076. method.kind = "method";
  13077. const isPrivate = this.match(138);
  13078. this.parseClassElementName(method);
  13079. this.parsePostMemberNameModifiers(publicMember);
  13080. if (isPrivate) {
  13081. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  13082. } else {
  13083. if (this.isNonstaticConstructor(publicMethod)) {
  13084. this.raise(Errors.ConstructorIsAsync, publicMethod.key);
  13085. }
  13086. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  13087. }
  13088. } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) {
  13089. this.resetPreviousNodeTrailingComments(key);
  13090. method.kind = maybeContextualKw;
  13091. const isPrivate = this.match(138);
  13092. this.parseClassElementName(publicMethod);
  13093. if (isPrivate) {
  13094. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  13095. } else {
  13096. if (this.isNonstaticConstructor(publicMethod)) {
  13097. this.raise(Errors.ConstructorIsAccessor, publicMethod.key);
  13098. }
  13099. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  13100. }
  13101. this.checkGetterSetterParams(publicMethod);
  13102. } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) {
  13103. this.expectPlugin("decoratorAutoAccessors");
  13104. this.resetPreviousNodeTrailingComments(key);
  13105. const isPrivate = this.match(138);
  13106. this.parseClassElementName(publicProp);
  13107. this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);
  13108. } else if (this.isLineTerminator()) {
  13109. if (isPrivate) {
  13110. this.pushClassPrivateProperty(classBody, privateProp);
  13111. } else {
  13112. this.pushClassProperty(classBody, publicProp);
  13113. }
  13114. } else {
  13115. this.unexpected();
  13116. }
  13117. }
  13118. parseClassElementName(member) {
  13119. const {
  13120. type,
  13121. value
  13122. } = this.state;
  13123. if ((type === 132 || type === 133) && member.static && value === "prototype") {
  13124. this.raise(Errors.StaticPrototype, this.state.startLoc);
  13125. }
  13126. if (type === 138) {
  13127. if (value === "constructor") {
  13128. this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc);
  13129. }
  13130. const key = this.parsePrivateName();
  13131. member.key = key;
  13132. return key;
  13133. }
  13134. this.parsePropertyName(member);
  13135. return member.key;
  13136. }
  13137. parseClassStaticBlock(classBody, member) {
  13138. var _member$decorators;
  13139. this.scope.enter(64 | 128 | 16);
  13140. const oldLabels = this.state.labels;
  13141. this.state.labels = [];
  13142. this.prodParam.enter(0);
  13143. const body = member.body = [];
  13144. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  13145. this.prodParam.exit();
  13146. this.scope.exit();
  13147. this.state.labels = oldLabels;
  13148. classBody.body.push(this.finishNode(member, "StaticBlock"));
  13149. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  13150. this.raise(Errors.DecoratorStaticBlock, member);
  13151. }
  13152. }
  13153. pushClassProperty(classBody, prop) {
  13154. if (!prop.computed && this.nameIsConstructor(prop.key)) {
  13155. this.raise(Errors.ConstructorClassField, prop.key);
  13156. }
  13157. classBody.body.push(this.parseClassProperty(prop));
  13158. }
  13159. pushClassPrivateProperty(classBody, prop) {
  13160. const node = this.parseClassPrivateProperty(prop);
  13161. classBody.body.push(node);
  13162. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  13163. }
  13164. pushClassAccessorProperty(classBody, prop, isPrivate) {
  13165. if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) {
  13166. this.raise(Errors.ConstructorClassField, prop.key);
  13167. }
  13168. const node = this.parseClassAccessorProperty(prop);
  13169. classBody.body.push(node);
  13170. if (isPrivate) {
  13171. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  13172. }
  13173. }
  13174. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  13175. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  13176. }
  13177. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  13178. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  13179. classBody.body.push(node);
  13180. const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0;
  13181. this.declareClassPrivateMethodInScope(node, kind);
  13182. }
  13183. declareClassPrivateMethodInScope(node, kind) {
  13184. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start);
  13185. }
  13186. parsePostMemberNameModifiers(methodOrProp) {}
  13187. parseClassPrivateProperty(node) {
  13188. this.parseInitializer(node);
  13189. this.semicolon();
  13190. return this.finishNode(node, "ClassPrivateProperty");
  13191. }
  13192. parseClassProperty(node) {
  13193. this.parseInitializer(node);
  13194. this.semicolon();
  13195. return this.finishNode(node, "ClassProperty");
  13196. }
  13197. parseClassAccessorProperty(node) {
  13198. this.parseInitializer(node);
  13199. this.semicolon();
  13200. return this.finishNode(node, "ClassAccessorProperty");
  13201. }
  13202. parseInitializer(node) {
  13203. this.scope.enter(64 | 16);
  13204. this.expressionScope.enter(newExpressionScope());
  13205. this.prodParam.enter(0);
  13206. node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
  13207. this.expressionScope.exit();
  13208. this.prodParam.exit();
  13209. this.scope.exit();
  13210. }
  13211. parseClassId(node, isStatement, optionalId, bindingType = 8331) {
  13212. if (tokenIsIdentifier(this.state.type)) {
  13213. node.id = this.parseIdentifier();
  13214. if (isStatement) {
  13215. this.declareNameFromIdentifier(node.id, bindingType);
  13216. }
  13217. } else {
  13218. if (optionalId || !isStatement) {
  13219. node.id = null;
  13220. } else {
  13221. throw this.raise(Errors.MissingClassName, this.state.startLoc);
  13222. }
  13223. }
  13224. }
  13225. parseClassSuper(node) {
  13226. node.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  13227. }
  13228. parseExport(node, decorators) {
  13229. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true);
  13230. const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  13231. const parseAfterDefault = !hasDefault || this.eat(12);
  13232. const hasStar = parseAfterDefault && this.eatExportStar(node);
  13233. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  13234. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  13235. const isFromRequired = hasDefault || hasStar;
  13236. if (hasStar && !hasNamespace) {
  13237. if (hasDefault) this.unexpected();
  13238. if (decorators) {
  13239. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13240. }
  13241. this.parseExportFrom(node, true);
  13242. return this.finishNode(node, "ExportAllDeclaration");
  13243. }
  13244. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  13245. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {
  13246. this.unexpected(null, 5);
  13247. }
  13248. if (hasNamespace && parseAfterNamespace) {
  13249. this.unexpected(null, 98);
  13250. }
  13251. let hasDeclaration;
  13252. if (isFromRequired || hasSpecifiers) {
  13253. hasDeclaration = false;
  13254. if (decorators) {
  13255. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13256. }
  13257. this.parseExportFrom(node, isFromRequired);
  13258. } else {
  13259. hasDeclaration = this.maybeParseExportDeclaration(node);
  13260. }
  13261. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  13262. var _node2$declaration;
  13263. const node2 = node;
  13264. this.checkExport(node2, true, false, !!node2.source);
  13265. if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
  13266. this.maybeTakeDecorators(decorators, node2.declaration, node2);
  13267. } else if (decorators) {
  13268. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13269. }
  13270. return this.finishNode(node2, "ExportNamedDeclaration");
  13271. }
  13272. if (this.eat(65)) {
  13273. const node2 = node;
  13274. const decl = this.parseExportDefaultExpression();
  13275. node2.declaration = decl;
  13276. if (decl.type === "ClassDeclaration") {
  13277. this.maybeTakeDecorators(decorators, decl, node2);
  13278. } else if (decorators) {
  13279. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  13280. }
  13281. this.checkExport(node2, true, true);
  13282. return this.finishNode(node2, "ExportDefaultDeclaration");
  13283. }
  13284. this.unexpected(null, 5);
  13285. }
  13286. eatExportStar(node) {
  13287. return this.eat(55);
  13288. }
  13289. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  13290. if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) {
  13291. this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start);
  13292. const id = maybeDefaultIdentifier || this.parseIdentifier(true);
  13293. const specifier = this.startNodeAtNode(id);
  13294. specifier.exported = id;
  13295. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  13296. return true;
  13297. }
  13298. return false;
  13299. }
  13300. maybeParseExportNamespaceSpecifier(node) {
  13301. if (this.isContextual(93)) {
  13302. var _ref, _ref$specifiers;
  13303. (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = [];
  13304. const specifier = this.startNodeAt(this.state.lastTokStartLoc);
  13305. this.next();
  13306. specifier.exported = this.parseModuleExportName();
  13307. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  13308. return true;
  13309. }
  13310. return false;
  13311. }
  13312. maybeParseExportNamedSpecifiers(node) {
  13313. if (this.match(5)) {
  13314. const node2 = node;
  13315. if (!node2.specifiers) node2.specifiers = [];
  13316. const isTypeExport = node2.exportKind === "type";
  13317. node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  13318. node2.source = null;
  13319. node2.declaration = null;
  13320. if (this.hasPlugin("importAssertions")) {
  13321. node2.assertions = [];
  13322. }
  13323. return true;
  13324. }
  13325. return false;
  13326. }
  13327. maybeParseExportDeclaration(node) {
  13328. if (this.shouldParseExportDeclaration()) {
  13329. node.specifiers = [];
  13330. node.source = null;
  13331. if (this.hasPlugin("importAssertions")) {
  13332. node.assertions = [];
  13333. }
  13334. node.declaration = this.parseExportDeclaration(node);
  13335. return true;
  13336. }
  13337. return false;
  13338. }
  13339. isAsyncFunction() {
  13340. if (!this.isContextual(95)) return false;
  13341. const next = this.nextTokenInLineStart();
  13342. return this.isUnparsedContextual(next, "function");
  13343. }
  13344. parseExportDefaultExpression() {
  13345. const expr = this.startNode();
  13346. if (this.match(68)) {
  13347. this.next();
  13348. return this.parseFunction(expr, 1 | 4);
  13349. } else if (this.isAsyncFunction()) {
  13350. this.next();
  13351. this.next();
  13352. return this.parseFunction(expr, 1 | 4 | 8);
  13353. }
  13354. if (this.match(80)) {
  13355. return this.parseClass(expr, true, true);
  13356. }
  13357. if (this.match(26)) {
  13358. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  13359. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  13360. }
  13361. return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
  13362. }
  13363. if (this.match(75) || this.match(74) || this.isLet()) {
  13364. throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc);
  13365. }
  13366. const res = this.parseMaybeAssignAllowIn();
  13367. this.semicolon();
  13368. return res;
  13369. }
  13370. parseExportDeclaration(node) {
  13371. if (this.match(80)) {
  13372. const node = this.parseClass(this.startNode(), true, false);
  13373. return node;
  13374. }
  13375. return this.parseStatementListItem();
  13376. }
  13377. isExportDefaultSpecifier() {
  13378. const {
  13379. type
  13380. } = this.state;
  13381. if (tokenIsIdentifier(type)) {
  13382. if (type === 95 && !this.state.containsEsc || type === 100) {
  13383. return false;
  13384. }
  13385. if ((type === 130 || type === 129) && !this.state.containsEsc) {
  13386. const {
  13387. type: nextType
  13388. } = this.lookahead();
  13389. if (tokenIsIdentifier(nextType) && nextType !== 98 || nextType === 5) {
  13390. this.expectOnePlugin(["flow", "typescript"]);
  13391. return false;
  13392. }
  13393. }
  13394. } else if (!this.match(65)) {
  13395. return false;
  13396. }
  13397. const next = this.nextTokenStart();
  13398. const hasFrom = this.isUnparsedContextual(next, "from");
  13399. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  13400. return true;
  13401. }
  13402. if (this.match(65) && hasFrom) {
  13403. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  13404. return nextAfterFrom === 34 || nextAfterFrom === 39;
  13405. }
  13406. return false;
  13407. }
  13408. parseExportFrom(node, expect) {
  13409. if (this.eatContextual(98)) {
  13410. node.source = this.parseImportSource();
  13411. this.checkExport(node);
  13412. this.maybeParseImportAttributes(node);
  13413. this.checkJSONModuleImport(node);
  13414. } else if (expect) {
  13415. this.unexpected();
  13416. }
  13417. this.semicolon();
  13418. }
  13419. shouldParseExportDeclaration() {
  13420. const {
  13421. type
  13422. } = this.state;
  13423. if (type === 26) {
  13424. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  13425. if (this.hasPlugin("decorators")) {
  13426. if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  13427. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  13428. }
  13429. return true;
  13430. }
  13431. }
  13432. if (this.isContextual(107)) {
  13433. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  13434. return true;
  13435. }
  13436. if (this.isContextual(96) && this.startsAwaitUsing()) {
  13437. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  13438. return true;
  13439. }
  13440. return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  13441. }
  13442. checkExport(node, checkNames, isDefault, isFrom) {
  13443. if (checkNames) {
  13444. var _node$specifiers;
  13445. if (isDefault) {
  13446. this.checkDuplicateExports(node, "default");
  13447. if (this.hasPlugin("exportDefaultFrom")) {
  13448. var _declaration$extra;
  13449. const declaration = node.declaration;
  13450. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  13451. this.raise(Errors.ExportDefaultFromAsIdentifier, declaration);
  13452. }
  13453. }
  13454. } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  13455. for (const specifier of node.specifiers) {
  13456. const {
  13457. exported
  13458. } = specifier;
  13459. const exportName = exported.type === "Identifier" ? exported.name : exported.value;
  13460. this.checkDuplicateExports(specifier, exportName);
  13461. if (!isFrom && specifier.local) {
  13462. const {
  13463. local
  13464. } = specifier;
  13465. if (local.type !== "Identifier") {
  13466. this.raise(Errors.ExportBindingIsString, specifier, {
  13467. localName: local.value,
  13468. exportName
  13469. });
  13470. } else {
  13471. this.checkReservedWord(local.name, local.loc.start, true, false);
  13472. this.scope.checkLocalExport(local);
  13473. }
  13474. }
  13475. }
  13476. } else if (node.declaration) {
  13477. const decl = node.declaration;
  13478. if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
  13479. const {
  13480. id
  13481. } = decl;
  13482. if (!id) throw new Error("Assertion failure");
  13483. this.checkDuplicateExports(node, id.name);
  13484. } else if (decl.type === "VariableDeclaration") {
  13485. for (const declaration of decl.declarations) {
  13486. this.checkDeclaration(declaration.id);
  13487. }
  13488. }
  13489. }
  13490. }
  13491. }
  13492. checkDeclaration(node) {
  13493. if (node.type === "Identifier") {
  13494. this.checkDuplicateExports(node, node.name);
  13495. } else if (node.type === "ObjectPattern") {
  13496. for (const prop of node.properties) {
  13497. this.checkDeclaration(prop);
  13498. }
  13499. } else if (node.type === "ArrayPattern") {
  13500. for (const elem of node.elements) {
  13501. if (elem) {
  13502. this.checkDeclaration(elem);
  13503. }
  13504. }
  13505. } else if (node.type === "ObjectProperty") {
  13506. this.checkDeclaration(node.value);
  13507. } else if (node.type === "RestElement") {
  13508. this.checkDeclaration(node.argument);
  13509. } else if (node.type === "AssignmentPattern") {
  13510. this.checkDeclaration(node.left);
  13511. }
  13512. }
  13513. checkDuplicateExports(node, exportName) {
  13514. if (this.exportedIdentifiers.has(exportName)) {
  13515. if (exportName === "default") {
  13516. this.raise(Errors.DuplicateDefaultExport, node);
  13517. } else {
  13518. this.raise(Errors.DuplicateExport, node, {
  13519. exportName
  13520. });
  13521. }
  13522. }
  13523. this.exportedIdentifiers.add(exportName);
  13524. }
  13525. parseExportSpecifiers(isInTypeExport) {
  13526. const nodes = [];
  13527. let first = true;
  13528. this.expect(5);
  13529. while (!this.eat(8)) {
  13530. if (first) {
  13531. first = false;
  13532. } else {
  13533. this.expect(12);
  13534. if (this.eat(8)) break;
  13535. }
  13536. const isMaybeTypeOnly = this.isContextual(130);
  13537. const isString = this.match(133);
  13538. const node = this.startNode();
  13539. node.local = this.parseModuleExportName();
  13540. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  13541. }
  13542. return nodes;
  13543. }
  13544. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  13545. if (this.eatContextual(93)) {
  13546. node.exported = this.parseModuleExportName();
  13547. } else if (isString) {
  13548. node.exported = cloneStringLiteral(node.local);
  13549. } else if (!node.exported) {
  13550. node.exported = cloneIdentifier(node.local);
  13551. }
  13552. return this.finishNode(node, "ExportSpecifier");
  13553. }
  13554. parseModuleExportName() {
  13555. if (this.match(133)) {
  13556. const result = this.parseStringLiteral(this.state.value);
  13557. const surrogate = loneSurrogate.exec(result.value);
  13558. if (surrogate) {
  13559. this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {
  13560. surrogateCharCode: surrogate[0].charCodeAt(0)
  13561. });
  13562. }
  13563. return result;
  13564. }
  13565. return this.parseIdentifier(true);
  13566. }
  13567. isJSONModuleImport(node) {
  13568. if (node.assertions != null) {
  13569. return node.assertions.some(({
  13570. key,
  13571. value
  13572. }) => {
  13573. return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
  13574. });
  13575. }
  13576. return false;
  13577. }
  13578. checkImportReflection(node) {
  13579. const {
  13580. specifiers
  13581. } = node;
  13582. const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null;
  13583. if (node.phase === "source") {
  13584. if (singleBindingType !== "ImportDefaultSpecifier") {
  13585. this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start);
  13586. }
  13587. } else if (node.phase === "defer") {
  13588. if (singleBindingType !== "ImportNamespaceSpecifier") {
  13589. this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start);
  13590. }
  13591. } else if (node.module) {
  13592. var _node$assertions;
  13593. if (singleBindingType !== "ImportDefaultSpecifier") {
  13594. this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start);
  13595. }
  13596. if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) {
  13597. this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start);
  13598. }
  13599. }
  13600. }
  13601. checkJSONModuleImport(node) {
  13602. if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") {
  13603. const {
  13604. specifiers
  13605. } = node;
  13606. if (specifiers != null) {
  13607. const nonDefaultNamedSpecifier = specifiers.find(specifier => {
  13608. let imported;
  13609. if (specifier.type === "ExportSpecifier") {
  13610. imported = specifier.local;
  13611. } else if (specifier.type === "ImportSpecifier") {
  13612. imported = specifier.imported;
  13613. }
  13614. if (imported !== undefined) {
  13615. return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
  13616. }
  13617. });
  13618. if (nonDefaultNamedSpecifier !== undefined) {
  13619. this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start);
  13620. }
  13621. }
  13622. }
  13623. }
  13624. isPotentialImportPhase(isExport) {
  13625. if (isExport) return false;
  13626. return this.isContextual(105) || this.isContextual(97) || this.isContextual(127);
  13627. }
  13628. applyImportPhase(node, isExport, phase, loc) {
  13629. if (isExport) {
  13630. return;
  13631. }
  13632. if (phase === "module") {
  13633. this.expectPlugin("importReflection", loc);
  13634. node.module = true;
  13635. } else if (this.hasPlugin("importReflection")) {
  13636. node.module = false;
  13637. }
  13638. if (phase === "source") {
  13639. this.expectPlugin("sourcePhaseImports", loc);
  13640. node.phase = "source";
  13641. } else if (phase === "defer") {
  13642. this.expectPlugin("deferredImportEvaluation", loc);
  13643. node.phase = "defer";
  13644. } else if (this.hasPlugin("sourcePhaseImports")) {
  13645. node.phase = null;
  13646. }
  13647. }
  13648. parseMaybeImportPhase(node, isExport) {
  13649. if (!this.isPotentialImportPhase(isExport)) {
  13650. this.applyImportPhase(node, isExport, null);
  13651. return null;
  13652. }
  13653. const phaseIdentifier = this.parseIdentifier(true);
  13654. const {
  13655. type
  13656. } = this.state;
  13657. const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  13658. if (isImportPhase) {
  13659. this.resetPreviousIdentifierLeadingComments(phaseIdentifier);
  13660. this.applyImportPhase(node, isExport, phaseIdentifier.name, phaseIdentifier.loc.start);
  13661. return null;
  13662. } else {
  13663. this.applyImportPhase(node, isExport, null);
  13664. return phaseIdentifier;
  13665. }
  13666. }
  13667. isPrecedingIdImportPhase(phase) {
  13668. const {
  13669. type
  13670. } = this.state;
  13671. return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  13672. }
  13673. parseImport(node) {
  13674. if (this.match(133)) {
  13675. return this.parseImportSourceAndAttributes(node);
  13676. }
  13677. return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false));
  13678. }
  13679. parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) {
  13680. node.specifiers = [];
  13681. const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier);
  13682. const parseNext = !hasDefault || this.eat(12);
  13683. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  13684. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  13685. this.expectContextual(98);
  13686. return this.parseImportSourceAndAttributes(node);
  13687. }
  13688. parseImportSourceAndAttributes(node) {
  13689. var _node$specifiers2;
  13690. (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
  13691. node.source = this.parseImportSource();
  13692. this.maybeParseImportAttributes(node);
  13693. this.checkImportReflection(node);
  13694. this.checkJSONModuleImport(node);
  13695. this.semicolon();
  13696. return this.finishNode(node, "ImportDeclaration");
  13697. }
  13698. parseImportSource() {
  13699. if (!this.match(133)) this.unexpected();
  13700. return this.parseExprAtom();
  13701. }
  13702. parseImportSpecifierLocal(node, specifier, type) {
  13703. specifier.local = this.parseIdentifier();
  13704. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  13705. }
  13706. finishImportSpecifier(specifier, type, bindingType = 8201) {
  13707. this.checkLVal(specifier.local, {
  13708. type
  13709. }, bindingType);
  13710. return this.finishNode(specifier, type);
  13711. }
  13712. parseImportAttributes() {
  13713. this.expect(5);
  13714. const attrs = [];
  13715. const attrNames = new Set();
  13716. do {
  13717. if (this.match(8)) {
  13718. break;
  13719. }
  13720. const node = this.startNode();
  13721. const keyName = this.state.value;
  13722. if (attrNames.has(keyName)) {
  13723. this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, {
  13724. key: keyName
  13725. });
  13726. }
  13727. attrNames.add(keyName);
  13728. if (this.match(133)) {
  13729. node.key = this.parseStringLiteral(keyName);
  13730. } else {
  13731. node.key = this.parseIdentifier(true);
  13732. }
  13733. this.expect(14);
  13734. if (!this.match(133)) {
  13735. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  13736. }
  13737. node.value = this.parseStringLiteral(this.state.value);
  13738. attrs.push(this.finishNode(node, "ImportAttribute"));
  13739. } while (this.eat(12));
  13740. this.expect(8);
  13741. return attrs;
  13742. }
  13743. parseModuleAttributes() {
  13744. const attrs = [];
  13745. const attributes = new Set();
  13746. do {
  13747. const node = this.startNode();
  13748. node.key = this.parseIdentifier(true);
  13749. if (node.key.name !== "type") {
  13750. this.raise(Errors.ModuleAttributeDifferentFromType, node.key);
  13751. }
  13752. if (attributes.has(node.key.name)) {
  13753. this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, {
  13754. key: node.key.name
  13755. });
  13756. }
  13757. attributes.add(node.key.name);
  13758. this.expect(14);
  13759. if (!this.match(133)) {
  13760. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  13761. }
  13762. node.value = this.parseStringLiteral(this.state.value);
  13763. attrs.push(this.finishNode(node, "ImportAttribute"));
  13764. } while (this.eat(12));
  13765. return attrs;
  13766. }
  13767. maybeParseImportAttributes(node) {
  13768. let attributes;
  13769. let useWith = false;
  13770. if (this.match(76)) {
  13771. if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) {
  13772. return;
  13773. }
  13774. this.next();
  13775. {
  13776. if (this.hasPlugin("moduleAttributes")) {
  13777. attributes = this.parseModuleAttributes();
  13778. } else {
  13779. this.expectImportAttributesPlugin();
  13780. attributes = this.parseImportAttributes();
  13781. }
  13782. }
  13783. useWith = true;
  13784. } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
  13785. if (this.hasPlugin("importAttributes")) {
  13786. if (this.getPluginOption("importAttributes", "deprecatedAssertSyntax") !== true) {
  13787. this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc);
  13788. }
  13789. this.addExtra(node, "deprecatedAssertSyntax", true);
  13790. } else {
  13791. this.expectOnePlugin(["importAttributes", "importAssertions"]);
  13792. }
  13793. this.next();
  13794. attributes = this.parseImportAttributes();
  13795. } else if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) {
  13796. attributes = [];
  13797. } else {
  13798. if (this.hasPlugin("moduleAttributes")) {
  13799. attributes = [];
  13800. } else return;
  13801. }
  13802. if (!useWith && this.hasPlugin("importAssertions")) {
  13803. node.assertions = attributes;
  13804. } else {
  13805. node.attributes = attributes;
  13806. }
  13807. }
  13808. maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) {
  13809. if (maybeDefaultIdentifier) {
  13810. const specifier = this.startNodeAtNode(maybeDefaultIdentifier);
  13811. specifier.local = maybeDefaultIdentifier;
  13812. node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier"));
  13813. return true;
  13814. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  13815. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier");
  13816. return true;
  13817. }
  13818. return false;
  13819. }
  13820. maybeParseStarImportSpecifier(node) {
  13821. if (this.match(55)) {
  13822. const specifier = this.startNode();
  13823. this.next();
  13824. this.expectContextual(93);
  13825. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier");
  13826. return true;
  13827. }
  13828. return false;
  13829. }
  13830. parseNamedImportSpecifiers(node) {
  13831. let first = true;
  13832. this.expect(5);
  13833. while (!this.eat(8)) {
  13834. if (first) {
  13835. first = false;
  13836. } else {
  13837. if (this.eat(14)) {
  13838. throw this.raise(Errors.DestructureNamedImport, this.state.startLoc);
  13839. }
  13840. this.expect(12);
  13841. if (this.eat(8)) break;
  13842. }
  13843. const specifier = this.startNode();
  13844. const importedIsString = this.match(133);
  13845. const isMaybeTypeOnly = this.isContextual(130);
  13846. specifier.imported = this.parseModuleExportName();
  13847. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined);
  13848. node.specifiers.push(importSpecifier);
  13849. }
  13850. }
  13851. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  13852. if (this.eatContextual(93)) {
  13853. specifier.local = this.parseIdentifier();
  13854. } else {
  13855. const {
  13856. imported
  13857. } = specifier;
  13858. if (importedIsString) {
  13859. throw this.raise(Errors.ImportBindingIsString, specifier, {
  13860. importName: imported.value
  13861. });
  13862. }
  13863. this.checkReservedWord(imported.name, specifier.loc.start, true, true);
  13864. if (!specifier.local) {
  13865. specifier.local = cloneIdentifier(imported);
  13866. }
  13867. }
  13868. return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  13869. }
  13870. isThisParam(param) {
  13871. return param.type === "Identifier" && param.name === "this";
  13872. }
  13873. }
  13874. class Parser extends StatementParser {
  13875. constructor(options, input, pluginsMap) {
  13876. options = getOptions(options);
  13877. super(options, input);
  13878. this.options = options;
  13879. this.initializeScopes();
  13880. this.plugins = pluginsMap;
  13881. this.filename = options.sourceFilename;
  13882. }
  13883. getScopeHandler() {
  13884. return ScopeHandler;
  13885. }
  13886. parse() {
  13887. this.enterInitialScopes();
  13888. const file = this.startNode();
  13889. const program = this.startNode();
  13890. this.nextToken();
  13891. file.errors = null;
  13892. this.parseTopLevel(file, program);
  13893. file.errors = this.state.errors;
  13894. file.comments.length = this.state.commentsLen;
  13895. return file;
  13896. }
  13897. }
  13898. function parse(input, options) {
  13899. var _options;
  13900. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  13901. options = Object.assign({}, options);
  13902. try {
  13903. options.sourceType = "module";
  13904. const parser = getParser(options, input);
  13905. const ast = parser.parse();
  13906. if (parser.sawUnambiguousESM) {
  13907. return ast;
  13908. }
  13909. if (parser.ambiguousScriptDifferentAst) {
  13910. try {
  13911. options.sourceType = "script";
  13912. return getParser(options, input).parse();
  13913. } catch (_unused) {}
  13914. } else {
  13915. ast.program.sourceType = "script";
  13916. }
  13917. return ast;
  13918. } catch (moduleError) {
  13919. try {
  13920. options.sourceType = "script";
  13921. return getParser(options, input).parse();
  13922. } catch (_unused2) {}
  13923. throw moduleError;
  13924. }
  13925. } else {
  13926. return getParser(options, input).parse();
  13927. }
  13928. }
  13929. function parseExpression(input, options) {
  13930. const parser = getParser(options, input);
  13931. if (parser.options.strictMode) {
  13932. parser.state.strict = true;
  13933. }
  13934. return parser.getExpression();
  13935. }
  13936. function generateExportedTokenTypes(internalTokenTypes) {
  13937. const tokenTypes = {};
  13938. for (const typeName of Object.keys(internalTokenTypes)) {
  13939. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  13940. }
  13941. return tokenTypes;
  13942. }
  13943. const tokTypes = generateExportedTokenTypes(tt);
  13944. function getParser(options, input) {
  13945. let cls = Parser;
  13946. const pluginsMap = new Map();
  13947. if (options != null && options.plugins) {
  13948. for (const plugin of options.plugins) {
  13949. let name, opts;
  13950. if (typeof plugin === "string") {
  13951. name = plugin;
  13952. } else {
  13953. [name, opts] = plugin;
  13954. }
  13955. if (!pluginsMap.has(name)) {
  13956. pluginsMap.set(name, opts || {});
  13957. }
  13958. }
  13959. validatePlugins(pluginsMap);
  13960. cls = getParserClass(pluginsMap);
  13961. }
  13962. return new cls(options, input, pluginsMap);
  13963. }
  13964. const parserClassCache = new Map();
  13965. function getParserClass(pluginsMap) {
  13966. const pluginList = [];
  13967. for (const name of mixinPluginNames) {
  13968. if (pluginsMap.has(name)) {
  13969. pluginList.push(name);
  13970. }
  13971. }
  13972. const key = pluginList.join("|");
  13973. let cls = parserClassCache.get(key);
  13974. if (!cls) {
  13975. cls = Parser;
  13976. for (const plugin of pluginList) {
  13977. cls = mixinPlugins[plugin](cls);
  13978. }
  13979. parserClassCache.set(key, cls);
  13980. }
  13981. return cls;
  13982. }
  13983. exports.parse = parse;
  13984. exports.parseExpression = parseExpression;
  13985. exports.tokTypes = tokTypes;
  13986. //# sourceMappingURL=index.js.map