Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const beforeExpr = true;
  4. const startsExpr = true;
  5. const isLoop = true;
  6. const isAssign = true;
  7. const prefix = true;
  8. const postfix = true;
  9. class TokenType {
  10. constructor(label, conf = {}) {
  11. this.label = label;
  12. this.keyword = conf.keyword;
  13. this.beforeExpr = !!conf.beforeExpr;
  14. this.startsExpr = !!conf.startsExpr;
  15. this.rightAssociative = !!conf.rightAssociative;
  16. this.isLoop = !!conf.isLoop;
  17. this.isAssign = !!conf.isAssign;
  18. this.prefix = !!conf.prefix;
  19. this.postfix = !!conf.postfix;
  20. this.binop = conf.binop != null ? conf.binop : null;
  21. this.updateContext = null;
  22. }
  23. }
  24. const keywords = new Map();
  25. function createKeyword(name, options = {}) {
  26. options.keyword = name;
  27. const token = new TokenType(name, options);
  28. keywords.set(name, token);
  29. return token;
  30. }
  31. function createBinop(name, binop) {
  32. return new TokenType(name, {
  33. beforeExpr,
  34. binop
  35. });
  36. }
  37. const types = {
  38. num: new TokenType("num", {
  39. startsExpr
  40. }),
  41. bigint: new TokenType("bigint", {
  42. startsExpr
  43. }),
  44. regexp: new TokenType("regexp", {
  45. startsExpr
  46. }),
  47. string: new TokenType("string", {
  48. startsExpr
  49. }),
  50. name: new TokenType("name", {
  51. startsExpr
  52. }),
  53. eof: new TokenType("eof"),
  54. bracketL: new TokenType("[", {
  55. beforeExpr,
  56. startsExpr
  57. }),
  58. bracketHashL: new TokenType("#[", {
  59. beforeExpr,
  60. startsExpr
  61. }),
  62. bracketBarL: new TokenType("[|", {
  63. beforeExpr,
  64. startsExpr
  65. }),
  66. bracketR: new TokenType("]"),
  67. bracketBarR: new TokenType("|]"),
  68. braceL: new TokenType("{", {
  69. beforeExpr,
  70. startsExpr
  71. }),
  72. braceBarL: new TokenType("{|", {
  73. beforeExpr,
  74. startsExpr
  75. }),
  76. braceHashL: new TokenType("#{", {
  77. beforeExpr,
  78. startsExpr
  79. }),
  80. braceR: new TokenType("}"),
  81. braceBarR: new TokenType("|}"),
  82. parenL: new TokenType("(", {
  83. beforeExpr,
  84. startsExpr
  85. }),
  86. parenR: new TokenType(")"),
  87. comma: new TokenType(",", {
  88. beforeExpr
  89. }),
  90. semi: new TokenType(";", {
  91. beforeExpr
  92. }),
  93. colon: new TokenType(":", {
  94. beforeExpr
  95. }),
  96. doubleColon: new TokenType("::", {
  97. beforeExpr
  98. }),
  99. dot: new TokenType("."),
  100. question: new TokenType("?", {
  101. beforeExpr
  102. }),
  103. questionDot: new TokenType("?."),
  104. arrow: new TokenType("=>", {
  105. beforeExpr
  106. }),
  107. template: new TokenType("template"),
  108. ellipsis: new TokenType("...", {
  109. beforeExpr
  110. }),
  111. backQuote: new TokenType("`", {
  112. startsExpr
  113. }),
  114. dollarBraceL: new TokenType("${", {
  115. beforeExpr,
  116. startsExpr
  117. }),
  118. at: new TokenType("@"),
  119. hash: new TokenType("#", {
  120. startsExpr
  121. }),
  122. interpreterDirective: new TokenType("#!..."),
  123. eq: new TokenType("=", {
  124. beforeExpr,
  125. isAssign
  126. }),
  127. assign: new TokenType("_=", {
  128. beforeExpr,
  129. isAssign
  130. }),
  131. incDec: new TokenType("++/--", {
  132. prefix,
  133. postfix,
  134. startsExpr
  135. }),
  136. bang: new TokenType("!", {
  137. beforeExpr,
  138. prefix,
  139. startsExpr
  140. }),
  141. tilde: new TokenType("~", {
  142. beforeExpr,
  143. prefix,
  144. startsExpr
  145. }),
  146. pipeline: createBinop("|>", 0),
  147. nullishCoalescing: createBinop("??", 1),
  148. logicalOR: createBinop("||", 1),
  149. logicalAND: createBinop("&&", 2),
  150. bitwiseOR: createBinop("|", 3),
  151. bitwiseXOR: createBinop("^", 4),
  152. bitwiseAND: createBinop("&", 5),
  153. equality: createBinop("==/!=/===/!==", 6),
  154. relational: createBinop("</>/<=/>=", 7),
  155. bitShift: createBinop("<</>>/>>>", 8),
  156. plusMin: new TokenType("+/-", {
  157. beforeExpr,
  158. binop: 9,
  159. prefix,
  160. startsExpr
  161. }),
  162. modulo: new TokenType("%", {
  163. beforeExpr,
  164. binop: 10,
  165. startsExpr
  166. }),
  167. star: createBinop("*", 10),
  168. slash: createBinop("/", 10),
  169. exponent: new TokenType("**", {
  170. beforeExpr,
  171. binop: 11,
  172. rightAssociative: true
  173. }),
  174. _break: createKeyword("break"),
  175. _case: createKeyword("case", {
  176. beforeExpr
  177. }),
  178. _catch: createKeyword("catch"),
  179. _continue: createKeyword("continue"),
  180. _debugger: createKeyword("debugger"),
  181. _default: createKeyword("default", {
  182. beforeExpr
  183. }),
  184. _do: createKeyword("do", {
  185. isLoop,
  186. beforeExpr
  187. }),
  188. _else: createKeyword("else", {
  189. beforeExpr
  190. }),
  191. _finally: createKeyword("finally"),
  192. _for: createKeyword("for", {
  193. isLoop
  194. }),
  195. _function: createKeyword("function", {
  196. startsExpr
  197. }),
  198. _if: createKeyword("if"),
  199. _return: createKeyword("return", {
  200. beforeExpr
  201. }),
  202. _switch: createKeyword("switch"),
  203. _throw: createKeyword("throw", {
  204. beforeExpr,
  205. prefix,
  206. startsExpr
  207. }),
  208. _try: createKeyword("try"),
  209. _var: createKeyword("var"),
  210. _const: createKeyword("const"),
  211. _while: createKeyword("while", {
  212. isLoop
  213. }),
  214. _with: createKeyword("with"),
  215. _new: createKeyword("new", {
  216. beforeExpr,
  217. startsExpr
  218. }),
  219. _this: createKeyword("this", {
  220. startsExpr
  221. }),
  222. _super: createKeyword("super", {
  223. startsExpr
  224. }),
  225. _class: createKeyword("class", {
  226. startsExpr
  227. }),
  228. _extends: createKeyword("extends", {
  229. beforeExpr
  230. }),
  231. _export: createKeyword("export"),
  232. _import: createKeyword("import", {
  233. startsExpr
  234. }),
  235. _null: createKeyword("null", {
  236. startsExpr
  237. }),
  238. _true: createKeyword("true", {
  239. startsExpr
  240. }),
  241. _false: createKeyword("false", {
  242. startsExpr
  243. }),
  244. _in: createKeyword("in", {
  245. beforeExpr,
  246. binop: 7
  247. }),
  248. _instanceof: createKeyword("instanceof", {
  249. beforeExpr,
  250. binop: 7
  251. }),
  252. _typeof: createKeyword("typeof", {
  253. beforeExpr,
  254. prefix,
  255. startsExpr
  256. }),
  257. _void: createKeyword("void", {
  258. beforeExpr,
  259. prefix,
  260. startsExpr
  261. }),
  262. _delete: createKeyword("delete", {
  263. beforeExpr,
  264. prefix,
  265. startsExpr
  266. })
  267. };
  268. const SCOPE_OTHER = 0b00000000,
  269. SCOPE_PROGRAM = 0b00000001,
  270. SCOPE_FUNCTION = 0b00000010,
  271. SCOPE_ARROW = 0b00000100,
  272. SCOPE_SIMPLE_CATCH = 0b00001000,
  273. SCOPE_SUPER = 0b00010000,
  274. SCOPE_DIRECT_SUPER = 0b00100000,
  275. SCOPE_CLASS = 0b01000000,
  276. SCOPE_TS_MODULE = 0b10000000,
  277. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  278. const BIND_KIND_VALUE = 0b00000000001,
  279. BIND_KIND_TYPE = 0b00000000010,
  280. BIND_SCOPE_VAR = 0b00000000100,
  281. BIND_SCOPE_LEXICAL = 0b00000001000,
  282. BIND_SCOPE_FUNCTION = 0b00000010000,
  283. BIND_FLAGS_NONE = 0b00001000000,
  284. BIND_FLAGS_CLASS = 0b00010000000,
  285. BIND_FLAGS_TS_ENUM = 0b00100000000,
  286. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  287. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  288. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  289. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  290. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  291. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  292. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  293. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  294. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  295. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  296. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  297. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  298. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  299. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  300. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  301. CLASS_ELEMENT_KIND_GETTER = 0b010,
  302. CLASS_ELEMENT_KIND_SETTER = 0b001,
  303. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  304. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  305. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  306. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  307. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  308. CLASS_ELEMENT_OTHER = 0;
  309. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  310. const lineBreakG = new RegExp(lineBreak.source, "g");
  311. function isNewLine(code) {
  312. switch (code) {
  313. case 10:
  314. case 13:
  315. case 8232:
  316. case 8233:
  317. return true;
  318. default:
  319. return false;
  320. }
  321. }
  322. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  323. function isWhitespace(code) {
  324. switch (code) {
  325. case 0x0009:
  326. case 0x000b:
  327. case 0x000c:
  328. case 32:
  329. case 160:
  330. case 5760:
  331. case 0x2000:
  332. case 0x2001:
  333. case 0x2002:
  334. case 0x2003:
  335. case 0x2004:
  336. case 0x2005:
  337. case 0x2006:
  338. case 0x2007:
  339. case 0x2008:
  340. case 0x2009:
  341. case 0x200a:
  342. case 0x202f:
  343. case 0x205f:
  344. case 0x3000:
  345. case 0xfeff:
  346. return true;
  347. default:
  348. return false;
  349. }
  350. }
  351. class Position {
  352. constructor(line, col) {
  353. this.line = line;
  354. this.column = col;
  355. }
  356. }
  357. class SourceLocation {
  358. constructor(start, end) {
  359. this.start = start;
  360. this.end = end;
  361. }
  362. }
  363. function getLineInfo(input, offset) {
  364. let line = 1;
  365. let lineStart = 0;
  366. let match;
  367. lineBreakG.lastIndex = 0;
  368. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  369. line++;
  370. lineStart = lineBreakG.lastIndex;
  371. }
  372. return new Position(line, offset - lineStart);
  373. }
  374. class BaseParser {
  375. constructor() {
  376. this.sawUnambiguousESM = false;
  377. this.ambiguousScriptDifferentAst = false;
  378. }
  379. hasPlugin(name) {
  380. return this.plugins.has(name);
  381. }
  382. getPluginOption(plugin, name) {
  383. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  384. }
  385. }
  386. function last(stack) {
  387. return stack[stack.length - 1];
  388. }
  389. class CommentsParser extends BaseParser {
  390. addComment(comment) {
  391. if (this.filename) comment.loc.filename = this.filename;
  392. this.state.trailingComments.push(comment);
  393. this.state.leadingComments.push(comment);
  394. }
  395. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  396. if (this.state.leadingComments.length === 0) {
  397. return;
  398. }
  399. let lastElement = null;
  400. let i = elements.length;
  401. while (lastElement === null && i > 0) {
  402. lastElement = elements[--i];
  403. }
  404. if (lastElement === null) {
  405. return;
  406. }
  407. for (let j = 0; j < this.state.leadingComments.length; j++) {
  408. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  409. this.state.leadingComments.splice(j, 1);
  410. j--;
  411. }
  412. }
  413. const newTrailingComments = [];
  414. for (let i = 0; i < this.state.leadingComments.length; i++) {
  415. const leadingComment = this.state.leadingComments[i];
  416. if (leadingComment.end < node.end) {
  417. newTrailingComments.push(leadingComment);
  418. if (!takeAllComments) {
  419. this.state.leadingComments.splice(i, 1);
  420. i--;
  421. }
  422. } else {
  423. if (node.trailingComments === undefined) {
  424. node.trailingComments = [];
  425. }
  426. node.trailingComments.push(leadingComment);
  427. }
  428. }
  429. if (takeAllComments) this.state.leadingComments = [];
  430. if (newTrailingComments.length > 0) {
  431. lastElement.trailingComments = newTrailingComments;
  432. } else if (lastElement.trailingComments !== undefined) {
  433. lastElement.trailingComments = [];
  434. }
  435. }
  436. processComment(node) {
  437. if (node.type === "Program" && node.body.length > 0) return;
  438. const stack = this.state.commentStack;
  439. let firstChild, lastChild, trailingComments, i, j;
  440. if (this.state.trailingComments.length > 0) {
  441. if (this.state.trailingComments[0].start >= node.end) {
  442. trailingComments = this.state.trailingComments;
  443. this.state.trailingComments = [];
  444. } else {
  445. this.state.trailingComments.length = 0;
  446. }
  447. } else if (stack.length > 0) {
  448. const lastInStack = last(stack);
  449. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  450. trailingComments = lastInStack.trailingComments;
  451. delete lastInStack.trailingComments;
  452. }
  453. }
  454. if (stack.length > 0 && last(stack).start >= node.start) {
  455. firstChild = stack.pop();
  456. }
  457. while (stack.length > 0 && last(stack).start >= node.start) {
  458. lastChild = stack.pop();
  459. }
  460. if (!lastChild && firstChild) lastChild = firstChild;
  461. if (firstChild) {
  462. switch (node.type) {
  463. case "ObjectExpression":
  464. this.adjustCommentsAfterTrailingComma(node, node.properties);
  465. break;
  466. case "ObjectPattern":
  467. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  468. break;
  469. case "CallExpression":
  470. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  471. break;
  472. case "ArrayExpression":
  473. this.adjustCommentsAfterTrailingComma(node, node.elements);
  474. break;
  475. case "ArrayPattern":
  476. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  477. break;
  478. }
  479. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  480. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  481. }
  482. if (lastChild) {
  483. if (lastChild.leadingComments) {
  484. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  485. node.leadingComments = lastChild.leadingComments;
  486. delete lastChild.leadingComments;
  487. } else {
  488. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  489. if (lastChild.leadingComments[i].end <= node.start) {
  490. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  491. break;
  492. }
  493. }
  494. }
  495. }
  496. } else if (this.state.leadingComments.length > 0) {
  497. if (last(this.state.leadingComments).end <= node.start) {
  498. if (this.state.commentPreviousNode) {
  499. for (j = 0; j < this.state.leadingComments.length; j++) {
  500. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  501. this.state.leadingComments.splice(j, 1);
  502. j--;
  503. }
  504. }
  505. }
  506. if (this.state.leadingComments.length > 0) {
  507. node.leadingComments = this.state.leadingComments;
  508. this.state.leadingComments = [];
  509. }
  510. } else {
  511. for (i = 0; i < this.state.leadingComments.length; i++) {
  512. if (this.state.leadingComments[i].end > node.start) {
  513. break;
  514. }
  515. }
  516. const leadingComments = this.state.leadingComments.slice(0, i);
  517. if (leadingComments.length) {
  518. node.leadingComments = leadingComments;
  519. }
  520. trailingComments = this.state.leadingComments.slice(i);
  521. if (trailingComments.length === 0) {
  522. trailingComments = null;
  523. }
  524. }
  525. }
  526. this.state.commentPreviousNode = node;
  527. if (trailingComments) {
  528. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  529. node.innerComments = trailingComments;
  530. } else {
  531. node.trailingComments = trailingComments;
  532. }
  533. }
  534. stack.push(node);
  535. }
  536. }
  537. const Errors = Object.freeze({
  538. ArgumentsDisallowedInInitializer: "'arguments' is not allowed in class field initializer",
  539. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  540. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  541. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  542. AwaitNotInAsyncFunction: "Can not use keyword 'await' outside an async function",
  543. BadGetterArity: "getter must not have any formal parameters",
  544. BadSetterArity: "setter must have exactly one formal parameter",
  545. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  546. ConstructorClassField: "Classes may not have a field named 'constructor'",
  547. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  548. ConstructorIsAccessor: "Class constructor may not be an accessor",
  549. ConstructorIsAsync: "Constructor can't be an async function",
  550. ConstructorIsGenerator: "Constructor can't be a generator",
  551. DeclarationMissingInitializer: "%0 require an initialization value",
  552. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  553. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  554. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  555. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  556. DeletePrivateField: "Deleting a private field is not allowed",
  557. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  558. DuplicateConstructor: "Duplicate constructor in the same class",
  559. DuplicateDefaultExport: "Only one default export allowed per module.",
  560. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  561. DuplicateProto: "Redefinition of __proto__ property",
  562. DuplicateRegExpFlags: "Duplicate regular expression flag",
  563. ElementAfterRest: "Rest element must be last element",
  564. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  565. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  566. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  567. IllegalBreakContinue: "Unsyntactic %0",
  568. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  569. IllegalReturn: "'return' outside of function",
  570. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  571. ImportCallArity: "import() requires exactly one argument",
  572. ImportCallArityLtOne: "Dynamic imports require a parameter: import('a.js')",
  573. ImportCallNotNewExpression: "Cannot use new with import(...)",
  574. ImportCallSpreadArgument: "... is not allowed in import()",
  575. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  576. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  577. InvalidCodePoint: "Code point out of bounds",
  578. InvalidDigit: "Expected number in radix %0",
  579. InvalidEscapeSequence: "Bad character escape sequence",
  580. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  581. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  582. InvalidIdentifier: "Invalid identifier %0",
  583. InvalidLhs: "Invalid left-hand side in %0",
  584. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  585. InvalidNumber: "Invalid number",
  586. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  587. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  588. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  589. InvalidPropertyBindingPattern: "Binding member expression",
  590. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  591. LabelRedeclaration: "Label '%0' is already declared",
  592. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  593. MalformedRegExpFlags: "Invalid regular expression flag",
  594. MissingClassName: "A class name is required",
  595. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  596. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  597. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  598. ModuleExportUndefined: "Export '%0' is not defined",
  599. MultipleDefaultsInSwitch: "Multiple default clauses",
  600. NewlineAfterThrow: "Illegal newline after throw",
  601. NoCatchOrFinally: "Missing catch or finally clause",
  602. NumberIdentifier: "Identifier directly after number",
  603. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  604. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  605. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  606. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  607. ParamDupe: "Argument name clash",
  608. PatternHasAccessor: "Object pattern can't contain getter or setter",
  609. PatternHasMethod: "Object pattern can't contain methods",
  610. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  611. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  612. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  613. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  614. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  615. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  616. PrivateNameRedeclaration: "Duplicate private name #%0",
  617. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  618. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  619. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  620. RestTrailingComma: "Unexpected trailing comma after rest element",
  621. SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement",
  622. StaticPrototype: "Classes may not have static property named prototype",
  623. StrictDelete: "Deleting local variable in strict mode",
  624. StrictEvalArguments: "Assigning to '%0' in strict mode",
  625. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  626. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  627. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  628. StrictWith: "'with' in strict mode",
  629. SuperNotAllowed: "super() is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  630. SuperPrivateField: "Private fields can't be accessed on super",
  631. TrailingDecorator: "Decorators must be attached to a class element",
  632. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  633. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  634. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  635. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  636. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  637. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  638. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  639. UnexpectedKeyword: "Unexpected keyword '%0'",
  640. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  641. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  642. UnexpectedNewTarget: "new.target can only be used in functions",
  643. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  644. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  645. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  646. UnexpectedSuper: "super is only allowed in object methods and classes",
  647. UnexpectedToken: "Unexpected token '%'",
  648. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  649. UnsupportedBind: "Binding should be performed on object property.",
  650. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  651. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  652. UnsupportedImport: "import can only be used in import() or import.meta",
  653. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  654. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  655. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  656. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  657. UnterminatedComment: "Unterminated comment",
  658. UnterminatedRegExp: "Unterminated regular expression",
  659. UnterminatedString: "Unterminated string constant",
  660. UnterminatedTemplate: "Unterminated template",
  661. VarRedeclaration: "Identifier '%0' has already been declared",
  662. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  663. YieldInParameter: "yield is not allowed in generator parameters",
  664. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  665. });
  666. class LocationParser extends CommentsParser {
  667. getLocationForPosition(pos) {
  668. let loc;
  669. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  670. return loc;
  671. }
  672. raise(pos, errorTemplate, ...params) {
  673. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  674. }
  675. raiseWithData(pos, data, errorTemplate, ...params) {
  676. const loc = this.getLocationForPosition(pos);
  677. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  678. return this._raise(Object.assign({
  679. loc,
  680. pos
  681. }, data), message);
  682. }
  683. _raise(errorContext, message) {
  684. const err = new SyntaxError(message);
  685. Object.assign(err, errorContext);
  686. if (this.options.errorRecovery) {
  687. if (!this.isLookahead) this.state.errors.push(err);
  688. return err;
  689. } else {
  690. throw err;
  691. }
  692. }
  693. }
  694. function isSimpleProperty(node) {
  695. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  696. }
  697. var estree = (superClass => class extends superClass {
  698. estreeParseRegExpLiteral({
  699. pattern,
  700. flags
  701. }) {
  702. let regex = null;
  703. try {
  704. regex = new RegExp(pattern, flags);
  705. } catch (e) {}
  706. const node = this.estreeParseLiteral(regex);
  707. node.regex = {
  708. pattern,
  709. flags
  710. };
  711. return node;
  712. }
  713. estreeParseBigIntLiteral(value) {
  714. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  715. const node = this.estreeParseLiteral(bigInt);
  716. node.bigint = String(node.value || value);
  717. return node;
  718. }
  719. estreeParseLiteral(value) {
  720. return this.parseLiteral(value, "Literal");
  721. }
  722. directiveToStmt(directive) {
  723. const directiveLiteral = directive.value;
  724. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  725. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  726. expression.value = directiveLiteral.value;
  727. expression.raw = directiveLiteral.extra.raw;
  728. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  729. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  730. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  731. }
  732. initFunction(node, isAsync) {
  733. super.initFunction(node, isAsync);
  734. node.expression = false;
  735. }
  736. checkDeclaration(node) {
  737. if (isSimpleProperty(node)) {
  738. this.checkDeclaration(node.value);
  739. } else {
  740. super.checkDeclaration(node);
  741. }
  742. }
  743. checkGetterSetterParams(method) {
  744. const prop = method;
  745. const paramCount = prop.kind === "get" ? 0 : 1;
  746. const start = prop.start;
  747. if (prop.value.params.length !== paramCount) {
  748. if (method.kind === "get") {
  749. this.raise(start, Errors.BadGetterArity);
  750. } else {
  751. this.raise(start, Errors.BadSetterArity);
  752. }
  753. } else if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
  754. this.raise(start, Errors.BadSetterRestParameter);
  755. }
  756. }
  757. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding) {
  758. switch (expr.type) {
  759. case "ObjectPattern":
  760. expr.properties.forEach(prop => {
  761. this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  762. });
  763. break;
  764. default:
  765. super.checkLVal(expr, bindingType, checkClashes, contextDescription, disallowLetBinding);
  766. }
  767. }
  768. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  769. if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) {
  770. return;
  771. }
  772. const key = prop.key;
  773. const name = key.type === "Identifier" ? key.name : String(key.value);
  774. if (name === "__proto__" && prop.kind === "init") {
  775. if (protoRef.used) {
  776. if (refExpressionErrors && refExpressionErrors.doubleProto === -1) {
  777. refExpressionErrors.doubleProto = key.start;
  778. } else {
  779. this.raise(key.start, Errors.DuplicateProto);
  780. }
  781. }
  782. protoRef.used = true;
  783. }
  784. }
  785. isValidDirective(stmt) {
  786. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized);
  787. }
  788. stmtToDirective(stmt) {
  789. const directive = super.stmtToDirective(stmt);
  790. const value = stmt.expression.value;
  791. directive.value.value = value;
  792. return directive;
  793. }
  794. parseBlockBody(node, allowDirectives, topLevel, end) {
  795. super.parseBlockBody(node, allowDirectives, topLevel, end);
  796. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  797. node.body = directiveStatements.concat(node.body);
  798. delete node.directives;
  799. }
  800. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  801. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  802. if (method.typeParameters) {
  803. method.value.typeParameters = method.typeParameters;
  804. delete method.typeParameters;
  805. }
  806. classBody.body.push(method);
  807. }
  808. parseExprAtom(refExpressionErrors) {
  809. switch (this.state.type) {
  810. case types.num:
  811. case types.string:
  812. return this.estreeParseLiteral(this.state.value);
  813. case types.regexp:
  814. return this.estreeParseRegExpLiteral(this.state.value);
  815. case types.bigint:
  816. return this.estreeParseBigIntLiteral(this.state.value);
  817. case types._null:
  818. return this.estreeParseLiteral(null);
  819. case types._true:
  820. return this.estreeParseLiteral(true);
  821. case types._false:
  822. return this.estreeParseLiteral(false);
  823. default:
  824. return super.parseExprAtom(refExpressionErrors);
  825. }
  826. }
  827. parseLiteral(value, type, startPos, startLoc) {
  828. const node = super.parseLiteral(value, type, startPos, startLoc);
  829. node.raw = node.extra.raw;
  830. delete node.extra;
  831. return node;
  832. }
  833. parseFunctionBody(node, allowExpression, isMethod = false) {
  834. super.parseFunctionBody(node, allowExpression, isMethod);
  835. node.expression = node.body.type !== "BlockStatement";
  836. }
  837. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  838. let funcNode = this.startNode();
  839. funcNode.kind = node.kind;
  840. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  841. funcNode.type = "FunctionExpression";
  842. delete funcNode.kind;
  843. node.value = funcNode;
  844. type = type === "ClassMethod" ? "MethodDefinition" : type;
  845. return this.finishNode(node, type);
  846. }
  847. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  848. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc);
  849. if (node) {
  850. node.type = "Property";
  851. if (node.kind === "method") node.kind = "init";
  852. node.shorthand = false;
  853. }
  854. return node;
  855. }
  856. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  857. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  858. if (node) {
  859. node.kind = "init";
  860. node.type = "Property";
  861. }
  862. return node;
  863. }
  864. toAssignable(node) {
  865. if (isSimpleProperty(node)) {
  866. this.toAssignable(node.value);
  867. return node;
  868. }
  869. return super.toAssignable(node);
  870. }
  871. toAssignableObjectExpressionProp(prop, isLast) {
  872. if (prop.kind === "get" || prop.kind === "set") {
  873. throw this.raise(prop.key.start, Errors.PatternHasAccessor);
  874. } else if (prop.method) {
  875. throw this.raise(prop.key.start, Errors.PatternHasMethod);
  876. } else {
  877. super.toAssignableObjectExpressionProp(prop, isLast);
  878. }
  879. }
  880. finishCallExpression(node, optional) {
  881. super.finishCallExpression(node, optional);
  882. if (node.callee.type === "Import") {
  883. node.type = "ImportExpression";
  884. node.source = node.arguments[0];
  885. delete node.arguments;
  886. delete node.callee;
  887. }
  888. return node;
  889. }
  890. toReferencedListDeep(exprList, isParenthesizedExpr) {
  891. if (!exprList) {
  892. return;
  893. }
  894. super.toReferencedListDeep(exprList, isParenthesizedExpr);
  895. }
  896. parseExport(node) {
  897. super.parseExport(node);
  898. switch (node.type) {
  899. case "ExportAllDeclaration":
  900. node.exported = null;
  901. break;
  902. case "ExportNamedDeclaration":
  903. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  904. node.type = "ExportAllDeclaration";
  905. node.exported = node.specifiers[0].exported;
  906. delete node.specifiers;
  907. }
  908. break;
  909. }
  910. return node;
  911. }
  912. });
  913. class TokContext {
  914. constructor(token, isExpr, preserveSpace, override) {
  915. this.token = token;
  916. this.isExpr = !!isExpr;
  917. this.preserveSpace = !!preserveSpace;
  918. this.override = override;
  919. }
  920. }
  921. const types$1 = {
  922. braceStatement: new TokContext("{", false),
  923. braceExpression: new TokContext("{", true),
  924. templateQuasi: new TokContext("${", false),
  925. parenStatement: new TokContext("(", false),
  926. parenExpression: new TokContext("(", true),
  927. template: new TokContext("`", true, true, p => p.readTmplToken()),
  928. functionExpression: new TokContext("function", true),
  929. functionStatement: new TokContext("function", false)
  930. };
  931. types.parenR.updateContext = types.braceR.updateContext = function () {
  932. if (this.state.context.length === 1) {
  933. this.state.exprAllowed = true;
  934. return;
  935. }
  936. let out = this.state.context.pop();
  937. if (out === types$1.braceStatement && this.curContext().token === "function") {
  938. out = this.state.context.pop();
  939. }
  940. this.state.exprAllowed = !out.isExpr;
  941. };
  942. types.name.updateContext = function (prevType) {
  943. let allowed = false;
  944. if (prevType !== types.dot) {
  945. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class || this.state.value === "yield" && this.prodParam.hasYield) {
  946. allowed = true;
  947. }
  948. }
  949. this.state.exprAllowed = allowed;
  950. if (this.state.isIterator) {
  951. this.state.isIterator = false;
  952. }
  953. };
  954. types.braceL.updateContext = function (prevType) {
  955. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  956. this.state.exprAllowed = true;
  957. };
  958. types.dollarBraceL.updateContext = function () {
  959. this.state.context.push(types$1.templateQuasi);
  960. this.state.exprAllowed = true;
  961. };
  962. types.parenL.updateContext = function (prevType) {
  963. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  964. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  965. this.state.exprAllowed = true;
  966. };
  967. types.incDec.updateContext = function () {};
  968. types._function.updateContext = types._class.updateContext = function (prevType) {
  969. if (prevType === types.dot || prevType === types.questionDot) ; else if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
  970. this.state.context.push(types$1.functionExpression);
  971. } else {
  972. this.state.context.push(types$1.functionStatement);
  973. }
  974. this.state.exprAllowed = false;
  975. };
  976. types.backQuote.updateContext = function () {
  977. if (this.curContext() === types$1.template) {
  978. this.state.context.pop();
  979. } else {
  980. this.state.context.push(types$1.template);
  981. }
  982. this.state.exprAllowed = false;
  983. };
  984. types.star.updateContext = function () {
  985. this.state.exprAllowed = false;
  986. };
  987. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  988. let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  989. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  990. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  991. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  992. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  993. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  994. function isInAstralSet(code, set) {
  995. let pos = 0x10000;
  996. for (let i = 0, length = set.length; i < length; i += 2) {
  997. pos += set[i];
  998. if (pos > code) return false;
  999. pos += set[i + 1];
  1000. if (pos >= code) return true;
  1001. }
  1002. return false;
  1003. }
  1004. function isIdentifierStart(code) {
  1005. if (code < 65) return code === 36;
  1006. if (code <= 90) return true;
  1007. if (code < 97) return code === 95;
  1008. if (code <= 122) return true;
  1009. if (code <= 0xffff) {
  1010. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1011. }
  1012. return isInAstralSet(code, astralIdentifierStartCodes);
  1013. }
  1014. function isIdentifierChar(code) {
  1015. if (code < 48) return code === 36;
  1016. if (code < 58) return true;
  1017. if (code < 65) return false;
  1018. if (code <= 90) return true;
  1019. if (code < 97) return code === 95;
  1020. if (code <= 122) return true;
  1021. if (code <= 0xffff) {
  1022. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1023. }
  1024. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1025. }
  1026. const reservedWords = {
  1027. 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"],
  1028. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1029. strictBind: ["eval", "arguments"]
  1030. };
  1031. const keywords$1 = new Set(reservedWords.keyword);
  1032. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1033. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1034. function isReservedWord(word, inModule) {
  1035. return inModule && word === "await" || word === "enum";
  1036. }
  1037. function isStrictReservedWord(word, inModule) {
  1038. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1039. }
  1040. function isStrictBindOnlyReservedWord(word) {
  1041. return reservedWordsStrictBindSet.has(word);
  1042. }
  1043. function isStrictBindReservedWord(word, inModule) {
  1044. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1045. }
  1046. function isKeyword(word) {
  1047. return keywords$1.has(word);
  1048. }
  1049. const keywordRelationalOperator = /^in(stanceof)?$/;
  1050. function isIteratorStart(current, next) {
  1051. return current === 64 && next === 64;
  1052. }
  1053. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1054. const FlowErrors = Object.freeze({
  1055. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1056. 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",
  1057. AssignReservedType: "Cannot overwrite reserved type %0",
  1058. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1059. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1060. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1061. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1062. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1063. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1064. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1065. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1066. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1067. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1068. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1069. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1070. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1071. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1072. 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",
  1073. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1074. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1075. InexactVariance: "Explicit inexact syntax cannot have variance",
  1076. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1077. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1078. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1079. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1080. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1081. SpreadVariance: "Spread properties cannot have variance",
  1082. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1083. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1084. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1085. UnexpectedReservedType: "Unexpected reserved type %0",
  1086. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1087. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1088. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1089. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1090. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1091. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1092. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1093. UnterminatedFlowComment: "Unterminated flow-comment"
  1094. });
  1095. function isEsModuleType(bodyElement) {
  1096. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1097. }
  1098. function hasTypeImportKind(node) {
  1099. return node.importKind === "type" || node.importKind === "typeof";
  1100. }
  1101. function isMaybeDefaultImport(state) {
  1102. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1103. }
  1104. const exportSuggestions = {
  1105. const: "declare export var",
  1106. let: "declare export var",
  1107. type: "export type",
  1108. interface: "export interface"
  1109. };
  1110. function partition(list, test) {
  1111. const list1 = [];
  1112. const list2 = [];
  1113. for (let i = 0; i < list.length; i++) {
  1114. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1115. }
  1116. return [list1, list2];
  1117. }
  1118. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1119. var flow = (superClass => class extends superClass {
  1120. constructor(options, input) {
  1121. super(options, input);
  1122. this.flowPragma = undefined;
  1123. }
  1124. shouldParseTypes() {
  1125. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1126. }
  1127. shouldParseEnums() {
  1128. return !!this.getPluginOption("flow", "enums");
  1129. }
  1130. finishToken(type, val) {
  1131. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1132. if (this.flowPragma === undefined) {
  1133. this.flowPragma = null;
  1134. }
  1135. }
  1136. return super.finishToken(type, val);
  1137. }
  1138. addComment(comment) {
  1139. if (this.flowPragma === undefined) {
  1140. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1141. if (!matches) ; else if (matches[1] === "flow") {
  1142. this.flowPragma = "flow";
  1143. } else if (matches[1] === "noflow") {
  1144. this.flowPragma = "noflow";
  1145. } else {
  1146. throw new Error("Unexpected flow pragma");
  1147. }
  1148. }
  1149. return super.addComment(comment);
  1150. }
  1151. flowParseTypeInitialiser(tok) {
  1152. const oldInType = this.state.inType;
  1153. this.state.inType = true;
  1154. this.expect(tok || types.colon);
  1155. const type = this.flowParseType();
  1156. this.state.inType = oldInType;
  1157. return type;
  1158. }
  1159. flowParsePredicate() {
  1160. const node = this.startNode();
  1161. const moduloLoc = this.state.startLoc;
  1162. const moduloPos = this.state.start;
  1163. this.expect(types.modulo);
  1164. const checksLoc = this.state.startLoc;
  1165. this.expectContextual("checks");
  1166. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1167. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1168. }
  1169. if (this.eat(types.parenL)) {
  1170. node.value = this.parseExpression();
  1171. this.expect(types.parenR);
  1172. return this.finishNode(node, "DeclaredPredicate");
  1173. } else {
  1174. return this.finishNode(node, "InferredPredicate");
  1175. }
  1176. }
  1177. flowParseTypeAndPredicateInitialiser() {
  1178. const oldInType = this.state.inType;
  1179. this.state.inType = true;
  1180. this.expect(types.colon);
  1181. let type = null;
  1182. let predicate = null;
  1183. if (this.match(types.modulo)) {
  1184. this.state.inType = oldInType;
  1185. predicate = this.flowParsePredicate();
  1186. } else {
  1187. type = this.flowParseType();
  1188. this.state.inType = oldInType;
  1189. if (this.match(types.modulo)) {
  1190. predicate = this.flowParsePredicate();
  1191. }
  1192. }
  1193. return [type, predicate];
  1194. }
  1195. flowParseDeclareClass(node) {
  1196. this.next();
  1197. this.flowParseInterfaceish(node, true);
  1198. return this.finishNode(node, "DeclareClass");
  1199. }
  1200. flowParseDeclareFunction(node) {
  1201. this.next();
  1202. const id = node.id = this.parseIdentifier();
  1203. const typeNode = this.startNode();
  1204. const typeContainer = this.startNode();
  1205. if (this.isRelational("<")) {
  1206. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1207. } else {
  1208. typeNode.typeParameters = null;
  1209. }
  1210. this.expect(types.parenL);
  1211. const tmp = this.flowParseFunctionTypeParams();
  1212. typeNode.params = tmp.params;
  1213. typeNode.rest = tmp.rest;
  1214. this.expect(types.parenR);
  1215. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1216. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1217. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1218. this.resetEndLocation(id);
  1219. this.semicolon();
  1220. return this.finishNode(node, "DeclareFunction");
  1221. }
  1222. flowParseDeclare(node, insideModule) {
  1223. if (this.match(types._class)) {
  1224. return this.flowParseDeclareClass(node);
  1225. } else if (this.match(types._function)) {
  1226. return this.flowParseDeclareFunction(node);
  1227. } else if (this.match(types._var)) {
  1228. return this.flowParseDeclareVariable(node);
  1229. } else if (this.eatContextual("module")) {
  1230. if (this.match(types.dot)) {
  1231. return this.flowParseDeclareModuleExports(node);
  1232. } else {
  1233. if (insideModule) {
  1234. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1235. }
  1236. return this.flowParseDeclareModule(node);
  1237. }
  1238. } else if (this.isContextual("type")) {
  1239. return this.flowParseDeclareTypeAlias(node);
  1240. } else if (this.isContextual("opaque")) {
  1241. return this.flowParseDeclareOpaqueType(node);
  1242. } else if (this.isContextual("interface")) {
  1243. return this.flowParseDeclareInterface(node);
  1244. } else if (this.match(types._export)) {
  1245. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1246. } else {
  1247. throw this.unexpected();
  1248. }
  1249. }
  1250. flowParseDeclareVariable(node) {
  1251. this.next();
  1252. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1253. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1254. this.semicolon();
  1255. return this.finishNode(node, "DeclareVariable");
  1256. }
  1257. flowParseDeclareModule(node) {
  1258. this.scope.enter(SCOPE_OTHER);
  1259. if (this.match(types.string)) {
  1260. node.id = this.parseExprAtom();
  1261. } else {
  1262. node.id = this.parseIdentifier();
  1263. }
  1264. const bodyNode = node.body = this.startNode();
  1265. const body = bodyNode.body = [];
  1266. this.expect(types.braceL);
  1267. while (!this.match(types.braceR)) {
  1268. let bodyNode = this.startNode();
  1269. if (this.match(types._import)) {
  1270. this.next();
  1271. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1272. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1273. }
  1274. this.parseImport(bodyNode);
  1275. } else {
  1276. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1277. bodyNode = this.flowParseDeclare(bodyNode, true);
  1278. }
  1279. body.push(bodyNode);
  1280. }
  1281. this.scope.exit();
  1282. this.expect(types.braceR);
  1283. this.finishNode(bodyNode, "BlockStatement");
  1284. let kind = null;
  1285. let hasModuleExport = false;
  1286. body.forEach(bodyElement => {
  1287. if (isEsModuleType(bodyElement)) {
  1288. if (kind === "CommonJS") {
  1289. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1290. }
  1291. kind = "ES";
  1292. } else if (bodyElement.type === "DeclareModuleExports") {
  1293. if (hasModuleExport) {
  1294. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1295. }
  1296. if (kind === "ES") {
  1297. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1298. }
  1299. kind = "CommonJS";
  1300. hasModuleExport = true;
  1301. }
  1302. });
  1303. node.kind = kind || "CommonJS";
  1304. return this.finishNode(node, "DeclareModule");
  1305. }
  1306. flowParseDeclareExportDeclaration(node, insideModule) {
  1307. this.expect(types._export);
  1308. if (this.eat(types._default)) {
  1309. if (this.match(types._function) || this.match(types._class)) {
  1310. node.declaration = this.flowParseDeclare(this.startNode());
  1311. } else {
  1312. node.declaration = this.flowParseType();
  1313. this.semicolon();
  1314. }
  1315. node.default = true;
  1316. return this.finishNode(node, "DeclareExportDeclaration");
  1317. } else {
  1318. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1319. const label = this.state.value;
  1320. const suggestion = exportSuggestions[label];
  1321. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1322. }
  1323. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1324. node.declaration = this.flowParseDeclare(this.startNode());
  1325. node.default = false;
  1326. return this.finishNode(node, "DeclareExportDeclaration");
  1327. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1328. node = this.parseExport(node);
  1329. if (node.type === "ExportNamedDeclaration") {
  1330. node.type = "ExportDeclaration";
  1331. node.default = false;
  1332. delete node.exportKind;
  1333. }
  1334. node.type = "Declare" + node.type;
  1335. return node;
  1336. }
  1337. }
  1338. throw this.unexpected();
  1339. }
  1340. flowParseDeclareModuleExports(node) {
  1341. this.next();
  1342. this.expectContextual("exports");
  1343. node.typeAnnotation = this.flowParseTypeAnnotation();
  1344. this.semicolon();
  1345. return this.finishNode(node, "DeclareModuleExports");
  1346. }
  1347. flowParseDeclareTypeAlias(node) {
  1348. this.next();
  1349. this.flowParseTypeAlias(node);
  1350. node.type = "DeclareTypeAlias";
  1351. return node;
  1352. }
  1353. flowParseDeclareOpaqueType(node) {
  1354. this.next();
  1355. this.flowParseOpaqueType(node, true);
  1356. node.type = "DeclareOpaqueType";
  1357. return node;
  1358. }
  1359. flowParseDeclareInterface(node) {
  1360. this.next();
  1361. this.flowParseInterfaceish(node);
  1362. return this.finishNode(node, "DeclareInterface");
  1363. }
  1364. flowParseInterfaceish(node, isClass = false) {
  1365. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1366. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1367. if (this.isRelational("<")) {
  1368. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1369. } else {
  1370. node.typeParameters = null;
  1371. }
  1372. node.extends = [];
  1373. node.implements = [];
  1374. node.mixins = [];
  1375. if (this.eat(types._extends)) {
  1376. do {
  1377. node.extends.push(this.flowParseInterfaceExtends());
  1378. } while (!isClass && this.eat(types.comma));
  1379. }
  1380. if (this.isContextual("mixins")) {
  1381. this.next();
  1382. do {
  1383. node.mixins.push(this.flowParseInterfaceExtends());
  1384. } while (this.eat(types.comma));
  1385. }
  1386. if (this.isContextual("implements")) {
  1387. this.next();
  1388. do {
  1389. node.implements.push(this.flowParseInterfaceExtends());
  1390. } while (this.eat(types.comma));
  1391. }
  1392. node.body = this.flowParseObjectType({
  1393. allowStatic: isClass,
  1394. allowExact: false,
  1395. allowSpread: false,
  1396. allowProto: isClass,
  1397. allowInexact: false
  1398. });
  1399. }
  1400. flowParseInterfaceExtends() {
  1401. const node = this.startNode();
  1402. node.id = this.flowParseQualifiedTypeIdentifier();
  1403. if (this.isRelational("<")) {
  1404. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1405. } else {
  1406. node.typeParameters = null;
  1407. }
  1408. return this.finishNode(node, "InterfaceExtends");
  1409. }
  1410. flowParseInterface(node) {
  1411. this.flowParseInterfaceish(node);
  1412. return this.finishNode(node, "InterfaceDeclaration");
  1413. }
  1414. checkNotUnderscore(word) {
  1415. if (word === "_") {
  1416. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1417. }
  1418. }
  1419. checkReservedType(word, startLoc, declaration) {
  1420. if (!reservedTypes.has(word)) return;
  1421. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1422. }
  1423. flowParseRestrictedIdentifier(liberal, declaration) {
  1424. this.checkReservedType(this.state.value, this.state.start, declaration);
  1425. return this.parseIdentifier(liberal);
  1426. }
  1427. flowParseTypeAlias(node) {
  1428. node.id = this.flowParseRestrictedIdentifier(false, true);
  1429. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1430. if (this.isRelational("<")) {
  1431. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1432. } else {
  1433. node.typeParameters = null;
  1434. }
  1435. node.right = this.flowParseTypeInitialiser(types.eq);
  1436. this.semicolon();
  1437. return this.finishNode(node, "TypeAlias");
  1438. }
  1439. flowParseOpaqueType(node, declare) {
  1440. this.expectContextual("type");
  1441. node.id = this.flowParseRestrictedIdentifier(true, true);
  1442. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1443. if (this.isRelational("<")) {
  1444. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1445. } else {
  1446. node.typeParameters = null;
  1447. }
  1448. node.supertype = null;
  1449. if (this.match(types.colon)) {
  1450. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1451. }
  1452. node.impltype = null;
  1453. if (!declare) {
  1454. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1455. }
  1456. this.semicolon();
  1457. return this.finishNode(node, "OpaqueType");
  1458. }
  1459. flowParseTypeParameter(requireDefault = false) {
  1460. const nodeStart = this.state.start;
  1461. const node = this.startNode();
  1462. const variance = this.flowParseVariance();
  1463. const ident = this.flowParseTypeAnnotatableIdentifier();
  1464. node.name = ident.name;
  1465. node.variance = variance;
  1466. node.bound = ident.typeAnnotation;
  1467. if (this.match(types.eq)) {
  1468. this.eat(types.eq);
  1469. node.default = this.flowParseType();
  1470. } else {
  1471. if (requireDefault) {
  1472. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1473. }
  1474. }
  1475. return this.finishNode(node, "TypeParameter");
  1476. }
  1477. flowParseTypeParameterDeclaration() {
  1478. const oldInType = this.state.inType;
  1479. const node = this.startNode();
  1480. node.params = [];
  1481. this.state.inType = true;
  1482. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1483. this.next();
  1484. } else {
  1485. this.unexpected();
  1486. }
  1487. let defaultRequired = false;
  1488. do {
  1489. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1490. node.params.push(typeParameter);
  1491. if (typeParameter.default) {
  1492. defaultRequired = true;
  1493. }
  1494. if (!this.isRelational(">")) {
  1495. this.expect(types.comma);
  1496. }
  1497. } while (!this.isRelational(">"));
  1498. this.expectRelational(">");
  1499. this.state.inType = oldInType;
  1500. return this.finishNode(node, "TypeParameterDeclaration");
  1501. }
  1502. flowParseTypeParameterInstantiation() {
  1503. const node = this.startNode();
  1504. const oldInType = this.state.inType;
  1505. node.params = [];
  1506. this.state.inType = true;
  1507. this.expectRelational("<");
  1508. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1509. this.state.noAnonFunctionType = false;
  1510. while (!this.isRelational(">")) {
  1511. node.params.push(this.flowParseType());
  1512. if (!this.isRelational(">")) {
  1513. this.expect(types.comma);
  1514. }
  1515. }
  1516. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1517. this.expectRelational(">");
  1518. this.state.inType = oldInType;
  1519. return this.finishNode(node, "TypeParameterInstantiation");
  1520. }
  1521. flowParseTypeParameterInstantiationCallOrNew() {
  1522. const node = this.startNode();
  1523. const oldInType = this.state.inType;
  1524. node.params = [];
  1525. this.state.inType = true;
  1526. this.expectRelational("<");
  1527. while (!this.isRelational(">")) {
  1528. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1529. if (!this.isRelational(">")) {
  1530. this.expect(types.comma);
  1531. }
  1532. }
  1533. this.expectRelational(">");
  1534. this.state.inType = oldInType;
  1535. return this.finishNode(node, "TypeParameterInstantiation");
  1536. }
  1537. flowParseInterfaceType() {
  1538. const node = this.startNode();
  1539. this.expectContextual("interface");
  1540. node.extends = [];
  1541. if (this.eat(types._extends)) {
  1542. do {
  1543. node.extends.push(this.flowParseInterfaceExtends());
  1544. } while (this.eat(types.comma));
  1545. }
  1546. node.body = this.flowParseObjectType({
  1547. allowStatic: false,
  1548. allowExact: false,
  1549. allowSpread: false,
  1550. allowProto: false,
  1551. allowInexact: false
  1552. });
  1553. return this.finishNode(node, "InterfaceTypeAnnotation");
  1554. }
  1555. flowParseObjectPropertyKey() {
  1556. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1557. }
  1558. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1559. node.static = isStatic;
  1560. if (this.lookahead().type === types.colon) {
  1561. node.id = this.flowParseObjectPropertyKey();
  1562. node.key = this.flowParseTypeInitialiser();
  1563. } else {
  1564. node.id = null;
  1565. node.key = this.flowParseType();
  1566. }
  1567. this.expect(types.bracketR);
  1568. node.value = this.flowParseTypeInitialiser();
  1569. node.variance = variance;
  1570. return this.finishNode(node, "ObjectTypeIndexer");
  1571. }
  1572. flowParseObjectTypeInternalSlot(node, isStatic) {
  1573. node.static = isStatic;
  1574. node.id = this.flowParseObjectPropertyKey();
  1575. this.expect(types.bracketR);
  1576. this.expect(types.bracketR);
  1577. if (this.isRelational("<") || this.match(types.parenL)) {
  1578. node.method = true;
  1579. node.optional = false;
  1580. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1581. } else {
  1582. node.method = false;
  1583. if (this.eat(types.question)) {
  1584. node.optional = true;
  1585. }
  1586. node.value = this.flowParseTypeInitialiser();
  1587. }
  1588. return this.finishNode(node, "ObjectTypeInternalSlot");
  1589. }
  1590. flowParseObjectTypeMethodish(node) {
  1591. node.params = [];
  1592. node.rest = null;
  1593. node.typeParameters = null;
  1594. if (this.isRelational("<")) {
  1595. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1596. }
  1597. this.expect(types.parenL);
  1598. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1599. node.params.push(this.flowParseFunctionTypeParam());
  1600. if (!this.match(types.parenR)) {
  1601. this.expect(types.comma);
  1602. }
  1603. }
  1604. if (this.eat(types.ellipsis)) {
  1605. node.rest = this.flowParseFunctionTypeParam();
  1606. }
  1607. this.expect(types.parenR);
  1608. node.returnType = this.flowParseTypeInitialiser();
  1609. return this.finishNode(node, "FunctionTypeAnnotation");
  1610. }
  1611. flowParseObjectTypeCallProperty(node, isStatic) {
  1612. const valueNode = this.startNode();
  1613. node.static = isStatic;
  1614. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1615. return this.finishNode(node, "ObjectTypeCallProperty");
  1616. }
  1617. flowParseObjectType({
  1618. allowStatic,
  1619. allowExact,
  1620. allowSpread,
  1621. allowProto,
  1622. allowInexact
  1623. }) {
  1624. const oldInType = this.state.inType;
  1625. this.state.inType = true;
  1626. const nodeStart = this.startNode();
  1627. nodeStart.callProperties = [];
  1628. nodeStart.properties = [];
  1629. nodeStart.indexers = [];
  1630. nodeStart.internalSlots = [];
  1631. let endDelim;
  1632. let exact;
  1633. let inexact = false;
  1634. if (allowExact && this.match(types.braceBarL)) {
  1635. this.expect(types.braceBarL);
  1636. endDelim = types.braceBarR;
  1637. exact = true;
  1638. } else {
  1639. this.expect(types.braceL);
  1640. endDelim = types.braceR;
  1641. exact = false;
  1642. }
  1643. nodeStart.exact = exact;
  1644. while (!this.match(endDelim)) {
  1645. let isStatic = false;
  1646. let protoStart = null;
  1647. let inexactStart = null;
  1648. const node = this.startNode();
  1649. if (allowProto && this.isContextual("proto")) {
  1650. const lookahead = this.lookahead();
  1651. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1652. this.next();
  1653. protoStart = this.state.start;
  1654. allowStatic = false;
  1655. }
  1656. }
  1657. if (allowStatic && this.isContextual("static")) {
  1658. const lookahead = this.lookahead();
  1659. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1660. this.next();
  1661. isStatic = true;
  1662. }
  1663. }
  1664. const variance = this.flowParseVariance();
  1665. if (this.eat(types.bracketL)) {
  1666. if (protoStart != null) {
  1667. this.unexpected(protoStart);
  1668. }
  1669. if (this.eat(types.bracketL)) {
  1670. if (variance) {
  1671. this.unexpected(variance.start);
  1672. }
  1673. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1674. } else {
  1675. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1676. }
  1677. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1678. if (protoStart != null) {
  1679. this.unexpected(protoStart);
  1680. }
  1681. if (variance) {
  1682. this.unexpected(variance.start);
  1683. }
  1684. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1685. } else {
  1686. let kind = "init";
  1687. if (this.isContextual("get") || this.isContextual("set")) {
  1688. const lookahead = this.lookahead();
  1689. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1690. kind = this.state.value;
  1691. this.next();
  1692. }
  1693. }
  1694. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1695. if (propOrInexact === null) {
  1696. inexact = true;
  1697. inexactStart = this.state.lastTokStart;
  1698. } else {
  1699. nodeStart.properties.push(propOrInexact);
  1700. }
  1701. }
  1702. this.flowObjectTypeSemicolon();
  1703. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1704. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  1705. }
  1706. }
  1707. this.expect(endDelim);
  1708. if (allowSpread) {
  1709. nodeStart.inexact = inexact;
  1710. }
  1711. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  1712. this.state.inType = oldInType;
  1713. return out;
  1714. }
  1715. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  1716. if (this.eat(types.ellipsis)) {
  1717. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  1718. if (isInexactToken) {
  1719. if (!allowSpread) {
  1720. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  1721. } else if (!allowInexact) {
  1722. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  1723. }
  1724. if (variance) {
  1725. this.raise(variance.start, FlowErrors.InexactVariance);
  1726. }
  1727. return null;
  1728. }
  1729. if (!allowSpread) {
  1730. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  1731. }
  1732. if (protoStart != null) {
  1733. this.unexpected(protoStart);
  1734. }
  1735. if (variance) {
  1736. this.raise(variance.start, FlowErrors.SpreadVariance);
  1737. }
  1738. node.argument = this.flowParseType();
  1739. return this.finishNode(node, "ObjectTypeSpreadProperty");
  1740. } else {
  1741. node.key = this.flowParseObjectPropertyKey();
  1742. node.static = isStatic;
  1743. node.proto = protoStart != null;
  1744. node.kind = kind;
  1745. let optional = false;
  1746. if (this.isRelational("<") || this.match(types.parenL)) {
  1747. node.method = true;
  1748. if (protoStart != null) {
  1749. this.unexpected(protoStart);
  1750. }
  1751. if (variance) {
  1752. this.unexpected(variance.start);
  1753. }
  1754. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1755. if (kind === "get" || kind === "set") {
  1756. this.flowCheckGetterSetterParams(node);
  1757. }
  1758. } else {
  1759. if (kind !== "init") this.unexpected();
  1760. node.method = false;
  1761. if (this.eat(types.question)) {
  1762. optional = true;
  1763. }
  1764. node.value = this.flowParseTypeInitialiser();
  1765. node.variance = variance;
  1766. }
  1767. node.optional = optional;
  1768. return this.finishNode(node, "ObjectTypeProperty");
  1769. }
  1770. }
  1771. flowCheckGetterSetterParams(property) {
  1772. const paramCount = property.kind === "get" ? 0 : 1;
  1773. const start = property.start;
  1774. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  1775. if (length !== paramCount) {
  1776. if (property.kind === "get") {
  1777. this.raise(start, Errors.BadGetterArity);
  1778. } else {
  1779. this.raise(start, Errors.BadSetterArity);
  1780. }
  1781. }
  1782. if (property.kind === "set" && property.value.rest) {
  1783. this.raise(start, Errors.BadSetterRestParameter);
  1784. }
  1785. }
  1786. flowObjectTypeSemicolon() {
  1787. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  1788. this.unexpected();
  1789. }
  1790. }
  1791. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  1792. startPos = startPos || this.state.start;
  1793. startLoc = startLoc || this.state.startLoc;
  1794. let node = id || this.flowParseRestrictedIdentifier(true);
  1795. while (this.eat(types.dot)) {
  1796. const node2 = this.startNodeAt(startPos, startLoc);
  1797. node2.qualification = node;
  1798. node2.id = this.flowParseRestrictedIdentifier(true);
  1799. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  1800. }
  1801. return node;
  1802. }
  1803. flowParseGenericType(startPos, startLoc, id) {
  1804. const node = this.startNodeAt(startPos, startLoc);
  1805. node.typeParameters = null;
  1806. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  1807. if (this.isRelational("<")) {
  1808. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1809. }
  1810. return this.finishNode(node, "GenericTypeAnnotation");
  1811. }
  1812. flowParseTypeofType() {
  1813. const node = this.startNode();
  1814. this.expect(types._typeof);
  1815. node.argument = this.flowParsePrimaryType();
  1816. return this.finishNode(node, "TypeofTypeAnnotation");
  1817. }
  1818. flowParseTupleType() {
  1819. const node = this.startNode();
  1820. node.types = [];
  1821. this.expect(types.bracketL);
  1822. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  1823. node.types.push(this.flowParseType());
  1824. if (this.match(types.bracketR)) break;
  1825. this.expect(types.comma);
  1826. }
  1827. this.expect(types.bracketR);
  1828. return this.finishNode(node, "TupleTypeAnnotation");
  1829. }
  1830. flowParseFunctionTypeParam() {
  1831. let name = null;
  1832. let optional = false;
  1833. let typeAnnotation = null;
  1834. const node = this.startNode();
  1835. const lh = this.lookahead();
  1836. if (lh.type === types.colon || lh.type === types.question) {
  1837. name = this.parseIdentifier();
  1838. if (this.eat(types.question)) {
  1839. optional = true;
  1840. }
  1841. typeAnnotation = this.flowParseTypeInitialiser();
  1842. } else {
  1843. typeAnnotation = this.flowParseType();
  1844. }
  1845. node.name = name;
  1846. node.optional = optional;
  1847. node.typeAnnotation = typeAnnotation;
  1848. return this.finishNode(node, "FunctionTypeParam");
  1849. }
  1850. reinterpretTypeAsFunctionTypeParam(type) {
  1851. const node = this.startNodeAt(type.start, type.loc.start);
  1852. node.name = null;
  1853. node.optional = false;
  1854. node.typeAnnotation = type;
  1855. return this.finishNode(node, "FunctionTypeParam");
  1856. }
  1857. flowParseFunctionTypeParams(params = []) {
  1858. let rest = null;
  1859. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1860. params.push(this.flowParseFunctionTypeParam());
  1861. if (!this.match(types.parenR)) {
  1862. this.expect(types.comma);
  1863. }
  1864. }
  1865. if (this.eat(types.ellipsis)) {
  1866. rest = this.flowParseFunctionTypeParam();
  1867. }
  1868. return {
  1869. params,
  1870. rest
  1871. };
  1872. }
  1873. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  1874. switch (id.name) {
  1875. case "any":
  1876. return this.finishNode(node, "AnyTypeAnnotation");
  1877. case "bool":
  1878. case "boolean":
  1879. return this.finishNode(node, "BooleanTypeAnnotation");
  1880. case "mixed":
  1881. return this.finishNode(node, "MixedTypeAnnotation");
  1882. case "empty":
  1883. return this.finishNode(node, "EmptyTypeAnnotation");
  1884. case "number":
  1885. return this.finishNode(node, "NumberTypeAnnotation");
  1886. case "string":
  1887. return this.finishNode(node, "StringTypeAnnotation");
  1888. case "symbol":
  1889. return this.finishNode(node, "SymbolTypeAnnotation");
  1890. default:
  1891. this.checkNotUnderscore(id.name);
  1892. return this.flowParseGenericType(startPos, startLoc, id);
  1893. }
  1894. }
  1895. flowParsePrimaryType() {
  1896. const startPos = this.state.start;
  1897. const startLoc = this.state.startLoc;
  1898. const node = this.startNode();
  1899. let tmp;
  1900. let type;
  1901. let isGroupedType = false;
  1902. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1903. switch (this.state.type) {
  1904. case types.name:
  1905. if (this.isContextual("interface")) {
  1906. return this.flowParseInterfaceType();
  1907. }
  1908. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  1909. case types.braceL:
  1910. return this.flowParseObjectType({
  1911. allowStatic: false,
  1912. allowExact: false,
  1913. allowSpread: true,
  1914. allowProto: false,
  1915. allowInexact: true
  1916. });
  1917. case types.braceBarL:
  1918. return this.flowParseObjectType({
  1919. allowStatic: false,
  1920. allowExact: true,
  1921. allowSpread: true,
  1922. allowProto: false,
  1923. allowInexact: false
  1924. });
  1925. case types.bracketL:
  1926. this.state.noAnonFunctionType = false;
  1927. type = this.flowParseTupleType();
  1928. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1929. return type;
  1930. case types.relational:
  1931. if (this.state.value === "<") {
  1932. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1933. this.expect(types.parenL);
  1934. tmp = this.flowParseFunctionTypeParams();
  1935. node.params = tmp.params;
  1936. node.rest = tmp.rest;
  1937. this.expect(types.parenR);
  1938. this.expect(types.arrow);
  1939. node.returnType = this.flowParseType();
  1940. return this.finishNode(node, "FunctionTypeAnnotation");
  1941. }
  1942. break;
  1943. case types.parenL:
  1944. this.next();
  1945. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1946. if (this.match(types.name)) {
  1947. const token = this.lookahead().type;
  1948. isGroupedType = token !== types.question && token !== types.colon;
  1949. } else {
  1950. isGroupedType = true;
  1951. }
  1952. }
  1953. if (isGroupedType) {
  1954. this.state.noAnonFunctionType = false;
  1955. type = this.flowParseType();
  1956. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1957. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  1958. this.expect(types.parenR);
  1959. return type;
  1960. } else {
  1961. this.eat(types.comma);
  1962. }
  1963. }
  1964. if (type) {
  1965. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  1966. } else {
  1967. tmp = this.flowParseFunctionTypeParams();
  1968. }
  1969. node.params = tmp.params;
  1970. node.rest = tmp.rest;
  1971. this.expect(types.parenR);
  1972. this.expect(types.arrow);
  1973. node.returnType = this.flowParseType();
  1974. node.typeParameters = null;
  1975. return this.finishNode(node, "FunctionTypeAnnotation");
  1976. case types.string:
  1977. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  1978. case types._true:
  1979. case types._false:
  1980. node.value = this.match(types._true);
  1981. this.next();
  1982. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  1983. case types.plusMin:
  1984. if (this.state.value === "-") {
  1985. this.next();
  1986. if (this.match(types.num)) {
  1987. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  1988. }
  1989. if (this.match(types.bigint)) {
  1990. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  1991. }
  1992. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  1993. }
  1994. throw this.unexpected();
  1995. case types.num:
  1996. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  1997. case types.bigint:
  1998. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  1999. case types._void:
  2000. this.next();
  2001. return this.finishNode(node, "VoidTypeAnnotation");
  2002. case types._null:
  2003. this.next();
  2004. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2005. case types._this:
  2006. this.next();
  2007. return this.finishNode(node, "ThisTypeAnnotation");
  2008. case types.star:
  2009. this.next();
  2010. return this.finishNode(node, "ExistsTypeAnnotation");
  2011. default:
  2012. if (this.state.type.keyword === "typeof") {
  2013. return this.flowParseTypeofType();
  2014. } else if (this.state.type.keyword) {
  2015. const label = this.state.type.label;
  2016. this.next();
  2017. return super.createIdentifier(node, label);
  2018. }
  2019. }
  2020. throw this.unexpected();
  2021. }
  2022. flowParsePostfixType() {
  2023. const startPos = this.state.start,
  2024. startLoc = this.state.startLoc;
  2025. let type = this.flowParsePrimaryType();
  2026. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2027. const node = this.startNodeAt(startPos, startLoc);
  2028. node.elementType = type;
  2029. this.expect(types.bracketL);
  2030. this.expect(types.bracketR);
  2031. type = this.finishNode(node, "ArrayTypeAnnotation");
  2032. }
  2033. return type;
  2034. }
  2035. flowParsePrefixType() {
  2036. const node = this.startNode();
  2037. if (this.eat(types.question)) {
  2038. node.typeAnnotation = this.flowParsePrefixType();
  2039. return this.finishNode(node, "NullableTypeAnnotation");
  2040. } else {
  2041. return this.flowParsePostfixType();
  2042. }
  2043. }
  2044. flowParseAnonFunctionWithoutParens() {
  2045. const param = this.flowParsePrefixType();
  2046. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2047. const node = this.startNodeAt(param.start, param.loc.start);
  2048. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2049. node.rest = null;
  2050. node.returnType = this.flowParseType();
  2051. node.typeParameters = null;
  2052. return this.finishNode(node, "FunctionTypeAnnotation");
  2053. }
  2054. return param;
  2055. }
  2056. flowParseIntersectionType() {
  2057. const node = this.startNode();
  2058. this.eat(types.bitwiseAND);
  2059. const type = this.flowParseAnonFunctionWithoutParens();
  2060. node.types = [type];
  2061. while (this.eat(types.bitwiseAND)) {
  2062. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2063. }
  2064. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2065. }
  2066. flowParseUnionType() {
  2067. const node = this.startNode();
  2068. this.eat(types.bitwiseOR);
  2069. const type = this.flowParseIntersectionType();
  2070. node.types = [type];
  2071. while (this.eat(types.bitwiseOR)) {
  2072. node.types.push(this.flowParseIntersectionType());
  2073. }
  2074. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2075. }
  2076. flowParseType() {
  2077. const oldInType = this.state.inType;
  2078. this.state.inType = true;
  2079. const type = this.flowParseUnionType();
  2080. this.state.inType = oldInType;
  2081. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2082. return type;
  2083. }
  2084. flowParseTypeOrImplicitInstantiation() {
  2085. if (this.state.type === types.name && this.state.value === "_") {
  2086. const startPos = this.state.start;
  2087. const startLoc = this.state.startLoc;
  2088. const node = this.parseIdentifier();
  2089. return this.flowParseGenericType(startPos, startLoc, node);
  2090. } else {
  2091. return this.flowParseType();
  2092. }
  2093. }
  2094. flowParseTypeAnnotation() {
  2095. const node = this.startNode();
  2096. node.typeAnnotation = this.flowParseTypeInitialiser();
  2097. return this.finishNode(node, "TypeAnnotation");
  2098. }
  2099. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2100. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2101. if (this.match(types.colon)) {
  2102. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2103. this.resetEndLocation(ident);
  2104. }
  2105. return ident;
  2106. }
  2107. typeCastToParameter(node) {
  2108. node.expression.typeAnnotation = node.typeAnnotation;
  2109. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2110. return node.expression;
  2111. }
  2112. flowParseVariance() {
  2113. let variance = null;
  2114. if (this.match(types.plusMin)) {
  2115. variance = this.startNode();
  2116. if (this.state.value === "+") {
  2117. variance.kind = "plus";
  2118. } else {
  2119. variance.kind = "minus";
  2120. }
  2121. this.next();
  2122. this.finishNode(variance, "Variance");
  2123. }
  2124. return variance;
  2125. }
  2126. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2127. if (allowExpressionBody) {
  2128. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2129. }
  2130. return super.parseFunctionBody(node, false, isMethod);
  2131. }
  2132. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2133. if (this.match(types.colon)) {
  2134. const typeNode = this.startNode();
  2135. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2136. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2137. }
  2138. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2139. }
  2140. parseStatement(context, topLevel) {
  2141. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2142. const node = this.startNode();
  2143. this.next();
  2144. return this.flowParseInterface(node);
  2145. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2146. const node = this.startNode();
  2147. this.next();
  2148. return this.flowParseEnumDeclaration(node);
  2149. } else {
  2150. const stmt = super.parseStatement(context, topLevel);
  2151. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2152. this.flowPragma = null;
  2153. }
  2154. return stmt;
  2155. }
  2156. }
  2157. parseExpressionStatement(node, expr) {
  2158. if (expr.type === "Identifier") {
  2159. if (expr.name === "declare") {
  2160. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2161. return this.flowParseDeclare(node);
  2162. }
  2163. } else if (this.match(types.name)) {
  2164. if (expr.name === "interface") {
  2165. return this.flowParseInterface(node);
  2166. } else if (expr.name === "type") {
  2167. return this.flowParseTypeAlias(node);
  2168. } else if (expr.name === "opaque") {
  2169. return this.flowParseOpaqueType(node, false);
  2170. }
  2171. }
  2172. }
  2173. return super.parseExpressionStatement(node, expr);
  2174. }
  2175. shouldParseExportDeclaration() {
  2176. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2177. }
  2178. isExportDefaultSpecifier() {
  2179. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2180. return false;
  2181. }
  2182. return super.isExportDefaultSpecifier();
  2183. }
  2184. parseExportDefaultExpression() {
  2185. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2186. const node = this.startNode();
  2187. this.next();
  2188. return this.flowParseEnumDeclaration(node);
  2189. }
  2190. return super.parseExportDefaultExpression();
  2191. }
  2192. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  2193. if (!this.match(types.question)) return expr;
  2194. if (refNeedsArrowPos) {
  2195. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  2196. if (!result.node) {
  2197. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2198. return expr;
  2199. }
  2200. if (result.error) this.state = result.failState;
  2201. return result.node;
  2202. }
  2203. this.expect(types.question);
  2204. const state = this.state.clone();
  2205. const originalNoArrowAt = this.state.noArrowAt;
  2206. const node = this.startNodeAt(startPos, startLoc);
  2207. let {
  2208. consequent,
  2209. failed
  2210. } = this.tryParseConditionalConsequent();
  2211. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2212. if (failed || invalid.length > 0) {
  2213. const noArrowAt = [...originalNoArrowAt];
  2214. if (invalid.length > 0) {
  2215. this.state = state;
  2216. this.state.noArrowAt = noArrowAt;
  2217. for (let i = 0; i < invalid.length; i++) {
  2218. noArrowAt.push(invalid[i].start);
  2219. }
  2220. ({
  2221. consequent,
  2222. failed
  2223. } = this.tryParseConditionalConsequent());
  2224. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2225. }
  2226. if (failed && valid.length > 1) {
  2227. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2228. }
  2229. if (failed && valid.length === 1) {
  2230. this.state = state;
  2231. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2232. ({
  2233. consequent,
  2234. failed
  2235. } = this.tryParseConditionalConsequent());
  2236. }
  2237. }
  2238. this.getArrowLikeExpressions(consequent, true);
  2239. this.state.noArrowAt = originalNoArrowAt;
  2240. this.expect(types.colon);
  2241. node.test = expr;
  2242. node.consequent = consequent;
  2243. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(noIn, undefined, undefined, undefined));
  2244. return this.finishNode(node, "ConditionalExpression");
  2245. }
  2246. tryParseConditionalConsequent() {
  2247. this.state.noArrowParamsConversionAt.push(this.state.start);
  2248. const consequent = this.parseMaybeAssign();
  2249. const failed = !this.match(types.colon);
  2250. this.state.noArrowParamsConversionAt.pop();
  2251. return {
  2252. consequent,
  2253. failed
  2254. };
  2255. }
  2256. getArrowLikeExpressions(node, disallowInvalid) {
  2257. const stack = [node];
  2258. const arrows = [];
  2259. while (stack.length !== 0) {
  2260. const node = stack.pop();
  2261. if (node.type === "ArrowFunctionExpression") {
  2262. if (node.typeParameters || !node.returnType) {
  2263. this.finishArrowValidation(node);
  2264. } else {
  2265. arrows.push(node);
  2266. }
  2267. stack.push(node.body);
  2268. } else if (node.type === "ConditionalExpression") {
  2269. stack.push(node.consequent);
  2270. stack.push(node.alternate);
  2271. }
  2272. }
  2273. if (disallowInvalid) {
  2274. arrows.forEach(node => this.finishArrowValidation(node));
  2275. return [arrows, []];
  2276. }
  2277. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2278. }
  2279. finishArrowValidation(node) {
  2280. var _node$extra;
  2281. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma);
  2282. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2283. super.checkParams(node, false, true);
  2284. this.scope.exit();
  2285. }
  2286. forwardNoArrowParamsConversionAt(node, parse) {
  2287. let result;
  2288. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2289. this.state.noArrowParamsConversionAt.push(this.state.start);
  2290. result = parse();
  2291. this.state.noArrowParamsConversionAt.pop();
  2292. } else {
  2293. result = parse();
  2294. }
  2295. return result;
  2296. }
  2297. parseParenItem(node, startPos, startLoc) {
  2298. node = super.parseParenItem(node, startPos, startLoc);
  2299. if (this.eat(types.question)) {
  2300. node.optional = true;
  2301. this.resetEndLocation(node);
  2302. }
  2303. if (this.match(types.colon)) {
  2304. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2305. typeCastNode.expression = node;
  2306. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2307. return this.finishNode(typeCastNode, "TypeCastExpression");
  2308. }
  2309. return node;
  2310. }
  2311. assertModuleNodeAllowed(node) {
  2312. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2313. return;
  2314. }
  2315. super.assertModuleNodeAllowed(node);
  2316. }
  2317. parseExport(node) {
  2318. const decl = super.parseExport(node);
  2319. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2320. decl.exportKind = decl.exportKind || "value";
  2321. }
  2322. return decl;
  2323. }
  2324. parseExportDeclaration(node) {
  2325. if (this.isContextual("type")) {
  2326. node.exportKind = "type";
  2327. const declarationNode = this.startNode();
  2328. this.next();
  2329. if (this.match(types.braceL)) {
  2330. node.specifiers = this.parseExportSpecifiers();
  2331. this.parseExportFrom(node);
  2332. return null;
  2333. } else {
  2334. return this.flowParseTypeAlias(declarationNode);
  2335. }
  2336. } else if (this.isContextual("opaque")) {
  2337. node.exportKind = "type";
  2338. const declarationNode = this.startNode();
  2339. this.next();
  2340. return this.flowParseOpaqueType(declarationNode, false);
  2341. } else if (this.isContextual("interface")) {
  2342. node.exportKind = "type";
  2343. const declarationNode = this.startNode();
  2344. this.next();
  2345. return this.flowParseInterface(declarationNode);
  2346. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2347. node.exportKind = "value";
  2348. const declarationNode = this.startNode();
  2349. this.next();
  2350. return this.flowParseEnumDeclaration(declarationNode);
  2351. } else {
  2352. return super.parseExportDeclaration(node);
  2353. }
  2354. }
  2355. eatExportStar(node) {
  2356. if (super.eatExportStar(...arguments)) return true;
  2357. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2358. node.exportKind = "type";
  2359. this.next();
  2360. this.next();
  2361. return true;
  2362. }
  2363. return false;
  2364. }
  2365. maybeParseExportNamespaceSpecifier(node) {
  2366. const pos = this.state.start;
  2367. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2368. if (hasNamespace && node.exportKind === "type") {
  2369. this.unexpected(pos);
  2370. }
  2371. return hasNamespace;
  2372. }
  2373. parseClassId(node, isStatement, optionalId) {
  2374. super.parseClassId(node, isStatement, optionalId);
  2375. if (this.isRelational("<")) {
  2376. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2377. }
  2378. }
  2379. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  2380. const pos = this.state.start;
  2381. if (this.isContextual("declare")) {
  2382. if (this.parseClassMemberFromModifier(classBody, member)) {
  2383. return;
  2384. }
  2385. member.declare = true;
  2386. }
  2387. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  2388. if (member.declare) {
  2389. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  2390. this.raise(pos, FlowErrors.DeclareClassElement);
  2391. } else if (member.value) {
  2392. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2393. }
  2394. }
  2395. }
  2396. getTokenFromCode(code) {
  2397. const next = this.input.charCodeAt(this.state.pos + 1);
  2398. if (code === 123 && next === 124) {
  2399. return this.finishOp(types.braceBarL, 2);
  2400. } else if (this.state.inType && (code === 62 || code === 60)) {
  2401. return this.finishOp(types.relational, 1);
  2402. } else if (isIteratorStart(code, next)) {
  2403. this.state.isIterator = true;
  2404. return super.readWord();
  2405. } else {
  2406. return super.getTokenFromCode(code);
  2407. }
  2408. }
  2409. isAssignable(node, isBinding) {
  2410. switch (node.type) {
  2411. case "Identifier":
  2412. case "ObjectPattern":
  2413. case "ArrayPattern":
  2414. case "AssignmentPattern":
  2415. return true;
  2416. case "ObjectExpression":
  2417. {
  2418. const last = node.properties.length - 1;
  2419. return node.properties.every((prop, i) => {
  2420. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2421. });
  2422. }
  2423. case "ObjectProperty":
  2424. return this.isAssignable(node.value);
  2425. case "SpreadElement":
  2426. return this.isAssignable(node.argument);
  2427. case "ArrayExpression":
  2428. return node.elements.every(element => this.isAssignable(element));
  2429. case "AssignmentExpression":
  2430. return node.operator === "=";
  2431. case "ParenthesizedExpression":
  2432. case "TypeCastExpression":
  2433. return this.isAssignable(node.expression);
  2434. case "MemberExpression":
  2435. case "OptionalMemberExpression":
  2436. return !isBinding;
  2437. default:
  2438. return false;
  2439. }
  2440. }
  2441. toAssignable(node) {
  2442. if (node.type === "TypeCastExpression") {
  2443. return super.toAssignable(this.typeCastToParameter(node));
  2444. } else {
  2445. return super.toAssignable(node);
  2446. }
  2447. }
  2448. toAssignableList(exprList, trailingCommaPos) {
  2449. for (let i = 0; i < exprList.length; i++) {
  2450. const expr = exprList[i];
  2451. if (expr && expr.type === "TypeCastExpression") {
  2452. exprList[i] = this.typeCastToParameter(expr);
  2453. }
  2454. }
  2455. return super.toAssignableList(exprList, trailingCommaPos);
  2456. }
  2457. toReferencedList(exprList, isParenthesizedExpr) {
  2458. for (let i = 0; i < exprList.length; i++) {
  2459. const expr = exprList[i];
  2460. if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2461. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2462. }
  2463. }
  2464. return exprList;
  2465. }
  2466. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  2467. if (expr.type !== "TypeCastExpression") {
  2468. return super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  2469. }
  2470. }
  2471. parseClassProperty(node) {
  2472. if (this.match(types.colon)) {
  2473. node.typeAnnotation = this.flowParseTypeAnnotation();
  2474. }
  2475. return super.parseClassProperty(node);
  2476. }
  2477. parseClassPrivateProperty(node) {
  2478. if (this.match(types.colon)) {
  2479. node.typeAnnotation = this.flowParseTypeAnnotation();
  2480. }
  2481. return super.parseClassPrivateProperty(node);
  2482. }
  2483. isClassMethod() {
  2484. return this.isRelational("<") || super.isClassMethod();
  2485. }
  2486. isClassProperty() {
  2487. return this.match(types.colon) || super.isClassProperty();
  2488. }
  2489. isNonstaticConstructor(method) {
  2490. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2491. }
  2492. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2493. if (method.variance) {
  2494. this.unexpected(method.variance.start);
  2495. }
  2496. delete method.variance;
  2497. if (this.isRelational("<")) {
  2498. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2499. }
  2500. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2501. }
  2502. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2503. if (method.variance) {
  2504. this.unexpected(method.variance.start);
  2505. }
  2506. delete method.variance;
  2507. if (this.isRelational("<")) {
  2508. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2509. }
  2510. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2511. }
  2512. parseClassSuper(node) {
  2513. super.parseClassSuper(node);
  2514. if (node.superClass && this.isRelational("<")) {
  2515. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2516. }
  2517. if (this.isContextual("implements")) {
  2518. this.next();
  2519. const implemented = node.implements = [];
  2520. do {
  2521. const node = this.startNode();
  2522. node.id = this.flowParseRestrictedIdentifier(true);
  2523. if (this.isRelational("<")) {
  2524. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2525. } else {
  2526. node.typeParameters = null;
  2527. }
  2528. implemented.push(this.finishNode(node, "ClassImplements"));
  2529. } while (this.eat(types.comma));
  2530. }
  2531. }
  2532. parsePropertyName(node, isPrivateNameAllowed) {
  2533. const variance = this.flowParseVariance();
  2534. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2535. node.variance = variance;
  2536. return key;
  2537. }
  2538. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  2539. if (prop.variance) {
  2540. this.unexpected(prop.variance.start);
  2541. }
  2542. delete prop.variance;
  2543. let typeParameters;
  2544. if (this.isRelational("<")) {
  2545. typeParameters = this.flowParseTypeParameterDeclaration();
  2546. if (!this.match(types.parenL)) this.unexpected();
  2547. }
  2548. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  2549. if (typeParameters) {
  2550. (prop.value || prop).typeParameters = typeParameters;
  2551. }
  2552. }
  2553. parseAssignableListItemTypes(param) {
  2554. if (this.eat(types.question)) {
  2555. if (param.type !== "Identifier") {
  2556. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  2557. }
  2558. param.optional = true;
  2559. }
  2560. if (this.match(types.colon)) {
  2561. param.typeAnnotation = this.flowParseTypeAnnotation();
  2562. }
  2563. this.resetEndLocation(param);
  2564. return param;
  2565. }
  2566. parseMaybeDefault(startPos, startLoc, left) {
  2567. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2568. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2569. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  2570. }
  2571. return node;
  2572. }
  2573. shouldParseDefaultImport(node) {
  2574. if (!hasTypeImportKind(node)) {
  2575. return super.shouldParseDefaultImport(node);
  2576. }
  2577. return isMaybeDefaultImport(this.state);
  2578. }
  2579. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2580. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2581. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  2582. node.specifiers.push(this.finishNode(specifier, type));
  2583. }
  2584. maybeParseDefaultImportSpecifier(node) {
  2585. node.importKind = "value";
  2586. let kind = null;
  2587. if (this.match(types._typeof)) {
  2588. kind = "typeof";
  2589. } else if (this.isContextual("type")) {
  2590. kind = "type";
  2591. }
  2592. if (kind) {
  2593. const lh = this.lookahead();
  2594. if (kind === "type" && lh.type === types.star) {
  2595. this.unexpected(lh.start);
  2596. }
  2597. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2598. this.next();
  2599. node.importKind = kind;
  2600. }
  2601. }
  2602. return super.maybeParseDefaultImportSpecifier(node);
  2603. }
  2604. parseImportSpecifier(node) {
  2605. const specifier = this.startNode();
  2606. const firstIdentLoc = this.state.start;
  2607. const firstIdent = this.parseIdentifier(true);
  2608. let specifierTypeKind = null;
  2609. if (firstIdent.name === "type") {
  2610. specifierTypeKind = "type";
  2611. } else if (firstIdent.name === "typeof") {
  2612. specifierTypeKind = "typeof";
  2613. }
  2614. let isBinding = false;
  2615. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2616. const as_ident = this.parseIdentifier(true);
  2617. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2618. specifier.imported = as_ident;
  2619. specifier.importKind = specifierTypeKind;
  2620. specifier.local = as_ident.__clone();
  2621. } else {
  2622. specifier.imported = firstIdent;
  2623. specifier.importKind = null;
  2624. specifier.local = this.parseIdentifier();
  2625. }
  2626. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  2627. specifier.imported = this.parseIdentifier(true);
  2628. specifier.importKind = specifierTypeKind;
  2629. if (this.eatContextual("as")) {
  2630. specifier.local = this.parseIdentifier();
  2631. } else {
  2632. isBinding = true;
  2633. specifier.local = specifier.imported.__clone();
  2634. }
  2635. } else {
  2636. isBinding = true;
  2637. specifier.imported = firstIdent;
  2638. specifier.importKind = null;
  2639. specifier.local = specifier.imported.__clone();
  2640. }
  2641. const nodeIsTypeImport = hasTypeImportKind(node);
  2642. const specifierIsTypeImport = hasTypeImportKind(specifier);
  2643. if (nodeIsTypeImport && specifierIsTypeImport) {
  2644. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  2645. }
  2646. if (nodeIsTypeImport || specifierIsTypeImport) {
  2647. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  2648. }
  2649. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  2650. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  2651. }
  2652. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  2653. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2654. }
  2655. parseFunctionParams(node, allowModifiers) {
  2656. const kind = node.kind;
  2657. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  2658. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2659. }
  2660. super.parseFunctionParams(node, allowModifiers);
  2661. }
  2662. parseVarId(decl, kind) {
  2663. super.parseVarId(decl, kind);
  2664. if (this.match(types.colon)) {
  2665. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  2666. this.resetEndLocation(decl.id);
  2667. }
  2668. }
  2669. parseAsyncArrowFromCallExpression(node, call) {
  2670. if (this.match(types.colon)) {
  2671. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2672. this.state.noAnonFunctionType = true;
  2673. node.returnType = this.flowParseTypeAnnotation();
  2674. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2675. }
  2676. return super.parseAsyncArrowFromCallExpression(node, call);
  2677. }
  2678. shouldParseAsyncArrow() {
  2679. return this.match(types.colon) || super.shouldParseAsyncArrow();
  2680. }
  2681. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  2682. let state = null;
  2683. let jsx;
  2684. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  2685. state = this.state.clone();
  2686. jsx = this.tryParse(() => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  2687. if (!jsx.error) return jsx.node;
  2688. const {
  2689. context
  2690. } = this.state;
  2691. if (context[context.length - 1] === types$1.j_oTag) {
  2692. context.length -= 2;
  2693. } else if (context[context.length - 1] === types$1.j_expr) {
  2694. context.length -= 1;
  2695. }
  2696. }
  2697. if (jsx && jsx.error || this.isRelational("<")) {
  2698. state = state || this.state.clone();
  2699. let typeParameters;
  2700. const arrow = this.tryParse(() => {
  2701. typeParameters = this.flowParseTypeParameterDeclaration();
  2702. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  2703. arrowExpression.typeParameters = typeParameters;
  2704. this.resetStartLocationFromNode(arrowExpression, typeParameters);
  2705. return arrowExpression;
  2706. }, state);
  2707. const arrowExpression = arrow.node && arrow.node.type === "ArrowFunctionExpression" ? arrow.node : null;
  2708. if (!arrow.error && arrowExpression) return arrowExpression;
  2709. if (jsx && jsx.node) {
  2710. this.state = jsx.failState;
  2711. return jsx.node;
  2712. }
  2713. if (arrowExpression) {
  2714. this.state = arrow.failState;
  2715. return arrowExpression;
  2716. }
  2717. if (jsx && jsx.thrown) throw jsx.error;
  2718. if (arrow.thrown) throw arrow.error;
  2719. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  2720. }
  2721. return super.parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  2722. }
  2723. parseArrow(node) {
  2724. if (this.match(types.colon)) {
  2725. const result = this.tryParse(() => {
  2726. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2727. this.state.noAnonFunctionType = true;
  2728. const typeNode = this.startNode();
  2729. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2730. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2731. if (this.canInsertSemicolon()) this.unexpected();
  2732. if (!this.match(types.arrow)) this.unexpected();
  2733. return typeNode;
  2734. });
  2735. if (result.thrown) return null;
  2736. if (result.error) this.state = result.failState;
  2737. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  2738. }
  2739. return super.parseArrow(node);
  2740. }
  2741. shouldParseArrow() {
  2742. return this.match(types.colon) || super.shouldParseArrow();
  2743. }
  2744. setArrowFunctionParameters(node, params) {
  2745. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2746. node.params = params;
  2747. } else {
  2748. super.setArrowFunctionParameters(node, params);
  2749. }
  2750. }
  2751. checkParams(node, allowDuplicates, isArrowFunction) {
  2752. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2753. return;
  2754. }
  2755. return super.checkParams(...arguments);
  2756. }
  2757. parseParenAndDistinguishExpression(canBeArrow) {
  2758. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  2759. }
  2760. parseSubscripts(base, startPos, startLoc, noCalls) {
  2761. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  2762. this.next();
  2763. const node = this.startNodeAt(startPos, startLoc);
  2764. node.callee = base;
  2765. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2766. base = this.finishNode(node, "CallExpression");
  2767. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  2768. const state = this.state.clone();
  2769. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  2770. if (!arrow.error && !arrow.aborted) return arrow.node;
  2771. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  2772. if (result.node && !result.error) return result.node;
  2773. if (arrow.node) {
  2774. this.state = arrow.failState;
  2775. return arrow.node;
  2776. }
  2777. if (result.node) {
  2778. this.state = result.failState;
  2779. return result.node;
  2780. }
  2781. throw arrow.error || result.error;
  2782. }
  2783. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  2784. }
  2785. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  2786. if (this.match(types.questionDot) && this.isLookaheadRelational("<")) {
  2787. subscriptState.optionalChainMember = true;
  2788. if (noCalls) {
  2789. subscriptState.stop = true;
  2790. return base;
  2791. }
  2792. this.next();
  2793. const node = this.startNodeAt(startPos, startLoc);
  2794. node.callee = base;
  2795. node.typeArguments = this.flowParseTypeParameterInstantiation();
  2796. this.expect(types.parenL);
  2797. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2798. node.optional = true;
  2799. return this.finishCallExpression(node, true);
  2800. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  2801. const node = this.startNodeAt(startPos, startLoc);
  2802. node.callee = base;
  2803. const result = this.tryParse(() => {
  2804. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  2805. this.expect(types.parenL);
  2806. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  2807. if (subscriptState.optionalChainMember) node.optional = false;
  2808. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  2809. });
  2810. if (result.node) {
  2811. if (result.error) this.state = result.failState;
  2812. return result.node;
  2813. }
  2814. }
  2815. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  2816. }
  2817. parseNewArguments(node) {
  2818. let targs = null;
  2819. if (this.shouldParseTypes() && this.isRelational("<")) {
  2820. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  2821. }
  2822. node.typeArguments = targs;
  2823. super.parseNewArguments(node);
  2824. }
  2825. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  2826. const node = this.startNodeAt(startPos, startLoc);
  2827. this.parseFunctionParams(node);
  2828. if (!this.parseArrow(node)) return;
  2829. return this.parseArrowExpression(node, undefined, true);
  2830. }
  2831. readToken_mult_modulo(code) {
  2832. const next = this.input.charCodeAt(this.state.pos + 1);
  2833. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  2834. this.state.hasFlowComment = false;
  2835. this.state.pos += 2;
  2836. this.nextToken();
  2837. return;
  2838. }
  2839. super.readToken_mult_modulo(code);
  2840. }
  2841. readToken_pipe_amp(code) {
  2842. const next = this.input.charCodeAt(this.state.pos + 1);
  2843. if (code === 124 && next === 125) {
  2844. this.finishOp(types.braceBarR, 2);
  2845. return;
  2846. }
  2847. super.readToken_pipe_amp(code);
  2848. }
  2849. parseTopLevel(file, program) {
  2850. const fileNode = super.parseTopLevel(file, program);
  2851. if (this.state.hasFlowComment) {
  2852. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  2853. }
  2854. return fileNode;
  2855. }
  2856. skipBlockComment() {
  2857. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  2858. if (this.state.hasFlowComment) {
  2859. this.unexpected(null, FlowErrors.NestedFlowComment);
  2860. }
  2861. this.hasFlowCommentCompletion();
  2862. this.state.pos += this.skipFlowComment();
  2863. this.state.hasFlowComment = true;
  2864. return;
  2865. }
  2866. if (this.state.hasFlowComment) {
  2867. const end = this.input.indexOf("*-/", this.state.pos += 2);
  2868. if (end === -1) {
  2869. throw this.raise(this.state.pos - 2, Errors.UnterminatedComment);
  2870. }
  2871. this.state.pos = end + 3;
  2872. return;
  2873. }
  2874. super.skipBlockComment();
  2875. }
  2876. skipFlowComment() {
  2877. const {
  2878. pos
  2879. } = this.state;
  2880. let shiftToFirstNonWhiteSpace = 2;
  2881. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  2882. shiftToFirstNonWhiteSpace++;
  2883. }
  2884. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  2885. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  2886. if (ch2 === 58 && ch3 === 58) {
  2887. return shiftToFirstNonWhiteSpace + 2;
  2888. }
  2889. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  2890. return shiftToFirstNonWhiteSpace + 12;
  2891. }
  2892. if (ch2 === 58 && ch3 !== 58) {
  2893. return shiftToFirstNonWhiteSpace;
  2894. }
  2895. return false;
  2896. }
  2897. hasFlowCommentCompletion() {
  2898. const end = this.input.indexOf("*/", this.state.pos);
  2899. if (end === -1) {
  2900. throw this.raise(this.state.pos, Errors.UnterminatedComment);
  2901. }
  2902. }
  2903. flowEnumErrorBooleanMemberNotInitialized(pos, {
  2904. enumName,
  2905. memberName
  2906. }) {
  2907. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  2908. }
  2909. flowEnumErrorInvalidMemberName(pos, {
  2910. enumName,
  2911. memberName
  2912. }) {
  2913. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  2914. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  2915. }
  2916. flowEnumErrorDuplicateMemberName(pos, {
  2917. enumName,
  2918. memberName
  2919. }) {
  2920. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  2921. }
  2922. flowEnumErrorInconsistentMemberValues(pos, {
  2923. enumName
  2924. }) {
  2925. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  2926. }
  2927. flowEnumErrorInvalidExplicitType(pos, {
  2928. enumName,
  2929. suppliedType
  2930. }) {
  2931. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  2932. }
  2933. flowEnumErrorInvalidMemberInitializer(pos, {
  2934. enumName,
  2935. explicitType,
  2936. memberName
  2937. }) {
  2938. let message = null;
  2939. switch (explicitType) {
  2940. case "boolean":
  2941. case "number":
  2942. case "string":
  2943. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  2944. break;
  2945. case "symbol":
  2946. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  2947. break;
  2948. default:
  2949. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  2950. }
  2951. return this.raise(pos, message, enumName, memberName, explicitType);
  2952. }
  2953. flowEnumErrorNumberMemberNotInitialized(pos, {
  2954. enumName,
  2955. memberName
  2956. }) {
  2957. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  2958. }
  2959. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  2960. enumName
  2961. }) {
  2962. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  2963. }
  2964. flowEnumMemberInit() {
  2965. const startPos = this.state.start;
  2966. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  2967. switch (this.state.type) {
  2968. case types.num:
  2969. {
  2970. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  2971. if (endOfInit()) {
  2972. return {
  2973. type: "number",
  2974. pos: literal.start,
  2975. value: literal
  2976. };
  2977. }
  2978. return {
  2979. type: "invalid",
  2980. pos: startPos
  2981. };
  2982. }
  2983. case types.string:
  2984. {
  2985. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  2986. if (endOfInit()) {
  2987. return {
  2988. type: "string",
  2989. pos: literal.start,
  2990. value: literal
  2991. };
  2992. }
  2993. return {
  2994. type: "invalid",
  2995. pos: startPos
  2996. };
  2997. }
  2998. case types._true:
  2999. case types._false:
  3000. {
  3001. const literal = this.parseBooleanLiteral();
  3002. if (endOfInit()) {
  3003. return {
  3004. type: "boolean",
  3005. pos: literal.start,
  3006. value: literal
  3007. };
  3008. }
  3009. return {
  3010. type: "invalid",
  3011. pos: startPos
  3012. };
  3013. }
  3014. default:
  3015. return {
  3016. type: "invalid",
  3017. pos: startPos
  3018. };
  3019. }
  3020. }
  3021. flowEnumMemberRaw() {
  3022. const pos = this.state.start;
  3023. const id = this.parseIdentifier(true);
  3024. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3025. type: "none",
  3026. pos
  3027. };
  3028. return {
  3029. id,
  3030. init
  3031. };
  3032. }
  3033. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3034. const {
  3035. explicitType
  3036. } = context;
  3037. if (explicitType === null) {
  3038. return;
  3039. }
  3040. if (explicitType !== expectedType) {
  3041. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3042. }
  3043. }
  3044. flowEnumMembers({
  3045. enumName,
  3046. explicitType
  3047. }) {
  3048. const seenNames = new Set();
  3049. const members = {
  3050. booleanMembers: [],
  3051. numberMembers: [],
  3052. stringMembers: [],
  3053. defaultedMembers: []
  3054. };
  3055. while (!this.match(types.braceR)) {
  3056. const memberNode = this.startNode();
  3057. const {
  3058. id,
  3059. init
  3060. } = this.flowEnumMemberRaw();
  3061. const memberName = id.name;
  3062. if (memberName === "") {
  3063. continue;
  3064. }
  3065. if (/^[a-z]/.test(memberName)) {
  3066. this.flowEnumErrorInvalidMemberName(id.start, {
  3067. enumName,
  3068. memberName
  3069. });
  3070. }
  3071. if (seenNames.has(memberName)) {
  3072. this.flowEnumErrorDuplicateMemberName(id.start, {
  3073. enumName,
  3074. memberName
  3075. });
  3076. }
  3077. seenNames.add(memberName);
  3078. const context = {
  3079. enumName,
  3080. explicitType,
  3081. memberName
  3082. };
  3083. memberNode.id = id;
  3084. switch (init.type) {
  3085. case "boolean":
  3086. {
  3087. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3088. memberNode.init = init.value;
  3089. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3090. break;
  3091. }
  3092. case "number":
  3093. {
  3094. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3095. memberNode.init = init.value;
  3096. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3097. break;
  3098. }
  3099. case "string":
  3100. {
  3101. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3102. memberNode.init = init.value;
  3103. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3104. break;
  3105. }
  3106. case "invalid":
  3107. {
  3108. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3109. }
  3110. case "none":
  3111. {
  3112. switch (explicitType) {
  3113. case "boolean":
  3114. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3115. break;
  3116. case "number":
  3117. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3118. break;
  3119. default:
  3120. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3121. }
  3122. }
  3123. }
  3124. if (!this.match(types.braceR)) {
  3125. this.expect(types.comma);
  3126. }
  3127. }
  3128. return members;
  3129. }
  3130. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3131. enumName
  3132. }) {
  3133. if (initializedMembers.length === 0) {
  3134. return defaultedMembers;
  3135. } else if (defaultedMembers.length === 0) {
  3136. return initializedMembers;
  3137. } else if (defaultedMembers.length > initializedMembers.length) {
  3138. for (let _i = 0; _i < initializedMembers.length; _i++) {
  3139. const member = initializedMembers[_i];
  3140. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3141. enumName
  3142. });
  3143. }
  3144. return defaultedMembers;
  3145. } else {
  3146. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  3147. const member = defaultedMembers[_i2];
  3148. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3149. enumName
  3150. });
  3151. }
  3152. return initializedMembers;
  3153. }
  3154. }
  3155. flowEnumParseExplicitType({
  3156. enumName
  3157. }) {
  3158. if (this.eatContextual("of")) {
  3159. if (!this.match(types.name)) {
  3160. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3161. enumName,
  3162. suppliedType: null
  3163. });
  3164. }
  3165. const {
  3166. value
  3167. } = this.state;
  3168. this.next();
  3169. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3170. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3171. enumName,
  3172. suppliedType: value
  3173. });
  3174. }
  3175. return value;
  3176. }
  3177. return null;
  3178. }
  3179. flowEnumBody(node, {
  3180. enumName,
  3181. nameLoc
  3182. }) {
  3183. const explicitType = this.flowEnumParseExplicitType({
  3184. enumName
  3185. });
  3186. this.expect(types.braceL);
  3187. const members = this.flowEnumMembers({
  3188. enumName,
  3189. explicitType
  3190. });
  3191. switch (explicitType) {
  3192. case "boolean":
  3193. node.explicitType = true;
  3194. node.members = members.booleanMembers;
  3195. this.expect(types.braceR);
  3196. return this.finishNode(node, "EnumBooleanBody");
  3197. case "number":
  3198. node.explicitType = true;
  3199. node.members = members.numberMembers;
  3200. this.expect(types.braceR);
  3201. return this.finishNode(node, "EnumNumberBody");
  3202. case "string":
  3203. node.explicitType = true;
  3204. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3205. enumName
  3206. });
  3207. this.expect(types.braceR);
  3208. return this.finishNode(node, "EnumStringBody");
  3209. case "symbol":
  3210. node.members = members.defaultedMembers;
  3211. this.expect(types.braceR);
  3212. return this.finishNode(node, "EnumSymbolBody");
  3213. default:
  3214. {
  3215. const empty = () => {
  3216. node.members = [];
  3217. this.expect(types.braceR);
  3218. return this.finishNode(node, "EnumStringBody");
  3219. };
  3220. node.explicitType = false;
  3221. const boolsLen = members.booleanMembers.length;
  3222. const numsLen = members.numberMembers.length;
  3223. const strsLen = members.stringMembers.length;
  3224. const defaultedLen = members.defaultedMembers.length;
  3225. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3226. return empty();
  3227. } else if (!boolsLen && !numsLen) {
  3228. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3229. enumName
  3230. });
  3231. this.expect(types.braceR);
  3232. return this.finishNode(node, "EnumStringBody");
  3233. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3234. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  3235. const member = _members$defaultedMem[_i3];
  3236. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3237. enumName,
  3238. memberName: member.id.name
  3239. });
  3240. }
  3241. node.members = members.booleanMembers;
  3242. this.expect(types.braceR);
  3243. return this.finishNode(node, "EnumBooleanBody");
  3244. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3245. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  3246. const member = _members$defaultedMem2[_i4];
  3247. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3248. enumName,
  3249. memberName: member.id.name
  3250. });
  3251. }
  3252. node.members = members.numberMembers;
  3253. this.expect(types.braceR);
  3254. return this.finishNode(node, "EnumNumberBody");
  3255. } else {
  3256. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3257. enumName
  3258. });
  3259. return empty();
  3260. }
  3261. }
  3262. }
  3263. }
  3264. flowParseEnumDeclaration(node) {
  3265. const id = this.parseIdentifier();
  3266. node.id = id;
  3267. node.body = this.flowEnumBody(this.startNode(), {
  3268. enumName: id.name,
  3269. nameLoc: id.start
  3270. });
  3271. return this.finishNode(node, "EnumDeclaration");
  3272. }
  3273. updateContext(prevType) {
  3274. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  3275. this.state.exprAllowed = false;
  3276. } else {
  3277. super.updateContext(prevType);
  3278. }
  3279. }
  3280. });
  3281. const entities = {
  3282. quot: "\u0022",
  3283. amp: "&",
  3284. apos: "\u0027",
  3285. lt: "<",
  3286. gt: ">",
  3287. nbsp: "\u00A0",
  3288. iexcl: "\u00A1",
  3289. cent: "\u00A2",
  3290. pound: "\u00A3",
  3291. curren: "\u00A4",
  3292. yen: "\u00A5",
  3293. brvbar: "\u00A6",
  3294. sect: "\u00A7",
  3295. uml: "\u00A8",
  3296. copy: "\u00A9",
  3297. ordf: "\u00AA",
  3298. laquo: "\u00AB",
  3299. not: "\u00AC",
  3300. shy: "\u00AD",
  3301. reg: "\u00AE",
  3302. macr: "\u00AF",
  3303. deg: "\u00B0",
  3304. plusmn: "\u00B1",
  3305. sup2: "\u00B2",
  3306. sup3: "\u00B3",
  3307. acute: "\u00B4",
  3308. micro: "\u00B5",
  3309. para: "\u00B6",
  3310. middot: "\u00B7",
  3311. cedil: "\u00B8",
  3312. sup1: "\u00B9",
  3313. ordm: "\u00BA",
  3314. raquo: "\u00BB",
  3315. frac14: "\u00BC",
  3316. frac12: "\u00BD",
  3317. frac34: "\u00BE",
  3318. iquest: "\u00BF",
  3319. Agrave: "\u00C0",
  3320. Aacute: "\u00C1",
  3321. Acirc: "\u00C2",
  3322. Atilde: "\u00C3",
  3323. Auml: "\u00C4",
  3324. Aring: "\u00C5",
  3325. AElig: "\u00C6",
  3326. Ccedil: "\u00C7",
  3327. Egrave: "\u00C8",
  3328. Eacute: "\u00C9",
  3329. Ecirc: "\u00CA",
  3330. Euml: "\u00CB",
  3331. Igrave: "\u00CC",
  3332. Iacute: "\u00CD",
  3333. Icirc: "\u00CE",
  3334. Iuml: "\u00CF",
  3335. ETH: "\u00D0",
  3336. Ntilde: "\u00D1",
  3337. Ograve: "\u00D2",
  3338. Oacute: "\u00D3",
  3339. Ocirc: "\u00D4",
  3340. Otilde: "\u00D5",
  3341. Ouml: "\u00D6",
  3342. times: "\u00D7",
  3343. Oslash: "\u00D8",
  3344. Ugrave: "\u00D9",
  3345. Uacute: "\u00DA",
  3346. Ucirc: "\u00DB",
  3347. Uuml: "\u00DC",
  3348. Yacute: "\u00DD",
  3349. THORN: "\u00DE",
  3350. szlig: "\u00DF",
  3351. agrave: "\u00E0",
  3352. aacute: "\u00E1",
  3353. acirc: "\u00E2",
  3354. atilde: "\u00E3",
  3355. auml: "\u00E4",
  3356. aring: "\u00E5",
  3357. aelig: "\u00E6",
  3358. ccedil: "\u00E7",
  3359. egrave: "\u00E8",
  3360. eacute: "\u00E9",
  3361. ecirc: "\u00EA",
  3362. euml: "\u00EB",
  3363. igrave: "\u00EC",
  3364. iacute: "\u00ED",
  3365. icirc: "\u00EE",
  3366. iuml: "\u00EF",
  3367. eth: "\u00F0",
  3368. ntilde: "\u00F1",
  3369. ograve: "\u00F2",
  3370. oacute: "\u00F3",
  3371. ocirc: "\u00F4",
  3372. otilde: "\u00F5",
  3373. ouml: "\u00F6",
  3374. divide: "\u00F7",
  3375. oslash: "\u00F8",
  3376. ugrave: "\u00F9",
  3377. uacute: "\u00FA",
  3378. ucirc: "\u00FB",
  3379. uuml: "\u00FC",
  3380. yacute: "\u00FD",
  3381. thorn: "\u00FE",
  3382. yuml: "\u00FF",
  3383. OElig: "\u0152",
  3384. oelig: "\u0153",
  3385. Scaron: "\u0160",
  3386. scaron: "\u0161",
  3387. Yuml: "\u0178",
  3388. fnof: "\u0192",
  3389. circ: "\u02C6",
  3390. tilde: "\u02DC",
  3391. Alpha: "\u0391",
  3392. Beta: "\u0392",
  3393. Gamma: "\u0393",
  3394. Delta: "\u0394",
  3395. Epsilon: "\u0395",
  3396. Zeta: "\u0396",
  3397. Eta: "\u0397",
  3398. Theta: "\u0398",
  3399. Iota: "\u0399",
  3400. Kappa: "\u039A",
  3401. Lambda: "\u039B",
  3402. Mu: "\u039C",
  3403. Nu: "\u039D",
  3404. Xi: "\u039E",
  3405. Omicron: "\u039F",
  3406. Pi: "\u03A0",
  3407. Rho: "\u03A1",
  3408. Sigma: "\u03A3",
  3409. Tau: "\u03A4",
  3410. Upsilon: "\u03A5",
  3411. Phi: "\u03A6",
  3412. Chi: "\u03A7",
  3413. Psi: "\u03A8",
  3414. Omega: "\u03A9",
  3415. alpha: "\u03B1",
  3416. beta: "\u03B2",
  3417. gamma: "\u03B3",
  3418. delta: "\u03B4",
  3419. epsilon: "\u03B5",
  3420. zeta: "\u03B6",
  3421. eta: "\u03B7",
  3422. theta: "\u03B8",
  3423. iota: "\u03B9",
  3424. kappa: "\u03BA",
  3425. lambda: "\u03BB",
  3426. mu: "\u03BC",
  3427. nu: "\u03BD",
  3428. xi: "\u03BE",
  3429. omicron: "\u03BF",
  3430. pi: "\u03C0",
  3431. rho: "\u03C1",
  3432. sigmaf: "\u03C2",
  3433. sigma: "\u03C3",
  3434. tau: "\u03C4",
  3435. upsilon: "\u03C5",
  3436. phi: "\u03C6",
  3437. chi: "\u03C7",
  3438. psi: "\u03C8",
  3439. omega: "\u03C9",
  3440. thetasym: "\u03D1",
  3441. upsih: "\u03D2",
  3442. piv: "\u03D6",
  3443. ensp: "\u2002",
  3444. emsp: "\u2003",
  3445. thinsp: "\u2009",
  3446. zwnj: "\u200C",
  3447. zwj: "\u200D",
  3448. lrm: "\u200E",
  3449. rlm: "\u200F",
  3450. ndash: "\u2013",
  3451. mdash: "\u2014",
  3452. lsquo: "\u2018",
  3453. rsquo: "\u2019",
  3454. sbquo: "\u201A",
  3455. ldquo: "\u201C",
  3456. rdquo: "\u201D",
  3457. bdquo: "\u201E",
  3458. dagger: "\u2020",
  3459. Dagger: "\u2021",
  3460. bull: "\u2022",
  3461. hellip: "\u2026",
  3462. permil: "\u2030",
  3463. prime: "\u2032",
  3464. Prime: "\u2033",
  3465. lsaquo: "\u2039",
  3466. rsaquo: "\u203A",
  3467. oline: "\u203E",
  3468. frasl: "\u2044",
  3469. euro: "\u20AC",
  3470. image: "\u2111",
  3471. weierp: "\u2118",
  3472. real: "\u211C",
  3473. trade: "\u2122",
  3474. alefsym: "\u2135",
  3475. larr: "\u2190",
  3476. uarr: "\u2191",
  3477. rarr: "\u2192",
  3478. darr: "\u2193",
  3479. harr: "\u2194",
  3480. crarr: "\u21B5",
  3481. lArr: "\u21D0",
  3482. uArr: "\u21D1",
  3483. rArr: "\u21D2",
  3484. dArr: "\u21D3",
  3485. hArr: "\u21D4",
  3486. forall: "\u2200",
  3487. part: "\u2202",
  3488. exist: "\u2203",
  3489. empty: "\u2205",
  3490. nabla: "\u2207",
  3491. isin: "\u2208",
  3492. notin: "\u2209",
  3493. ni: "\u220B",
  3494. prod: "\u220F",
  3495. sum: "\u2211",
  3496. minus: "\u2212",
  3497. lowast: "\u2217",
  3498. radic: "\u221A",
  3499. prop: "\u221D",
  3500. infin: "\u221E",
  3501. ang: "\u2220",
  3502. and: "\u2227",
  3503. or: "\u2228",
  3504. cap: "\u2229",
  3505. cup: "\u222A",
  3506. int: "\u222B",
  3507. there4: "\u2234",
  3508. sim: "\u223C",
  3509. cong: "\u2245",
  3510. asymp: "\u2248",
  3511. ne: "\u2260",
  3512. equiv: "\u2261",
  3513. le: "\u2264",
  3514. ge: "\u2265",
  3515. sub: "\u2282",
  3516. sup: "\u2283",
  3517. nsub: "\u2284",
  3518. sube: "\u2286",
  3519. supe: "\u2287",
  3520. oplus: "\u2295",
  3521. otimes: "\u2297",
  3522. perp: "\u22A5",
  3523. sdot: "\u22C5",
  3524. lceil: "\u2308",
  3525. rceil: "\u2309",
  3526. lfloor: "\u230A",
  3527. rfloor: "\u230B",
  3528. lang: "\u2329",
  3529. rang: "\u232A",
  3530. loz: "\u25CA",
  3531. spades: "\u2660",
  3532. clubs: "\u2663",
  3533. hearts: "\u2665",
  3534. diams: "\u2666"
  3535. };
  3536. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3537. const DECIMAL_NUMBER = /^\d+$/;
  3538. const JsxErrors = Object.freeze({
  3539. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3540. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3541. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3542. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3543. UnterminatedJsxContent: "Unterminated JSX contents",
  3544. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3545. });
  3546. types$1.j_oTag = new TokContext("<tag", false);
  3547. types$1.j_cTag = new TokContext("</tag", false);
  3548. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3549. types.jsxName = new TokenType("jsxName");
  3550. types.jsxText = new TokenType("jsxText", {
  3551. beforeExpr: true
  3552. });
  3553. types.jsxTagStart = new TokenType("jsxTagStart", {
  3554. startsExpr: true
  3555. });
  3556. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3557. types.jsxTagStart.updateContext = function () {
  3558. this.state.context.push(types$1.j_expr);
  3559. this.state.context.push(types$1.j_oTag);
  3560. this.state.exprAllowed = false;
  3561. };
  3562. types.jsxTagEnd.updateContext = function (prevType) {
  3563. const out = this.state.context.pop();
  3564. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3565. this.state.context.pop();
  3566. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3567. } else {
  3568. this.state.exprAllowed = true;
  3569. }
  3570. };
  3571. function isFragment(object) {
  3572. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  3573. }
  3574. function getQualifiedJSXName(object) {
  3575. if (object.type === "JSXIdentifier") {
  3576. return object.name;
  3577. }
  3578. if (object.type === "JSXNamespacedName") {
  3579. return object.namespace.name + ":" + object.name.name;
  3580. }
  3581. if (object.type === "JSXMemberExpression") {
  3582. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  3583. }
  3584. throw new Error("Node had unexpected type: " + object.type);
  3585. }
  3586. var jsx = (superClass => class extends superClass {
  3587. jsxReadToken() {
  3588. let out = "";
  3589. let chunkStart = this.state.pos;
  3590. for (;;) {
  3591. if (this.state.pos >= this.length) {
  3592. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  3593. }
  3594. const ch = this.input.charCodeAt(this.state.pos);
  3595. switch (ch) {
  3596. case 60:
  3597. case 123:
  3598. if (this.state.pos === this.state.start) {
  3599. if (ch === 60 && this.state.exprAllowed) {
  3600. ++this.state.pos;
  3601. return this.finishToken(types.jsxTagStart);
  3602. }
  3603. return super.getTokenFromCode(ch);
  3604. }
  3605. out += this.input.slice(chunkStart, this.state.pos);
  3606. return this.finishToken(types.jsxText, out);
  3607. case 38:
  3608. out += this.input.slice(chunkStart, this.state.pos);
  3609. out += this.jsxReadEntity();
  3610. chunkStart = this.state.pos;
  3611. break;
  3612. default:
  3613. if (isNewLine(ch)) {
  3614. out += this.input.slice(chunkStart, this.state.pos);
  3615. out += this.jsxReadNewLine(true);
  3616. chunkStart = this.state.pos;
  3617. } else {
  3618. ++this.state.pos;
  3619. }
  3620. }
  3621. }
  3622. }
  3623. jsxReadNewLine(normalizeCRLF) {
  3624. const ch = this.input.charCodeAt(this.state.pos);
  3625. let out;
  3626. ++this.state.pos;
  3627. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  3628. ++this.state.pos;
  3629. out = normalizeCRLF ? "\n" : "\r\n";
  3630. } else {
  3631. out = String.fromCharCode(ch);
  3632. }
  3633. ++this.state.curLine;
  3634. this.state.lineStart = this.state.pos;
  3635. return out;
  3636. }
  3637. jsxReadString(quote) {
  3638. let out = "";
  3639. let chunkStart = ++this.state.pos;
  3640. for (;;) {
  3641. if (this.state.pos >= this.length) {
  3642. throw this.raise(this.state.start, Errors.UnterminatedString);
  3643. }
  3644. const ch = this.input.charCodeAt(this.state.pos);
  3645. if (ch === quote) break;
  3646. if (ch === 38) {
  3647. out += this.input.slice(chunkStart, this.state.pos);
  3648. out += this.jsxReadEntity();
  3649. chunkStart = this.state.pos;
  3650. } else if (isNewLine(ch)) {
  3651. out += this.input.slice(chunkStart, this.state.pos);
  3652. out += this.jsxReadNewLine(false);
  3653. chunkStart = this.state.pos;
  3654. } else {
  3655. ++this.state.pos;
  3656. }
  3657. }
  3658. out += this.input.slice(chunkStart, this.state.pos++);
  3659. return this.finishToken(types.string, out);
  3660. }
  3661. jsxReadEntity() {
  3662. let str = "";
  3663. let count = 0;
  3664. let entity;
  3665. let ch = this.input[this.state.pos];
  3666. const startPos = ++this.state.pos;
  3667. while (this.state.pos < this.length && count++ < 10) {
  3668. ch = this.input[this.state.pos++];
  3669. if (ch === ";") {
  3670. if (str[0] === "#") {
  3671. if (str[1] === "x") {
  3672. str = str.substr(2);
  3673. if (HEX_NUMBER.test(str)) {
  3674. entity = String.fromCodePoint(parseInt(str, 16));
  3675. }
  3676. } else {
  3677. str = str.substr(1);
  3678. if (DECIMAL_NUMBER.test(str)) {
  3679. entity = String.fromCodePoint(parseInt(str, 10));
  3680. }
  3681. }
  3682. } else {
  3683. entity = entities[str];
  3684. }
  3685. break;
  3686. }
  3687. str += ch;
  3688. }
  3689. if (!entity) {
  3690. this.state.pos = startPos;
  3691. return "&";
  3692. }
  3693. return entity;
  3694. }
  3695. jsxReadWord() {
  3696. let ch;
  3697. const start = this.state.pos;
  3698. do {
  3699. ch = this.input.charCodeAt(++this.state.pos);
  3700. } while (isIdentifierChar(ch) || ch === 45);
  3701. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  3702. }
  3703. jsxParseIdentifier() {
  3704. const node = this.startNode();
  3705. if (this.match(types.jsxName)) {
  3706. node.name = this.state.value;
  3707. } else if (this.state.type.keyword) {
  3708. node.name = this.state.type.keyword;
  3709. } else {
  3710. this.unexpected();
  3711. }
  3712. this.next();
  3713. return this.finishNode(node, "JSXIdentifier");
  3714. }
  3715. jsxParseNamespacedName() {
  3716. const startPos = this.state.start;
  3717. const startLoc = this.state.startLoc;
  3718. const name = this.jsxParseIdentifier();
  3719. if (!this.eat(types.colon)) return name;
  3720. const node = this.startNodeAt(startPos, startLoc);
  3721. node.namespace = name;
  3722. node.name = this.jsxParseIdentifier();
  3723. return this.finishNode(node, "JSXNamespacedName");
  3724. }
  3725. jsxParseElementName() {
  3726. const startPos = this.state.start;
  3727. const startLoc = this.state.startLoc;
  3728. let node = this.jsxParseNamespacedName();
  3729. if (node.type === "JSXNamespacedName") {
  3730. return node;
  3731. }
  3732. while (this.eat(types.dot)) {
  3733. const newNode = this.startNodeAt(startPos, startLoc);
  3734. newNode.object = node;
  3735. newNode.property = this.jsxParseIdentifier();
  3736. node = this.finishNode(newNode, "JSXMemberExpression");
  3737. }
  3738. return node;
  3739. }
  3740. jsxParseAttributeValue() {
  3741. let node;
  3742. switch (this.state.type) {
  3743. case types.braceL:
  3744. node = this.startNode();
  3745. this.next();
  3746. node = this.jsxParseExpressionContainer(node);
  3747. if (node.expression.type === "JSXEmptyExpression") {
  3748. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  3749. }
  3750. return node;
  3751. case types.jsxTagStart:
  3752. case types.string:
  3753. return this.parseExprAtom();
  3754. default:
  3755. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  3756. }
  3757. }
  3758. jsxParseEmptyExpression() {
  3759. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  3760. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  3761. }
  3762. jsxParseSpreadChild(node) {
  3763. this.next();
  3764. node.expression = this.parseExpression();
  3765. this.expect(types.braceR);
  3766. return this.finishNode(node, "JSXSpreadChild");
  3767. }
  3768. jsxParseExpressionContainer(node) {
  3769. if (this.match(types.braceR)) {
  3770. node.expression = this.jsxParseEmptyExpression();
  3771. } else {
  3772. node.expression = this.parseExpression();
  3773. }
  3774. this.expect(types.braceR);
  3775. return this.finishNode(node, "JSXExpressionContainer");
  3776. }
  3777. jsxParseAttribute() {
  3778. const node = this.startNode();
  3779. if (this.eat(types.braceL)) {
  3780. this.expect(types.ellipsis);
  3781. node.argument = this.parseMaybeAssign();
  3782. this.expect(types.braceR);
  3783. return this.finishNode(node, "JSXSpreadAttribute");
  3784. }
  3785. node.name = this.jsxParseNamespacedName();
  3786. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  3787. return this.finishNode(node, "JSXAttribute");
  3788. }
  3789. jsxParseOpeningElementAt(startPos, startLoc) {
  3790. const node = this.startNodeAt(startPos, startLoc);
  3791. if (this.match(types.jsxTagEnd)) {
  3792. this.expect(types.jsxTagEnd);
  3793. return this.finishNode(node, "JSXOpeningFragment");
  3794. }
  3795. node.name = this.jsxParseElementName();
  3796. return this.jsxParseOpeningElementAfterName(node);
  3797. }
  3798. jsxParseOpeningElementAfterName(node) {
  3799. const attributes = [];
  3800. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  3801. attributes.push(this.jsxParseAttribute());
  3802. }
  3803. node.attributes = attributes;
  3804. node.selfClosing = this.eat(types.slash);
  3805. this.expect(types.jsxTagEnd);
  3806. return this.finishNode(node, "JSXOpeningElement");
  3807. }
  3808. jsxParseClosingElementAt(startPos, startLoc) {
  3809. const node = this.startNodeAt(startPos, startLoc);
  3810. if (this.match(types.jsxTagEnd)) {
  3811. this.expect(types.jsxTagEnd);
  3812. return this.finishNode(node, "JSXClosingFragment");
  3813. }
  3814. node.name = this.jsxParseElementName();
  3815. this.expect(types.jsxTagEnd);
  3816. return this.finishNode(node, "JSXClosingElement");
  3817. }
  3818. jsxParseElementAt(startPos, startLoc) {
  3819. const node = this.startNodeAt(startPos, startLoc);
  3820. const children = [];
  3821. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  3822. let closingElement = null;
  3823. if (!openingElement.selfClosing) {
  3824. contents: for (;;) {
  3825. switch (this.state.type) {
  3826. case types.jsxTagStart:
  3827. startPos = this.state.start;
  3828. startLoc = this.state.startLoc;
  3829. this.next();
  3830. if (this.eat(types.slash)) {
  3831. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  3832. break contents;
  3833. }
  3834. children.push(this.jsxParseElementAt(startPos, startLoc));
  3835. break;
  3836. case types.jsxText:
  3837. children.push(this.parseExprAtom());
  3838. break;
  3839. case types.braceL:
  3840. {
  3841. const node = this.startNode();
  3842. this.next();
  3843. if (this.match(types.ellipsis)) {
  3844. children.push(this.jsxParseSpreadChild(node));
  3845. } else {
  3846. children.push(this.jsxParseExpressionContainer(node));
  3847. }
  3848. break;
  3849. }
  3850. default:
  3851. throw this.unexpected();
  3852. }
  3853. }
  3854. if (isFragment(openingElement) && !isFragment(closingElement)) {
  3855. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  3856. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  3857. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3858. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  3859. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  3860. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  3861. }
  3862. }
  3863. }
  3864. if (isFragment(openingElement)) {
  3865. node.openingFragment = openingElement;
  3866. node.closingFragment = closingElement;
  3867. } else {
  3868. node.openingElement = openingElement;
  3869. node.closingElement = closingElement;
  3870. }
  3871. node.children = children;
  3872. if (this.isRelational("<")) {
  3873. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  3874. }
  3875. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  3876. }
  3877. jsxParseElement() {
  3878. const startPos = this.state.start;
  3879. const startLoc = this.state.startLoc;
  3880. this.next();
  3881. return this.jsxParseElementAt(startPos, startLoc);
  3882. }
  3883. parseExprAtom(refExpressionErrors) {
  3884. if (this.match(types.jsxText)) {
  3885. return this.parseLiteral(this.state.value, "JSXText");
  3886. } else if (this.match(types.jsxTagStart)) {
  3887. return this.jsxParseElement();
  3888. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  3889. this.finishToken(types.jsxTagStart);
  3890. return this.jsxParseElement();
  3891. } else {
  3892. return super.parseExprAtom(refExpressionErrors);
  3893. }
  3894. }
  3895. getTokenFromCode(code) {
  3896. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  3897. const context = this.curContext();
  3898. if (context === types$1.j_expr) {
  3899. return this.jsxReadToken();
  3900. }
  3901. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  3902. if (isIdentifierStart(code)) {
  3903. return this.jsxReadWord();
  3904. }
  3905. if (code === 62) {
  3906. ++this.state.pos;
  3907. return this.finishToken(types.jsxTagEnd);
  3908. }
  3909. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  3910. return this.jsxReadString(code);
  3911. }
  3912. }
  3913. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  3914. ++this.state.pos;
  3915. return this.finishToken(types.jsxTagStart);
  3916. }
  3917. return super.getTokenFromCode(code);
  3918. }
  3919. updateContext(prevType) {
  3920. if (this.match(types.braceL)) {
  3921. const curContext = this.curContext();
  3922. if (curContext === types$1.j_oTag) {
  3923. this.state.context.push(types$1.braceExpression);
  3924. } else if (curContext === types$1.j_expr) {
  3925. this.state.context.push(types$1.templateQuasi);
  3926. } else {
  3927. super.updateContext(prevType);
  3928. }
  3929. this.state.exprAllowed = true;
  3930. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  3931. this.state.context.length -= 2;
  3932. this.state.context.push(types$1.j_cTag);
  3933. this.state.exprAllowed = false;
  3934. } else {
  3935. return super.updateContext(prevType);
  3936. }
  3937. }
  3938. });
  3939. class Scope {
  3940. constructor(flags) {
  3941. this.var = [];
  3942. this.lexical = [];
  3943. this.functions = [];
  3944. this.flags = flags;
  3945. }
  3946. }
  3947. class ScopeHandler {
  3948. constructor(raise, inModule) {
  3949. this.scopeStack = [];
  3950. this.undefinedExports = new Map();
  3951. this.undefinedPrivateNames = new Map();
  3952. this.raise = raise;
  3953. this.inModule = inModule;
  3954. }
  3955. get inFunction() {
  3956. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  3957. }
  3958. get allowSuper() {
  3959. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  3960. }
  3961. get allowDirectSuper() {
  3962. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  3963. }
  3964. get inClass() {
  3965. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  3966. }
  3967. get inNonArrowFunction() {
  3968. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  3969. }
  3970. get treatFunctionsAsVar() {
  3971. return this.treatFunctionsAsVarInScope(this.currentScope());
  3972. }
  3973. createScope(flags) {
  3974. return new Scope(flags);
  3975. }
  3976. enter(flags) {
  3977. this.scopeStack.push(this.createScope(flags));
  3978. }
  3979. exit() {
  3980. this.scopeStack.pop();
  3981. }
  3982. treatFunctionsAsVarInScope(scope) {
  3983. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  3984. }
  3985. declareName(name, bindingType, pos) {
  3986. let scope = this.currentScope();
  3987. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  3988. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  3989. if (bindingType & BIND_SCOPE_FUNCTION) {
  3990. scope.functions.push(name);
  3991. } else {
  3992. scope.lexical.push(name);
  3993. }
  3994. if (bindingType & BIND_SCOPE_LEXICAL) {
  3995. this.maybeExportDefined(scope, name);
  3996. }
  3997. } else if (bindingType & BIND_SCOPE_VAR) {
  3998. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  3999. scope = this.scopeStack[i];
  4000. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4001. scope.var.push(name);
  4002. this.maybeExportDefined(scope, name);
  4003. if (scope.flags & SCOPE_VAR) break;
  4004. }
  4005. }
  4006. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4007. this.undefinedExports.delete(name);
  4008. }
  4009. }
  4010. maybeExportDefined(scope, name) {
  4011. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  4012. this.undefinedExports.delete(name);
  4013. }
  4014. }
  4015. checkRedeclarationInScope(scope, name, bindingType, pos) {
  4016. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  4017. this.raise(pos, Errors.VarRedeclaration, name);
  4018. }
  4019. }
  4020. isRedeclaredInScope(scope, name, bindingType) {
  4021. if (!(bindingType & BIND_KIND_VALUE)) return false;
  4022. if (bindingType & BIND_SCOPE_LEXICAL) {
  4023. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  4024. }
  4025. if (bindingType & BIND_SCOPE_FUNCTION) {
  4026. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  4027. }
  4028. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  4029. }
  4030. checkLocalExport(id) {
  4031. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) {
  4032. this.undefinedExports.set(id.name, id.start);
  4033. }
  4034. }
  4035. currentScope() {
  4036. return this.scopeStack[this.scopeStack.length - 1];
  4037. }
  4038. currentVarScope() {
  4039. for (let i = this.scopeStack.length - 1;; i--) {
  4040. const scope = this.scopeStack[i];
  4041. if (scope.flags & SCOPE_VAR) {
  4042. return scope;
  4043. }
  4044. }
  4045. }
  4046. currentThisScope() {
  4047. for (let i = this.scopeStack.length - 1;; i--) {
  4048. const scope = this.scopeStack[i];
  4049. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  4050. return scope;
  4051. }
  4052. }
  4053. }
  4054. }
  4055. class TypeScriptScope extends Scope {
  4056. constructor(...args) {
  4057. super(...args);
  4058. this.types = [];
  4059. this.enums = [];
  4060. this.constEnums = [];
  4061. this.classes = [];
  4062. this.exportOnlyBindings = [];
  4063. }
  4064. }
  4065. class TypeScriptScopeHandler extends ScopeHandler {
  4066. createScope(flags) {
  4067. return new TypeScriptScope(flags);
  4068. }
  4069. declareName(name, bindingType, pos) {
  4070. const scope = this.currentScope();
  4071. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4072. this.maybeExportDefined(scope, name);
  4073. scope.exportOnlyBindings.push(name);
  4074. return;
  4075. }
  4076. super.declareName(...arguments);
  4077. if (bindingType & BIND_KIND_TYPE) {
  4078. if (!(bindingType & BIND_KIND_VALUE)) {
  4079. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4080. this.maybeExportDefined(scope, name);
  4081. }
  4082. scope.types.push(name);
  4083. }
  4084. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4085. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4086. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4087. }
  4088. isRedeclaredInScope(scope, name, bindingType) {
  4089. if (scope.enums.indexOf(name) > -1) {
  4090. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4091. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4092. const wasConst = scope.constEnums.indexOf(name) > -1;
  4093. return isConst !== wasConst;
  4094. }
  4095. return true;
  4096. }
  4097. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4098. if (scope.lexical.indexOf(name) > -1) {
  4099. return !!(bindingType & BIND_KIND_VALUE);
  4100. } else {
  4101. return false;
  4102. }
  4103. }
  4104. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4105. return true;
  4106. }
  4107. return super.isRedeclaredInScope(...arguments);
  4108. }
  4109. checkLocalExport(id) {
  4110. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4111. super.checkLocalExport(id);
  4112. }
  4113. }
  4114. }
  4115. const PARAM = 0b000,
  4116. PARAM_YIELD = 0b001,
  4117. PARAM_AWAIT = 0b010,
  4118. PARAM_RETURN = 0b100;
  4119. class ProductionParameterHandler {
  4120. constructor() {
  4121. this.stacks = [];
  4122. }
  4123. enter(flags) {
  4124. this.stacks.push(flags);
  4125. }
  4126. exit() {
  4127. this.stacks.pop();
  4128. }
  4129. currentFlags() {
  4130. return this.stacks[this.stacks.length - 1];
  4131. }
  4132. get hasAwait() {
  4133. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4134. }
  4135. get hasYield() {
  4136. return (this.currentFlags() & PARAM_YIELD) > 0;
  4137. }
  4138. get hasReturn() {
  4139. return (this.currentFlags() & PARAM_RETURN) > 0;
  4140. }
  4141. }
  4142. function functionFlags(isAsync, isGenerator) {
  4143. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4144. }
  4145. function nonNull(x) {
  4146. if (x == null) {
  4147. throw new Error(`Unexpected ${x} value.`);
  4148. }
  4149. return x;
  4150. }
  4151. function assert(x) {
  4152. if (!x) {
  4153. throw new Error("Assert fail");
  4154. }
  4155. }
  4156. const TSErrors = Object.freeze({
  4157. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4158. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4159. DeclareClassFieldHasInitializer: "'declare' class fields cannot have an initializer",
  4160. DuplicateModifier: "Duplicate modifier: '%0'",
  4161. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4162. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4163. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4164. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4165. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4166. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4167. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4168. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4169. TemplateTypeHasSubstitution: "Template literal types cannot have any substitution",
  4170. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4171. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4172. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4173. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4174. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4175. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4176. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4177. });
  4178. function keywordTypeFromName(value) {
  4179. switch (value) {
  4180. case "any":
  4181. return "TSAnyKeyword";
  4182. case "boolean":
  4183. return "TSBooleanKeyword";
  4184. case "bigint":
  4185. return "TSBigIntKeyword";
  4186. case "never":
  4187. return "TSNeverKeyword";
  4188. case "number":
  4189. return "TSNumberKeyword";
  4190. case "object":
  4191. return "TSObjectKeyword";
  4192. case "string":
  4193. return "TSStringKeyword";
  4194. case "symbol":
  4195. return "TSSymbolKeyword";
  4196. case "undefined":
  4197. return "TSUndefinedKeyword";
  4198. case "unknown":
  4199. return "TSUnknownKeyword";
  4200. default:
  4201. return undefined;
  4202. }
  4203. }
  4204. var typescript = (superClass => class extends superClass {
  4205. getScopeHandler() {
  4206. return TypeScriptScopeHandler;
  4207. }
  4208. tsIsIdentifier() {
  4209. return this.match(types.name);
  4210. }
  4211. tsNextTokenCanFollowModifier() {
  4212. this.next();
  4213. return !this.hasPrecedingLineBreak() && !this.match(types.parenL) && !this.match(types.parenR) && !this.match(types.colon) && !this.match(types.eq) && !this.match(types.question) && !this.match(types.bang);
  4214. }
  4215. tsParseModifier(allowedModifiers) {
  4216. if (!this.match(types.name)) {
  4217. return undefined;
  4218. }
  4219. const modifier = this.state.value;
  4220. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4221. return modifier;
  4222. }
  4223. return undefined;
  4224. }
  4225. tsParseModifiers(modified, allowedModifiers) {
  4226. for (;;) {
  4227. const startPos = this.state.start;
  4228. const modifier = this.tsParseModifier(allowedModifiers);
  4229. if (!modifier) break;
  4230. if (Object.hasOwnProperty.call(modified, modifier)) {
  4231. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4232. }
  4233. modified[modifier] = true;
  4234. }
  4235. }
  4236. tsIsListTerminator(kind) {
  4237. switch (kind) {
  4238. case "EnumMembers":
  4239. case "TypeMembers":
  4240. return this.match(types.braceR);
  4241. case "HeritageClauseElement":
  4242. return this.match(types.braceL);
  4243. case "TupleElementTypes":
  4244. return this.match(types.bracketR);
  4245. case "TypeParametersOrArguments":
  4246. return this.isRelational(">");
  4247. }
  4248. throw new Error("Unreachable");
  4249. }
  4250. tsParseList(kind, parseElement) {
  4251. const result = [];
  4252. while (!this.tsIsListTerminator(kind)) {
  4253. result.push(parseElement());
  4254. }
  4255. return result;
  4256. }
  4257. tsParseDelimitedList(kind, parseElement) {
  4258. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4259. }
  4260. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4261. const result = [];
  4262. for (;;) {
  4263. if (this.tsIsListTerminator(kind)) {
  4264. break;
  4265. }
  4266. const element = parseElement();
  4267. if (element == null) {
  4268. return undefined;
  4269. }
  4270. result.push(element);
  4271. if (this.eat(types.comma)) {
  4272. continue;
  4273. }
  4274. if (this.tsIsListTerminator(kind)) {
  4275. break;
  4276. }
  4277. if (expectSuccess) {
  4278. this.expect(types.comma);
  4279. }
  4280. return undefined;
  4281. }
  4282. return result;
  4283. }
  4284. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4285. if (!skipFirstToken) {
  4286. if (bracket) {
  4287. this.expect(types.bracketL);
  4288. } else {
  4289. this.expectRelational("<");
  4290. }
  4291. }
  4292. const result = this.tsParseDelimitedList(kind, parseElement);
  4293. if (bracket) {
  4294. this.expect(types.bracketR);
  4295. } else {
  4296. this.expectRelational(">");
  4297. }
  4298. return result;
  4299. }
  4300. tsParseImportType() {
  4301. const node = this.startNode();
  4302. this.expect(types._import);
  4303. this.expect(types.parenL);
  4304. if (!this.match(types.string)) {
  4305. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4306. }
  4307. node.argument = this.parseExprAtom();
  4308. this.expect(types.parenR);
  4309. if (this.eat(types.dot)) {
  4310. node.qualifier = this.tsParseEntityName(true);
  4311. }
  4312. if (this.isRelational("<")) {
  4313. node.typeParameters = this.tsParseTypeArguments();
  4314. }
  4315. return this.finishNode(node, "TSImportType");
  4316. }
  4317. tsParseEntityName(allowReservedWords) {
  4318. let entity = this.parseIdentifier();
  4319. while (this.eat(types.dot)) {
  4320. const node = this.startNodeAtNode(entity);
  4321. node.left = entity;
  4322. node.right = this.parseIdentifier(allowReservedWords);
  4323. entity = this.finishNode(node, "TSQualifiedName");
  4324. }
  4325. return entity;
  4326. }
  4327. tsParseTypeReference() {
  4328. const node = this.startNode();
  4329. node.typeName = this.tsParseEntityName(false);
  4330. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4331. node.typeParameters = this.tsParseTypeArguments();
  4332. }
  4333. return this.finishNode(node, "TSTypeReference");
  4334. }
  4335. tsParseThisTypePredicate(lhs) {
  4336. this.next();
  4337. const node = this.startNodeAtNode(lhs);
  4338. node.parameterName = lhs;
  4339. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4340. return this.finishNode(node, "TSTypePredicate");
  4341. }
  4342. tsParseThisTypeNode() {
  4343. const node = this.startNode();
  4344. this.next();
  4345. return this.finishNode(node, "TSThisType");
  4346. }
  4347. tsParseTypeQuery() {
  4348. const node = this.startNode();
  4349. this.expect(types._typeof);
  4350. if (this.match(types._import)) {
  4351. node.exprName = this.tsParseImportType();
  4352. } else {
  4353. node.exprName = this.tsParseEntityName(true);
  4354. }
  4355. return this.finishNode(node, "TSTypeQuery");
  4356. }
  4357. tsParseTypeParameter() {
  4358. const node = this.startNode();
  4359. node.name = this.parseIdentifierName(node.start);
  4360. node.constraint = this.tsEatThenParseType(types._extends);
  4361. node.default = this.tsEatThenParseType(types.eq);
  4362. return this.finishNode(node, "TSTypeParameter");
  4363. }
  4364. tsTryParseTypeParameters() {
  4365. if (this.isRelational("<")) {
  4366. return this.tsParseTypeParameters();
  4367. }
  4368. }
  4369. tsParseTypeParameters() {
  4370. const node = this.startNode();
  4371. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4372. this.next();
  4373. } else {
  4374. this.unexpected();
  4375. }
  4376. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4377. return this.finishNode(node, "TSTypeParameterDeclaration");
  4378. }
  4379. tsTryNextParseConstantContext() {
  4380. if (this.lookahead().type === types._const) {
  4381. this.next();
  4382. return this.tsParseTypeReference();
  4383. }
  4384. return null;
  4385. }
  4386. tsFillSignature(returnToken, signature) {
  4387. const returnTokenRequired = returnToken === types.arrow;
  4388. signature.typeParameters = this.tsTryParseTypeParameters();
  4389. this.expect(types.parenL);
  4390. signature.parameters = this.tsParseBindingListForSignature();
  4391. if (returnTokenRequired) {
  4392. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4393. } else if (this.match(returnToken)) {
  4394. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4395. }
  4396. }
  4397. tsParseBindingListForSignature() {
  4398. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4399. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4400. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4401. }
  4402. return pattern;
  4403. });
  4404. }
  4405. tsParseTypeMemberSemicolon() {
  4406. if (!this.eat(types.comma)) {
  4407. this.semicolon();
  4408. }
  4409. }
  4410. tsParseSignatureMember(kind, node) {
  4411. this.tsFillSignature(types.colon, node);
  4412. this.tsParseTypeMemberSemicolon();
  4413. return this.finishNode(node, kind);
  4414. }
  4415. tsIsUnambiguouslyIndexSignature() {
  4416. this.next();
  4417. return this.eat(types.name) && this.match(types.colon);
  4418. }
  4419. tsTryParseIndexSignature(node) {
  4420. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4421. return undefined;
  4422. }
  4423. this.expect(types.bracketL);
  4424. const id = this.parseIdentifier();
  4425. id.typeAnnotation = this.tsParseTypeAnnotation();
  4426. this.resetEndLocation(id);
  4427. this.expect(types.bracketR);
  4428. node.parameters = [id];
  4429. const type = this.tsTryParseTypeAnnotation();
  4430. if (type) node.typeAnnotation = type;
  4431. this.tsParseTypeMemberSemicolon();
  4432. return this.finishNode(node, "TSIndexSignature");
  4433. }
  4434. tsParsePropertyOrMethodSignature(node, readonly) {
  4435. if (this.eat(types.question)) node.optional = true;
  4436. const nodeAny = node;
  4437. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  4438. const method = nodeAny;
  4439. this.tsFillSignature(types.colon, method);
  4440. this.tsParseTypeMemberSemicolon();
  4441. return this.finishNode(method, "TSMethodSignature");
  4442. } else {
  4443. const property = nodeAny;
  4444. if (readonly) property.readonly = true;
  4445. const type = this.tsTryParseTypeAnnotation();
  4446. if (type) property.typeAnnotation = type;
  4447. this.tsParseTypeMemberSemicolon();
  4448. return this.finishNode(property, "TSPropertySignature");
  4449. }
  4450. }
  4451. tsParseTypeMember() {
  4452. const node = this.startNode();
  4453. if (this.match(types.parenL) || this.isRelational("<")) {
  4454. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4455. }
  4456. if (this.match(types._new)) {
  4457. const id = this.startNode();
  4458. this.next();
  4459. if (this.match(types.parenL) || this.isRelational("<")) {
  4460. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4461. } else {
  4462. node.key = this.createIdentifier(id, "new");
  4463. return this.tsParsePropertyOrMethodSignature(node, false);
  4464. }
  4465. }
  4466. const readonly = !!this.tsParseModifier(["readonly"]);
  4467. const idx = this.tsTryParseIndexSignature(node);
  4468. if (idx) {
  4469. if (readonly) node.readonly = true;
  4470. return idx;
  4471. }
  4472. this.parsePropertyName(node, false);
  4473. return this.tsParsePropertyOrMethodSignature(node, readonly);
  4474. }
  4475. tsParseTypeLiteral() {
  4476. const node = this.startNode();
  4477. node.members = this.tsParseObjectTypeMembers();
  4478. return this.finishNode(node, "TSTypeLiteral");
  4479. }
  4480. tsParseObjectTypeMembers() {
  4481. this.expect(types.braceL);
  4482. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4483. this.expect(types.braceR);
  4484. return members;
  4485. }
  4486. tsIsStartOfMappedType() {
  4487. this.next();
  4488. if (this.eat(types.plusMin)) {
  4489. return this.isContextual("readonly");
  4490. }
  4491. if (this.isContextual("readonly")) {
  4492. this.next();
  4493. }
  4494. if (!this.match(types.bracketL)) {
  4495. return false;
  4496. }
  4497. this.next();
  4498. if (!this.tsIsIdentifier()) {
  4499. return false;
  4500. }
  4501. this.next();
  4502. return this.match(types._in);
  4503. }
  4504. tsParseMappedTypeParameter() {
  4505. const node = this.startNode();
  4506. node.name = this.parseIdentifierName(node.start);
  4507. node.constraint = this.tsExpectThenParseType(types._in);
  4508. return this.finishNode(node, "TSTypeParameter");
  4509. }
  4510. tsParseMappedType() {
  4511. const node = this.startNode();
  4512. this.expect(types.braceL);
  4513. if (this.match(types.plusMin)) {
  4514. node.readonly = this.state.value;
  4515. this.next();
  4516. this.expectContextual("readonly");
  4517. } else if (this.eatContextual("readonly")) {
  4518. node.readonly = true;
  4519. }
  4520. this.expect(types.bracketL);
  4521. node.typeParameter = this.tsParseMappedTypeParameter();
  4522. this.expect(types.bracketR);
  4523. if (this.match(types.plusMin)) {
  4524. node.optional = this.state.value;
  4525. this.next();
  4526. this.expect(types.question);
  4527. } else if (this.eat(types.question)) {
  4528. node.optional = true;
  4529. }
  4530. node.typeAnnotation = this.tsTryParseType();
  4531. this.semicolon();
  4532. this.expect(types.braceR);
  4533. return this.finishNode(node, "TSMappedType");
  4534. }
  4535. tsParseTupleType() {
  4536. const node = this.startNode();
  4537. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4538. let seenOptionalElement = false;
  4539. node.elementTypes.forEach(elementNode => {
  4540. if (elementNode.type === "TSOptionalType") {
  4541. seenOptionalElement = true;
  4542. } else if (seenOptionalElement && elementNode.type !== "TSRestType") {
  4543. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4544. }
  4545. });
  4546. return this.finishNode(node, "TSTupleType");
  4547. }
  4548. tsParseTupleElementType() {
  4549. if (this.match(types.ellipsis)) {
  4550. const restNode = this.startNode();
  4551. this.next();
  4552. restNode.typeAnnotation = this.tsParseType();
  4553. if (this.match(types.comma) && this.lookaheadCharCode() !== 93) {
  4554. this.raiseRestNotLast(this.state.start);
  4555. }
  4556. return this.finishNode(restNode, "TSRestType");
  4557. }
  4558. const type = this.tsParseType();
  4559. if (this.eat(types.question)) {
  4560. const optionalTypeNode = this.startNodeAtNode(type);
  4561. optionalTypeNode.typeAnnotation = type;
  4562. return this.finishNode(optionalTypeNode, "TSOptionalType");
  4563. }
  4564. return type;
  4565. }
  4566. tsParseParenthesizedType() {
  4567. const node = this.startNode();
  4568. this.expect(types.parenL);
  4569. node.typeAnnotation = this.tsParseType();
  4570. this.expect(types.parenR);
  4571. return this.finishNode(node, "TSParenthesizedType");
  4572. }
  4573. tsParseFunctionOrConstructorType(type) {
  4574. const node = this.startNode();
  4575. if (type === "TSConstructorType") {
  4576. this.expect(types._new);
  4577. }
  4578. this.tsFillSignature(types.arrow, node);
  4579. return this.finishNode(node, type);
  4580. }
  4581. tsParseLiteralTypeNode() {
  4582. const node = this.startNode();
  4583. node.literal = (() => {
  4584. switch (this.state.type) {
  4585. case types.num:
  4586. case types.string:
  4587. case types._true:
  4588. case types._false:
  4589. return this.parseExprAtom();
  4590. default:
  4591. throw this.unexpected();
  4592. }
  4593. })();
  4594. return this.finishNode(node, "TSLiteralType");
  4595. }
  4596. tsParseTemplateLiteralType() {
  4597. const node = this.startNode();
  4598. const templateNode = this.parseTemplate(false);
  4599. if (templateNode.expressions.length > 0) {
  4600. this.raise(templateNode.expressions[0].start, TSErrors.TemplateTypeHasSubstitution);
  4601. }
  4602. node.literal = templateNode;
  4603. return this.finishNode(node, "TSLiteralType");
  4604. }
  4605. tsParseThisTypeOrThisTypePredicate() {
  4606. const thisKeyword = this.tsParseThisTypeNode();
  4607. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4608. return this.tsParseThisTypePredicate(thisKeyword);
  4609. } else {
  4610. return thisKeyword;
  4611. }
  4612. }
  4613. tsParseNonArrayType() {
  4614. switch (this.state.type) {
  4615. case types.name:
  4616. case types._void:
  4617. case types._null:
  4618. {
  4619. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  4620. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  4621. const node = this.startNode();
  4622. this.next();
  4623. return this.finishNode(node, type);
  4624. }
  4625. return this.tsParseTypeReference();
  4626. }
  4627. case types.string:
  4628. case types.num:
  4629. case types._true:
  4630. case types._false:
  4631. return this.tsParseLiteralTypeNode();
  4632. case types.plusMin:
  4633. if (this.state.value === "-") {
  4634. const node = this.startNode();
  4635. if (this.lookahead().type !== types.num) {
  4636. throw this.unexpected();
  4637. }
  4638. node.literal = this.parseMaybeUnary();
  4639. return this.finishNode(node, "TSLiteralType");
  4640. }
  4641. break;
  4642. case types._this:
  4643. return this.tsParseThisTypeOrThisTypePredicate();
  4644. case types._typeof:
  4645. return this.tsParseTypeQuery();
  4646. case types._import:
  4647. return this.tsParseImportType();
  4648. case types.braceL:
  4649. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  4650. case types.bracketL:
  4651. return this.tsParseTupleType();
  4652. case types.parenL:
  4653. return this.tsParseParenthesizedType();
  4654. case types.backQuote:
  4655. return this.tsParseTemplateLiteralType();
  4656. }
  4657. throw this.unexpected();
  4658. }
  4659. tsParseArrayTypeOrHigher() {
  4660. let type = this.tsParseNonArrayType();
  4661. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  4662. if (this.match(types.bracketR)) {
  4663. const node = this.startNodeAtNode(type);
  4664. node.elementType = type;
  4665. this.expect(types.bracketR);
  4666. type = this.finishNode(node, "TSArrayType");
  4667. } else {
  4668. const node = this.startNodeAtNode(type);
  4669. node.objectType = type;
  4670. node.indexType = this.tsParseType();
  4671. this.expect(types.bracketR);
  4672. type = this.finishNode(node, "TSIndexedAccessType");
  4673. }
  4674. }
  4675. return type;
  4676. }
  4677. tsParseTypeOperator(operator) {
  4678. const node = this.startNode();
  4679. this.expectContextual(operator);
  4680. node.operator = operator;
  4681. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  4682. if (operator === "readonly") {
  4683. this.tsCheckTypeAnnotationForReadOnly(node);
  4684. }
  4685. return this.finishNode(node, "TSTypeOperator");
  4686. }
  4687. tsCheckTypeAnnotationForReadOnly(node) {
  4688. switch (node.typeAnnotation.type) {
  4689. case "TSTupleType":
  4690. case "TSArrayType":
  4691. return;
  4692. default:
  4693. this.raise(node.start, TSErrors.UnexpectedReadonly);
  4694. }
  4695. }
  4696. tsParseInferType() {
  4697. const node = this.startNode();
  4698. this.expectContextual("infer");
  4699. const typeParameter = this.startNode();
  4700. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  4701. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  4702. return this.finishNode(node, "TSInferType");
  4703. }
  4704. tsParseTypeOperatorOrHigher() {
  4705. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  4706. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  4707. }
  4708. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  4709. this.eat(operator);
  4710. let type = parseConstituentType();
  4711. if (this.match(operator)) {
  4712. const types = [type];
  4713. while (this.eat(operator)) {
  4714. types.push(parseConstituentType());
  4715. }
  4716. const node = this.startNodeAtNode(type);
  4717. node.types = types;
  4718. type = this.finishNode(node, kind);
  4719. }
  4720. return type;
  4721. }
  4722. tsParseIntersectionTypeOrHigher() {
  4723. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  4724. }
  4725. tsParseUnionTypeOrHigher() {
  4726. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  4727. }
  4728. tsIsStartOfFunctionType() {
  4729. if (this.isRelational("<")) {
  4730. return true;
  4731. }
  4732. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  4733. }
  4734. tsSkipParameterStart() {
  4735. if (this.match(types.name) || this.match(types._this)) {
  4736. this.next();
  4737. return true;
  4738. }
  4739. if (this.match(types.braceL)) {
  4740. let braceStackCounter = 1;
  4741. this.next();
  4742. while (braceStackCounter > 0) {
  4743. if (this.match(types.braceL)) {
  4744. ++braceStackCounter;
  4745. } else if (this.match(types.braceR)) {
  4746. --braceStackCounter;
  4747. }
  4748. this.next();
  4749. }
  4750. return true;
  4751. }
  4752. if (this.match(types.bracketL)) {
  4753. let braceStackCounter = 1;
  4754. this.next();
  4755. while (braceStackCounter > 0) {
  4756. if (this.match(types.bracketL)) {
  4757. ++braceStackCounter;
  4758. } else if (this.match(types.bracketR)) {
  4759. --braceStackCounter;
  4760. }
  4761. this.next();
  4762. }
  4763. return true;
  4764. }
  4765. return false;
  4766. }
  4767. tsIsUnambiguouslyStartOfFunctionType() {
  4768. this.next();
  4769. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  4770. return true;
  4771. }
  4772. if (this.tsSkipParameterStart()) {
  4773. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  4774. return true;
  4775. }
  4776. if (this.match(types.parenR)) {
  4777. this.next();
  4778. if (this.match(types.arrow)) {
  4779. return true;
  4780. }
  4781. }
  4782. }
  4783. return false;
  4784. }
  4785. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  4786. return this.tsInType(() => {
  4787. const t = this.startNode();
  4788. this.expect(returnToken);
  4789. const asserts = this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  4790. if (asserts && this.match(types._this)) {
  4791. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  4792. if (thisTypePredicate.type === "TSThisType") {
  4793. const node = this.startNodeAtNode(t);
  4794. node.parameterName = thisTypePredicate;
  4795. node.asserts = true;
  4796. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  4797. } else {
  4798. thisTypePredicate.asserts = true;
  4799. }
  4800. t.typeAnnotation = thisTypePredicate;
  4801. return this.finishNode(t, "TSTypeAnnotation");
  4802. }
  4803. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  4804. if (!typePredicateVariable) {
  4805. if (!asserts) {
  4806. return this.tsParseTypeAnnotation(false, t);
  4807. }
  4808. const node = this.startNodeAtNode(t);
  4809. node.parameterName = this.parseIdentifier();
  4810. node.asserts = asserts;
  4811. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4812. return this.finishNode(t, "TSTypeAnnotation");
  4813. }
  4814. const type = this.tsParseTypeAnnotation(false);
  4815. const node = this.startNodeAtNode(t);
  4816. node.parameterName = typePredicateVariable;
  4817. node.typeAnnotation = type;
  4818. node.asserts = asserts;
  4819. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  4820. return this.finishNode(t, "TSTypeAnnotation");
  4821. });
  4822. }
  4823. tsTryParseTypeOrTypePredicateAnnotation() {
  4824. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  4825. }
  4826. tsTryParseTypeAnnotation() {
  4827. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  4828. }
  4829. tsTryParseType() {
  4830. return this.tsEatThenParseType(types.colon);
  4831. }
  4832. tsParseTypePredicatePrefix() {
  4833. const id = this.parseIdentifier();
  4834. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4835. this.next();
  4836. return id;
  4837. }
  4838. }
  4839. tsParseTypePredicateAsserts() {
  4840. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  4841. return false;
  4842. }
  4843. const containsEsc = this.state.containsEsc;
  4844. this.next();
  4845. if (!this.match(types.name) && !this.match(types._this)) {
  4846. return false;
  4847. }
  4848. if (containsEsc) {
  4849. this.raise(this.state.lastTokStart, Errors.InvalidEscapedReservedWord, "asserts");
  4850. }
  4851. return true;
  4852. }
  4853. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  4854. this.tsInType(() => {
  4855. if (eatColon) this.expect(types.colon);
  4856. t.typeAnnotation = this.tsParseType();
  4857. });
  4858. return this.finishNode(t, "TSTypeAnnotation");
  4859. }
  4860. tsParseType() {
  4861. assert(this.state.inType);
  4862. const type = this.tsParseNonConditionalType();
  4863. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  4864. return type;
  4865. }
  4866. const node = this.startNodeAtNode(type);
  4867. node.checkType = type;
  4868. node.extendsType = this.tsParseNonConditionalType();
  4869. this.expect(types.question);
  4870. node.trueType = this.tsParseType();
  4871. this.expect(types.colon);
  4872. node.falseType = this.tsParseType();
  4873. return this.finishNode(node, "TSConditionalType");
  4874. }
  4875. tsParseNonConditionalType() {
  4876. if (this.tsIsStartOfFunctionType()) {
  4877. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  4878. }
  4879. if (this.match(types._new)) {
  4880. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  4881. }
  4882. return this.tsParseUnionTypeOrHigher();
  4883. }
  4884. tsParseTypeAssertion() {
  4885. const node = this.startNode();
  4886. const _const = this.tsTryNextParseConstantContext();
  4887. node.typeAnnotation = _const || this.tsNextThenParseType();
  4888. this.expectRelational(">");
  4889. node.expression = this.parseMaybeUnary();
  4890. return this.finishNode(node, "TSTypeAssertion");
  4891. }
  4892. tsParseHeritageClause(descriptor) {
  4893. const originalStart = this.state.start;
  4894. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  4895. if (!delimitedList.length) {
  4896. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  4897. }
  4898. return delimitedList;
  4899. }
  4900. tsParseExpressionWithTypeArguments() {
  4901. const node = this.startNode();
  4902. node.expression = this.tsParseEntityName(false);
  4903. if (this.isRelational("<")) {
  4904. node.typeParameters = this.tsParseTypeArguments();
  4905. }
  4906. return this.finishNode(node, "TSExpressionWithTypeArguments");
  4907. }
  4908. tsParseInterfaceDeclaration(node) {
  4909. node.id = this.parseIdentifier();
  4910. this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration");
  4911. node.typeParameters = this.tsTryParseTypeParameters();
  4912. if (this.eat(types._extends)) {
  4913. node.extends = this.tsParseHeritageClause("extends");
  4914. }
  4915. const body = this.startNode();
  4916. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  4917. node.body = this.finishNode(body, "TSInterfaceBody");
  4918. return this.finishNode(node, "TSInterfaceDeclaration");
  4919. }
  4920. tsParseTypeAliasDeclaration(node) {
  4921. node.id = this.parseIdentifier();
  4922. this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias");
  4923. node.typeParameters = this.tsTryParseTypeParameters();
  4924. node.typeAnnotation = this.tsExpectThenParseType(types.eq);
  4925. this.semicolon();
  4926. return this.finishNode(node, "TSTypeAliasDeclaration");
  4927. }
  4928. tsInNoContext(cb) {
  4929. const oldContext = this.state.context;
  4930. this.state.context = [oldContext[0]];
  4931. try {
  4932. return cb();
  4933. } finally {
  4934. this.state.context = oldContext;
  4935. }
  4936. }
  4937. tsInType(cb) {
  4938. const oldInType = this.state.inType;
  4939. this.state.inType = true;
  4940. try {
  4941. return cb();
  4942. } finally {
  4943. this.state.inType = oldInType;
  4944. }
  4945. }
  4946. tsEatThenParseType(token) {
  4947. return !this.match(token) ? undefined : this.tsNextThenParseType();
  4948. }
  4949. tsExpectThenParseType(token) {
  4950. return this.tsDoThenParseType(() => this.expect(token));
  4951. }
  4952. tsNextThenParseType() {
  4953. return this.tsDoThenParseType(() => this.next());
  4954. }
  4955. tsDoThenParseType(cb) {
  4956. return this.tsInType(() => {
  4957. cb();
  4958. return this.tsParseType();
  4959. });
  4960. }
  4961. tsParseEnumMember() {
  4962. const node = this.startNode();
  4963. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  4964. if (this.eat(types.eq)) {
  4965. node.initializer = this.parseMaybeAssign();
  4966. }
  4967. return this.finishNode(node, "TSEnumMember");
  4968. }
  4969. tsParseEnumDeclaration(node, isConst) {
  4970. if (isConst) node.const = true;
  4971. node.id = this.parseIdentifier();
  4972. this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration");
  4973. this.expect(types.braceL);
  4974. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  4975. this.expect(types.braceR);
  4976. return this.finishNode(node, "TSEnumDeclaration");
  4977. }
  4978. tsParseModuleBlock() {
  4979. const node = this.startNode();
  4980. this.scope.enter(SCOPE_OTHER);
  4981. this.expect(types.braceL);
  4982. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  4983. this.scope.exit();
  4984. return this.finishNode(node, "TSModuleBlock");
  4985. }
  4986. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  4987. node.id = this.parseIdentifier();
  4988. if (!nested) {
  4989. this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration");
  4990. }
  4991. if (this.eat(types.dot)) {
  4992. const inner = this.startNode();
  4993. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  4994. node.body = inner;
  4995. } else {
  4996. this.scope.enter(SCOPE_TS_MODULE);
  4997. this.prodParam.enter(PARAM);
  4998. node.body = this.tsParseModuleBlock();
  4999. this.prodParam.exit();
  5000. this.scope.exit();
  5001. }
  5002. return this.finishNode(node, "TSModuleDeclaration");
  5003. }
  5004. tsParseAmbientExternalModuleDeclaration(node) {
  5005. if (this.isContextual("global")) {
  5006. node.global = true;
  5007. node.id = this.parseIdentifier();
  5008. } else if (this.match(types.string)) {
  5009. node.id = this.parseExprAtom();
  5010. } else {
  5011. this.unexpected();
  5012. }
  5013. if (this.match(types.braceL)) {
  5014. this.scope.enter(SCOPE_TS_MODULE);
  5015. this.prodParam.enter(PARAM);
  5016. node.body = this.tsParseModuleBlock();
  5017. this.prodParam.exit();
  5018. this.scope.exit();
  5019. } else {
  5020. this.semicolon();
  5021. }
  5022. return this.finishNode(node, "TSModuleDeclaration");
  5023. }
  5024. tsParseImportEqualsDeclaration(node, isExport) {
  5025. node.isExport = isExport || false;
  5026. node.id = this.parseIdentifier();
  5027. this.checkLVal(node.id, BIND_LEXICAL, undefined, "import equals declaration");
  5028. this.expect(types.eq);
  5029. node.moduleReference = this.tsParseModuleReference();
  5030. this.semicolon();
  5031. return this.finishNode(node, "TSImportEqualsDeclaration");
  5032. }
  5033. tsIsExternalModuleReference() {
  5034. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5035. }
  5036. tsParseModuleReference() {
  5037. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5038. }
  5039. tsParseExternalModuleReference() {
  5040. const node = this.startNode();
  5041. this.expectContextual("require");
  5042. this.expect(types.parenL);
  5043. if (!this.match(types.string)) {
  5044. throw this.unexpected();
  5045. }
  5046. node.expression = this.parseExprAtom();
  5047. this.expect(types.parenR);
  5048. return this.finishNode(node, "TSExternalModuleReference");
  5049. }
  5050. tsLookAhead(f) {
  5051. const state = this.state.clone();
  5052. const res = f();
  5053. this.state = state;
  5054. return res;
  5055. }
  5056. tsTryParseAndCatch(f) {
  5057. const result = this.tryParse(abort => f() || abort());
  5058. if (result.aborted || !result.node) return undefined;
  5059. if (result.error) this.state = result.failState;
  5060. return result.node;
  5061. }
  5062. tsTryParse(f) {
  5063. const state = this.state.clone();
  5064. const result = f();
  5065. if (result !== undefined && result !== false) {
  5066. return result;
  5067. } else {
  5068. this.state = state;
  5069. return undefined;
  5070. }
  5071. }
  5072. tsTryParseDeclare(nany) {
  5073. if (this.isLineTerminator()) {
  5074. return;
  5075. }
  5076. let starttype = this.state.type;
  5077. let kind;
  5078. if (this.isContextual("let")) {
  5079. starttype = types._var;
  5080. kind = "let";
  5081. }
  5082. switch (starttype) {
  5083. case types._function:
  5084. return this.parseFunctionStatement(nany, false, true);
  5085. case types._class:
  5086. nany.declare = true;
  5087. return this.parseClass(nany, true, false);
  5088. case types._const:
  5089. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5090. this.expect(types._const);
  5091. this.expectContextual("enum");
  5092. return this.tsParseEnumDeclaration(nany, true);
  5093. }
  5094. case types._var:
  5095. kind = kind || this.state.value;
  5096. return this.parseVarStatement(nany, kind);
  5097. case types.name:
  5098. {
  5099. const value = this.state.value;
  5100. if (value === "global") {
  5101. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5102. } else {
  5103. return this.tsParseDeclaration(nany, value, true);
  5104. }
  5105. }
  5106. }
  5107. }
  5108. tsTryParseExportDeclaration() {
  5109. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5110. }
  5111. tsParseExpressionStatement(node, expr) {
  5112. switch (expr.name) {
  5113. case "declare":
  5114. {
  5115. const declaration = this.tsTryParseDeclare(node);
  5116. if (declaration) {
  5117. declaration.declare = true;
  5118. return declaration;
  5119. }
  5120. break;
  5121. }
  5122. case "global":
  5123. if (this.match(types.braceL)) {
  5124. this.scope.enter(SCOPE_TS_MODULE);
  5125. this.prodParam.enter(PARAM);
  5126. const mod = node;
  5127. mod.global = true;
  5128. mod.id = expr;
  5129. mod.body = this.tsParseModuleBlock();
  5130. this.scope.exit();
  5131. this.prodParam.exit();
  5132. return this.finishNode(mod, "TSModuleDeclaration");
  5133. }
  5134. break;
  5135. default:
  5136. return this.tsParseDeclaration(node, expr.name, false);
  5137. }
  5138. }
  5139. tsParseDeclaration(node, value, next) {
  5140. switch (value) {
  5141. case "abstract":
  5142. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  5143. const cls = node;
  5144. cls.abstract = true;
  5145. if (next) {
  5146. this.next();
  5147. if (!this.match(types._class)) {
  5148. this.unexpected(null, types._class);
  5149. }
  5150. }
  5151. return this.parseClass(cls, true, false);
  5152. }
  5153. break;
  5154. case "enum":
  5155. if (next || this.match(types.name)) {
  5156. if (next) this.next();
  5157. return this.tsParseEnumDeclaration(node, false);
  5158. }
  5159. break;
  5160. case "interface":
  5161. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5162. if (next) this.next();
  5163. return this.tsParseInterfaceDeclaration(node);
  5164. }
  5165. break;
  5166. case "module":
  5167. if (next) this.next();
  5168. if (this.match(types.string)) {
  5169. return this.tsParseAmbientExternalModuleDeclaration(node);
  5170. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5171. return this.tsParseModuleOrNamespaceDeclaration(node);
  5172. }
  5173. break;
  5174. case "namespace":
  5175. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5176. if (next) this.next();
  5177. return this.tsParseModuleOrNamespaceDeclaration(node);
  5178. }
  5179. break;
  5180. case "type":
  5181. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  5182. if (next) this.next();
  5183. return this.tsParseTypeAliasDeclaration(node);
  5184. }
  5185. break;
  5186. }
  5187. }
  5188. tsCheckLineTerminatorAndMatch(tokenType, next) {
  5189. return (next || this.match(tokenType)) && !this.isLineTerminator();
  5190. }
  5191. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5192. if (!this.isRelational("<")) {
  5193. return undefined;
  5194. }
  5195. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5196. const oldYieldPos = this.state.yieldPos;
  5197. const oldAwaitPos = this.state.awaitPos;
  5198. this.state.maybeInArrowParameters = true;
  5199. this.state.yieldPos = -1;
  5200. this.state.awaitPos = -1;
  5201. const res = this.tsTryParseAndCatch(() => {
  5202. const node = this.startNodeAt(startPos, startLoc);
  5203. node.typeParameters = this.tsParseTypeParameters();
  5204. super.parseFunctionParams(node);
  5205. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5206. this.expect(types.arrow);
  5207. return node;
  5208. });
  5209. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5210. this.state.yieldPos = oldYieldPos;
  5211. this.state.awaitPos = oldAwaitPos;
  5212. if (!res) {
  5213. return undefined;
  5214. }
  5215. return this.parseArrowExpression(res, null, true);
  5216. }
  5217. tsParseTypeArguments() {
  5218. const node = this.startNode();
  5219. node.params = this.tsInType(() => this.tsInNoContext(() => {
  5220. this.expectRelational("<");
  5221. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  5222. }));
  5223. this.state.exprAllowed = false;
  5224. this.expectRelational(">");
  5225. return this.finishNode(node, "TSTypeParameterInstantiation");
  5226. }
  5227. tsIsDeclarationStart() {
  5228. if (this.match(types.name)) {
  5229. switch (this.state.value) {
  5230. case "abstract":
  5231. case "declare":
  5232. case "enum":
  5233. case "interface":
  5234. case "module":
  5235. case "namespace":
  5236. case "type":
  5237. return true;
  5238. }
  5239. }
  5240. return false;
  5241. }
  5242. isExportDefaultSpecifier() {
  5243. if (this.tsIsDeclarationStart()) return false;
  5244. return super.isExportDefaultSpecifier();
  5245. }
  5246. parseAssignableListItem(allowModifiers, decorators) {
  5247. const startPos = this.state.start;
  5248. const startLoc = this.state.startLoc;
  5249. let accessibility;
  5250. let readonly = false;
  5251. if (allowModifiers) {
  5252. accessibility = this.parseAccessModifier();
  5253. readonly = !!this.tsParseModifier(["readonly"]);
  5254. }
  5255. const left = this.parseMaybeDefault();
  5256. this.parseAssignableListItemTypes(left);
  5257. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  5258. if (accessibility || readonly) {
  5259. const pp = this.startNodeAt(startPos, startLoc);
  5260. if (decorators.length) {
  5261. pp.decorators = decorators;
  5262. }
  5263. if (accessibility) pp.accessibility = accessibility;
  5264. if (readonly) pp.readonly = readonly;
  5265. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  5266. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  5267. }
  5268. pp.parameter = elt;
  5269. return this.finishNode(pp, "TSParameterProperty");
  5270. }
  5271. if (decorators.length) {
  5272. left.decorators = decorators;
  5273. }
  5274. return elt;
  5275. }
  5276. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5277. if (this.match(types.colon)) {
  5278. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5279. }
  5280. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  5281. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  5282. this.finishNode(node, bodilessType);
  5283. return;
  5284. }
  5285. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5286. }
  5287. registerFunctionStatementId(node) {
  5288. if (!node.body && node.id) {
  5289. this.checkLVal(node.id, BIND_TS_AMBIENT, null, "function name");
  5290. } else {
  5291. super.registerFunctionStatementId(...arguments);
  5292. }
  5293. }
  5294. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5295. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5296. this.state.exprAllowed = false;
  5297. this.next();
  5298. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5299. nonNullExpression.expression = base;
  5300. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5301. }
  5302. if (this.isRelational("<")) {
  5303. const result = this.tsTryParseAndCatch(() => {
  5304. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5305. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5306. if (asyncArrowFn) {
  5307. return asyncArrowFn;
  5308. }
  5309. }
  5310. const node = this.startNodeAt(startPos, startLoc);
  5311. node.callee = base;
  5312. const typeArguments = this.tsParseTypeArguments();
  5313. if (typeArguments) {
  5314. if (!noCalls && this.eat(types.parenL)) {
  5315. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5316. node.typeParameters = typeArguments;
  5317. return this.finishCallExpression(node, state.optionalChainMember);
  5318. } else if (this.match(types.backQuote)) {
  5319. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments);
  5320. }
  5321. }
  5322. this.unexpected();
  5323. });
  5324. if (result) return result;
  5325. }
  5326. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5327. }
  5328. parseNewArguments(node) {
  5329. if (this.isRelational("<")) {
  5330. const typeParameters = this.tsTryParseAndCatch(() => {
  5331. const args = this.tsParseTypeArguments();
  5332. if (!this.match(types.parenL)) this.unexpected();
  5333. return args;
  5334. });
  5335. if (typeParameters) {
  5336. node.typeParameters = typeParameters;
  5337. }
  5338. }
  5339. super.parseNewArguments(node);
  5340. }
  5341. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  5342. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5343. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5344. node.expression = left;
  5345. const _const = this.tsTryNextParseConstantContext();
  5346. if (_const) {
  5347. node.typeAnnotation = _const;
  5348. } else {
  5349. node.typeAnnotation = this.tsNextThenParseType();
  5350. }
  5351. this.finishNode(node, "TSAsExpression");
  5352. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  5353. }
  5354. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn);
  5355. }
  5356. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5357. checkDuplicateExports() {}
  5358. parseImport(node) {
  5359. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5360. const ahead = this.lookahead();
  5361. if (this.match(types.name) && ahead.type === types.eq) {
  5362. return this.tsParseImportEqualsDeclaration(node);
  5363. }
  5364. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  5365. node.importKind = "type";
  5366. this.next();
  5367. } else {
  5368. node.importKind = "value";
  5369. }
  5370. }
  5371. const importNode = super.parseImport(node);
  5372. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5373. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5374. }
  5375. return importNode;
  5376. }
  5377. parseExport(node) {
  5378. if (this.match(types._import)) {
  5379. this.expect(types._import);
  5380. return this.tsParseImportEqualsDeclaration(node, true);
  5381. } else if (this.eat(types.eq)) {
  5382. const assign = node;
  5383. assign.expression = this.parseExpression();
  5384. this.semicolon();
  5385. return this.finishNode(assign, "TSExportAssignment");
  5386. } else if (this.eatContextual("as")) {
  5387. const decl = node;
  5388. this.expectContextual("namespace");
  5389. decl.id = this.parseIdentifier();
  5390. this.semicolon();
  5391. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5392. } else {
  5393. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5394. this.next();
  5395. node.exportKind = "type";
  5396. } else {
  5397. node.exportKind = "value";
  5398. }
  5399. return super.parseExport(node);
  5400. }
  5401. }
  5402. isAbstractClass() {
  5403. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5404. }
  5405. parseExportDefaultExpression() {
  5406. if (this.isAbstractClass()) {
  5407. const cls = this.startNode();
  5408. this.next();
  5409. this.parseClass(cls, true, true);
  5410. cls.abstract = true;
  5411. return cls;
  5412. }
  5413. if (this.state.value === "interface") {
  5414. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5415. if (result) return result;
  5416. }
  5417. return super.parseExportDefaultExpression();
  5418. }
  5419. parseStatementContent(context, topLevel) {
  5420. if (this.state.type === types._const) {
  5421. const ahead = this.lookahead();
  5422. if (ahead.type === types.name && ahead.value === "enum") {
  5423. const node = this.startNode();
  5424. this.expect(types._const);
  5425. this.expectContextual("enum");
  5426. return this.tsParseEnumDeclaration(node, true);
  5427. }
  5428. }
  5429. return super.parseStatementContent(context, topLevel);
  5430. }
  5431. parseAccessModifier() {
  5432. return this.tsParseModifier(["public", "protected", "private"]);
  5433. }
  5434. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  5435. this.tsParseModifiers(member, ["declare"]);
  5436. const accessibility = this.parseAccessModifier();
  5437. if (accessibility) member.accessibility = accessibility;
  5438. this.tsParseModifiers(member, ["declare"]);
  5439. super.parseClassMember(classBody, member, state, constructorAllowsSuper);
  5440. }
  5441. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  5442. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5443. const idx = this.tsTryParseIndexSignature(member);
  5444. if (idx) {
  5445. classBody.body.push(idx);
  5446. if (member.abstract) {
  5447. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5448. }
  5449. if (isStatic) {
  5450. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5451. }
  5452. if (member.accessibility) {
  5453. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5454. }
  5455. return;
  5456. }
  5457. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  5458. }
  5459. parsePostMemberNameModifiers(methodOrProp) {
  5460. const optional = this.eat(types.question);
  5461. if (optional) methodOrProp.optional = true;
  5462. if (methodOrProp.readonly && this.match(types.parenL)) {
  5463. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5464. }
  5465. if (methodOrProp.declare && this.match(types.parenL)) {
  5466. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5467. }
  5468. }
  5469. parseExpressionStatement(node, expr) {
  5470. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5471. return decl || super.parseExpressionStatement(node, expr);
  5472. }
  5473. shouldParseExportDeclaration() {
  5474. if (this.tsIsDeclarationStart()) return true;
  5475. return super.shouldParseExportDeclaration();
  5476. }
  5477. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  5478. if (!refNeedsArrowPos || !this.match(types.question)) {
  5479. return super.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  5480. }
  5481. const result = this.tryParse(() => super.parseConditional(expr, noIn, startPos, startLoc));
  5482. if (!result.node) {
  5483. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5484. return expr;
  5485. }
  5486. if (result.error) this.state = result.failState;
  5487. return result.node;
  5488. }
  5489. parseParenItem(node, startPos, startLoc) {
  5490. node = super.parseParenItem(node, startPos, startLoc);
  5491. if (this.eat(types.question)) {
  5492. node.optional = true;
  5493. this.resetEndLocation(node);
  5494. }
  5495. if (this.match(types.colon)) {
  5496. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5497. typeCastNode.expression = node;
  5498. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5499. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5500. }
  5501. return node;
  5502. }
  5503. parseExportDeclaration(node) {
  5504. const startPos = this.state.start;
  5505. const startLoc = this.state.startLoc;
  5506. const isDeclare = this.eatContextual("declare");
  5507. let declaration;
  5508. if (this.match(types.name)) {
  5509. declaration = this.tsTryParseExportDeclaration();
  5510. }
  5511. if (!declaration) {
  5512. declaration = super.parseExportDeclaration(node);
  5513. }
  5514. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5515. node.exportKind = "type";
  5516. }
  5517. if (declaration && isDeclare) {
  5518. this.resetStartLocation(declaration, startPos, startLoc);
  5519. declaration.declare = true;
  5520. }
  5521. return declaration;
  5522. }
  5523. parseClassId(node, isStatement, optionalId) {
  5524. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5525. return;
  5526. }
  5527. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5528. const typeParameters = this.tsTryParseTypeParameters();
  5529. if (typeParameters) node.typeParameters = typeParameters;
  5530. }
  5531. parseClassPropertyAnnotation(node) {
  5532. if (!node.optional && this.eat(types.bang)) {
  5533. node.definite = true;
  5534. }
  5535. const type = this.tsTryParseTypeAnnotation();
  5536. if (type) node.typeAnnotation = type;
  5537. }
  5538. parseClassProperty(node) {
  5539. this.parseClassPropertyAnnotation(node);
  5540. if (node.declare && this.match(types.equal)) {
  5541. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5542. }
  5543. return super.parseClassProperty(node);
  5544. }
  5545. parseClassPrivateProperty(node) {
  5546. if (node.abstract) {
  5547. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  5548. }
  5549. if (node.accessibility) {
  5550. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  5551. }
  5552. this.parseClassPropertyAnnotation(node);
  5553. return super.parseClassPrivateProperty(node);
  5554. }
  5555. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5556. const typeParameters = this.tsTryParseTypeParameters();
  5557. if (typeParameters) method.typeParameters = typeParameters;
  5558. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5559. }
  5560. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5561. const typeParameters = this.tsTryParseTypeParameters();
  5562. if (typeParameters) method.typeParameters = typeParameters;
  5563. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5564. }
  5565. parseClassSuper(node) {
  5566. super.parseClassSuper(node);
  5567. if (node.superClass && this.isRelational("<")) {
  5568. node.superTypeParameters = this.tsParseTypeArguments();
  5569. }
  5570. if (this.eatContextual("implements")) {
  5571. node.implements = this.tsParseHeritageClause("implements");
  5572. }
  5573. }
  5574. parseObjPropValue(prop, ...args) {
  5575. const typeParameters = this.tsTryParseTypeParameters();
  5576. if (typeParameters) prop.typeParameters = typeParameters;
  5577. super.parseObjPropValue(prop, ...args);
  5578. }
  5579. parseFunctionParams(node, allowModifiers) {
  5580. const typeParameters = this.tsTryParseTypeParameters();
  5581. if (typeParameters) node.typeParameters = typeParameters;
  5582. super.parseFunctionParams(node, allowModifiers);
  5583. }
  5584. parseVarId(decl, kind) {
  5585. super.parseVarId(decl, kind);
  5586. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  5587. decl.definite = true;
  5588. }
  5589. const type = this.tsTryParseTypeAnnotation();
  5590. if (type) {
  5591. decl.id.typeAnnotation = type;
  5592. this.resetEndLocation(decl.id);
  5593. }
  5594. }
  5595. parseAsyncArrowFromCallExpression(node, call) {
  5596. if (this.match(types.colon)) {
  5597. node.returnType = this.tsParseTypeAnnotation();
  5598. }
  5599. return super.parseAsyncArrowFromCallExpression(node, call);
  5600. }
  5601. parseMaybeAssign(...args) {
  5602. let state;
  5603. let jsx;
  5604. let typeCast;
  5605. if (this.match(types.jsxTagStart)) {
  5606. state = this.state.clone();
  5607. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5608. if (!jsx.error) return jsx.node;
  5609. const {
  5610. context
  5611. } = this.state;
  5612. if (context[context.length - 1] === types$1.j_oTag) {
  5613. context.length -= 2;
  5614. } else if (context[context.length - 1] === types$1.j_expr) {
  5615. context.length -= 1;
  5616. }
  5617. }
  5618. if (!(jsx && jsx.error) && !this.isRelational("<")) {
  5619. return super.parseMaybeAssign(...args);
  5620. }
  5621. let typeParameters;
  5622. state = state || this.state.clone();
  5623. const arrow = this.tryParse(abort => {
  5624. typeParameters = this.tsParseTypeParameters();
  5625. const expr = super.parseMaybeAssign(...args);
  5626. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  5627. abort();
  5628. }
  5629. if (typeParameters && typeParameters.params.length !== 0) {
  5630. this.resetStartLocationFromNode(expr, typeParameters);
  5631. }
  5632. expr.typeParameters = typeParameters;
  5633. return expr;
  5634. }, state);
  5635. if (!arrow.error && !arrow.aborted) return arrow.node;
  5636. if (!jsx) {
  5637. assert(!this.hasPlugin("jsx"));
  5638. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  5639. if (!typeCast.error) return typeCast.node;
  5640. }
  5641. if (jsx && jsx.node) {
  5642. this.state = jsx.failState;
  5643. return jsx.node;
  5644. }
  5645. if (arrow.node) {
  5646. this.state = arrow.failState;
  5647. return arrow.node;
  5648. }
  5649. if (typeCast && typeCast.node) {
  5650. this.state = typeCast.failState;
  5651. return typeCast.node;
  5652. }
  5653. if (jsx && jsx.thrown) throw jsx.error;
  5654. if (arrow.thrown) throw arrow.error;
  5655. if (typeCast && typeCast.thrown) throw typeCast.error;
  5656. throw jsx && jsx.error || arrow.error || typeCast && typeCast.error;
  5657. }
  5658. parseMaybeUnary(refExpressionErrors) {
  5659. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  5660. return this.tsParseTypeAssertion();
  5661. } else {
  5662. return super.parseMaybeUnary(refExpressionErrors);
  5663. }
  5664. }
  5665. parseArrow(node) {
  5666. if (this.match(types.colon)) {
  5667. const result = this.tryParse(abort => {
  5668. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5669. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  5670. return returnType;
  5671. });
  5672. if (result.aborted) return;
  5673. if (!result.thrown) {
  5674. if (result.error) this.state = result.failState;
  5675. node.returnType = result.node;
  5676. }
  5677. }
  5678. return super.parseArrow(node);
  5679. }
  5680. parseAssignableListItemTypes(param) {
  5681. if (this.eat(types.question)) {
  5682. if (param.type !== "Identifier") {
  5683. this.raise(param.start, TSErrors.PatternIsOptional);
  5684. }
  5685. param.optional = true;
  5686. }
  5687. const type = this.tsTryParseTypeAnnotation();
  5688. if (type) param.typeAnnotation = type;
  5689. this.resetEndLocation(param);
  5690. return param;
  5691. }
  5692. toAssignable(node) {
  5693. switch (node.type) {
  5694. case "TSTypeCastExpression":
  5695. return super.toAssignable(this.typeCastToParameter(node));
  5696. case "TSParameterProperty":
  5697. return super.toAssignable(node);
  5698. case "TSAsExpression":
  5699. case "TSNonNullExpression":
  5700. case "TSTypeAssertion":
  5701. node.expression = this.toAssignable(node.expression);
  5702. return node;
  5703. default:
  5704. return super.toAssignable(node);
  5705. }
  5706. }
  5707. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) {
  5708. switch (expr.type) {
  5709. case "TSTypeCastExpression":
  5710. return;
  5711. case "TSParameterProperty":
  5712. this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property");
  5713. return;
  5714. case "TSAsExpression":
  5715. case "TSNonNullExpression":
  5716. case "TSTypeAssertion":
  5717. this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription);
  5718. return;
  5719. default:
  5720. super.checkLVal(expr, bindingType, checkClashes, contextDescription);
  5721. return;
  5722. }
  5723. }
  5724. parseBindingAtom() {
  5725. switch (this.state.type) {
  5726. case types._this:
  5727. return this.parseIdentifier(true);
  5728. default:
  5729. return super.parseBindingAtom();
  5730. }
  5731. }
  5732. parseMaybeDecoratorArguments(expr) {
  5733. if (this.isRelational("<")) {
  5734. const typeArguments = this.tsParseTypeArguments();
  5735. if (this.match(types.parenL)) {
  5736. const call = super.parseMaybeDecoratorArguments(expr);
  5737. call.typeParameters = typeArguments;
  5738. return call;
  5739. }
  5740. this.unexpected(this.state.start, types.parenL);
  5741. }
  5742. return super.parseMaybeDecoratorArguments(expr);
  5743. }
  5744. isClassMethod() {
  5745. return this.isRelational("<") || super.isClassMethod();
  5746. }
  5747. isClassProperty() {
  5748. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  5749. }
  5750. parseMaybeDefault(...args) {
  5751. const node = super.parseMaybeDefault(...args);
  5752. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5753. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  5754. }
  5755. return node;
  5756. }
  5757. getTokenFromCode(code) {
  5758. if (this.state.inType && (code === 62 || code === 60)) {
  5759. return this.finishOp(types.relational, 1);
  5760. } else {
  5761. return super.getTokenFromCode(code);
  5762. }
  5763. }
  5764. toAssignableList(exprList) {
  5765. for (let i = 0; i < exprList.length; i++) {
  5766. const expr = exprList[i];
  5767. if (!expr) continue;
  5768. switch (expr.type) {
  5769. case "TSTypeCastExpression":
  5770. exprList[i] = this.typeCastToParameter(expr);
  5771. break;
  5772. case "TSAsExpression":
  5773. case "TSTypeAssertion":
  5774. if (!this.state.maybeInArrowParameters) {
  5775. exprList[i] = this.typeCastToParameter(expr);
  5776. } else {
  5777. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  5778. }
  5779. break;
  5780. }
  5781. }
  5782. return super.toAssignableList(...arguments);
  5783. }
  5784. typeCastToParameter(node) {
  5785. node.expression.typeAnnotation = node.typeAnnotation;
  5786. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5787. return node.expression;
  5788. }
  5789. toReferencedList(exprList, isInParens) {
  5790. for (let i = 0; i < exprList.length; i++) {
  5791. const expr = exprList[i];
  5792. if (expr && expr.type === "TSTypeCastExpression") {
  5793. this.raise(expr.start, TSErrors.UnexpectedTypeAnnotation);
  5794. }
  5795. }
  5796. return exprList;
  5797. }
  5798. shouldParseArrow() {
  5799. return this.match(types.colon) || super.shouldParseArrow();
  5800. }
  5801. shouldParseAsyncArrow() {
  5802. return this.match(types.colon) || super.shouldParseAsyncArrow();
  5803. }
  5804. canHaveLeadingDecorator() {
  5805. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  5806. }
  5807. jsxParseOpeningElementAfterName(node) {
  5808. if (this.isRelational("<")) {
  5809. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  5810. if (typeArguments) node.typeParameters = typeArguments;
  5811. }
  5812. return super.jsxParseOpeningElementAfterName(node);
  5813. }
  5814. getGetterSetterExpectedParamCount(method) {
  5815. const baseCount = super.getGetterSetterExpectedParamCount(method);
  5816. const firstParam = method.params[0];
  5817. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  5818. return hasContextParam ? baseCount + 1 : baseCount;
  5819. }
  5820. });
  5821. types.placeholder = new TokenType("%%", {
  5822. startsExpr: true
  5823. });
  5824. var placeholders = (superClass => class extends superClass {
  5825. parsePlaceholder(expectedNode) {
  5826. if (this.match(types.placeholder)) {
  5827. const node = this.startNode();
  5828. this.next();
  5829. this.assertNoSpace("Unexpected space in placeholder.");
  5830. node.name = super.parseIdentifier(true);
  5831. this.assertNoSpace("Unexpected space in placeholder.");
  5832. this.expect(types.placeholder);
  5833. return this.finishPlaceholder(node, expectedNode);
  5834. }
  5835. }
  5836. finishPlaceholder(node, expectedNode) {
  5837. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  5838. node.expectedNode = expectedNode;
  5839. return isFinished ? node : this.finishNode(node, "Placeholder");
  5840. }
  5841. getTokenFromCode(code) {
  5842. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  5843. return this.finishOp(types.placeholder, 2);
  5844. }
  5845. return super.getTokenFromCode(...arguments);
  5846. }
  5847. parseExprAtom() {
  5848. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  5849. }
  5850. parseIdentifier() {
  5851. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  5852. }
  5853. checkReservedWord(word) {
  5854. if (word !== undefined) super.checkReservedWord(...arguments);
  5855. }
  5856. parseBindingAtom() {
  5857. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  5858. }
  5859. checkLVal(expr) {
  5860. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  5861. }
  5862. toAssignable(node) {
  5863. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  5864. node.expectedNode = "Pattern";
  5865. return node;
  5866. }
  5867. return super.toAssignable(...arguments);
  5868. }
  5869. verifyBreakContinue(node) {
  5870. if (node.label && node.label.type === "Placeholder") return;
  5871. super.verifyBreakContinue(...arguments);
  5872. }
  5873. parseExpressionStatement(node, expr) {
  5874. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  5875. return super.parseExpressionStatement(...arguments);
  5876. }
  5877. if (this.match(types.colon)) {
  5878. const stmt = node;
  5879. stmt.label = this.finishPlaceholder(expr, "Identifier");
  5880. this.next();
  5881. stmt.body = this.parseStatement("label");
  5882. return this.finishNode(stmt, "LabeledStatement");
  5883. }
  5884. this.semicolon();
  5885. node.name = expr.name;
  5886. return this.finishPlaceholder(node, "Statement");
  5887. }
  5888. parseBlock() {
  5889. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  5890. }
  5891. parseFunctionId() {
  5892. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  5893. }
  5894. parseClass(node, isStatement, optionalId) {
  5895. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  5896. this.next();
  5897. this.takeDecorators(node);
  5898. const placeholder = this.parsePlaceholder("Identifier");
  5899. if (placeholder) {
  5900. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  5901. node.id = placeholder;
  5902. } else if (optionalId || !isStatement) {
  5903. node.id = null;
  5904. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  5905. return this.finishNode(node, type);
  5906. } else {
  5907. this.unexpected(null, "A class name is required");
  5908. }
  5909. } else {
  5910. this.parseClassId(node, isStatement, optionalId);
  5911. }
  5912. this.parseClassSuper(node);
  5913. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass);
  5914. return this.finishNode(node, type);
  5915. }
  5916. parseExport(node) {
  5917. const placeholder = this.parsePlaceholder("Identifier");
  5918. if (!placeholder) return super.parseExport(...arguments);
  5919. if (!this.isContextual("from") && !this.match(types.comma)) {
  5920. node.specifiers = [];
  5921. node.source = null;
  5922. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  5923. return this.finishNode(node, "ExportNamedDeclaration");
  5924. }
  5925. this.expectPlugin("exportDefaultFrom");
  5926. const specifier = this.startNode();
  5927. specifier.exported = placeholder;
  5928. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  5929. return super.parseExport(node);
  5930. }
  5931. maybeParseExportDefaultSpecifier(node) {
  5932. if (node.specifiers && node.specifiers.length > 0) {
  5933. return true;
  5934. }
  5935. return super.maybeParseExportDefaultSpecifier(...arguments);
  5936. }
  5937. checkExport(node) {
  5938. const {
  5939. specifiers
  5940. } = node;
  5941. if (specifiers && specifiers.length) {
  5942. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  5943. }
  5944. super.checkExport(node);
  5945. node.specifiers = specifiers;
  5946. }
  5947. parseImport(node) {
  5948. const placeholder = this.parsePlaceholder("Identifier");
  5949. if (!placeholder) return super.parseImport(...arguments);
  5950. node.specifiers = [];
  5951. if (!this.isContextual("from") && !this.match(types.comma)) {
  5952. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  5953. this.semicolon();
  5954. return this.finishNode(node, "ImportDeclaration");
  5955. }
  5956. const specifier = this.startNodeAtNode(placeholder);
  5957. specifier.local = placeholder;
  5958. this.finishNode(specifier, "ImportDefaultSpecifier");
  5959. node.specifiers.push(specifier);
  5960. if (this.eat(types.comma)) {
  5961. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  5962. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  5963. }
  5964. this.expectContextual("from");
  5965. node.source = this.parseImportSource();
  5966. this.semicolon();
  5967. return this.finishNode(node, "ImportDeclaration");
  5968. }
  5969. parseImportSource() {
  5970. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  5971. }
  5972. });
  5973. var v8intrinsic = (superClass => class extends superClass {
  5974. parseV8Intrinsic() {
  5975. if (this.match(types.modulo)) {
  5976. const v8IntrinsicStart = this.state.start;
  5977. const node = this.startNode();
  5978. this.eat(types.modulo);
  5979. if (this.match(types.name)) {
  5980. const name = this.parseIdentifierName(this.state.start);
  5981. const identifier = this.createIdentifier(node, name);
  5982. identifier.type = "V8IntrinsicIdentifier";
  5983. if (this.match(types.parenL)) {
  5984. return identifier;
  5985. }
  5986. }
  5987. this.unexpected(v8IntrinsicStart);
  5988. }
  5989. }
  5990. parseExprAtom() {
  5991. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  5992. }
  5993. });
  5994. function hasPlugin(plugins, name) {
  5995. return plugins.some(plugin => {
  5996. if (Array.isArray(plugin)) {
  5997. return plugin[0] === name;
  5998. } else {
  5999. return plugin === name;
  6000. }
  6001. });
  6002. }
  6003. function getPluginOption(plugins, name, option) {
  6004. const plugin = plugins.find(plugin => {
  6005. if (Array.isArray(plugin)) {
  6006. return plugin[0] === name;
  6007. } else {
  6008. return plugin === name;
  6009. }
  6010. });
  6011. if (plugin && Array.isArray(plugin)) {
  6012. return plugin[1][option];
  6013. }
  6014. return null;
  6015. }
  6016. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6017. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6018. function validatePlugins(plugins) {
  6019. if (hasPlugin(plugins, "decorators")) {
  6020. if (hasPlugin(plugins, "decorators-legacy")) {
  6021. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6022. }
  6023. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6024. if (decoratorsBeforeExport == null) {
  6025. throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'.");
  6026. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6027. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6028. }
  6029. }
  6030. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6031. throw new Error("Cannot combine flow and typescript plugins.");
  6032. }
  6033. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6034. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6035. }
  6036. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6037. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6038. }
  6039. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6040. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6041. }
  6042. }
  6043. const mixinPlugins = {
  6044. estree,
  6045. jsx,
  6046. flow,
  6047. typescript,
  6048. v8intrinsic,
  6049. placeholders
  6050. };
  6051. const mixinPluginNames = Object.keys(mixinPlugins);
  6052. const defaultOptions = {
  6053. sourceType: "script",
  6054. sourceFilename: undefined,
  6055. startLine: 1,
  6056. allowAwaitOutsideFunction: false,
  6057. allowReturnOutsideFunction: false,
  6058. allowImportExportEverywhere: false,
  6059. allowSuperOutsideMethod: false,
  6060. allowUndeclaredExports: false,
  6061. plugins: [],
  6062. strictMode: null,
  6063. ranges: false,
  6064. tokens: false,
  6065. createParenthesizedExpressions: false,
  6066. errorRecovery: false
  6067. };
  6068. function getOptions(opts) {
  6069. const options = {};
  6070. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  6071. const key = _Object$keys[_i];
  6072. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6073. }
  6074. return options;
  6075. }
  6076. class State {
  6077. constructor() {
  6078. this.errors = [];
  6079. this.potentialArrowAt = -1;
  6080. this.noArrowAt = [];
  6081. this.noArrowParamsConversionAt = [];
  6082. this.inParameters = false;
  6083. this.maybeInArrowParameters = false;
  6084. this.maybeInAsyncArrowHead = false;
  6085. this.inPipeline = false;
  6086. this.inType = false;
  6087. this.noAnonFunctionType = false;
  6088. this.inPropertyName = false;
  6089. this.hasFlowComment = false;
  6090. this.isIterator = false;
  6091. this.topicContext = {
  6092. maxNumOfResolvableTopics: 0,
  6093. maxTopicIndex: null
  6094. };
  6095. this.soloAwait = false;
  6096. this.inFSharpPipelineDirectBody = false;
  6097. this.labels = [];
  6098. this.decoratorStack = [[]];
  6099. this.yieldPos = -1;
  6100. this.awaitPos = -1;
  6101. this.comments = [];
  6102. this.trailingComments = [];
  6103. this.leadingComments = [];
  6104. this.commentStack = [];
  6105. this.commentPreviousNode = null;
  6106. this.pos = 0;
  6107. this.lineStart = 0;
  6108. this.type = types.eof;
  6109. this.value = null;
  6110. this.start = 0;
  6111. this.end = 0;
  6112. this.lastTokEndLoc = null;
  6113. this.lastTokStartLoc = null;
  6114. this.lastTokStart = 0;
  6115. this.lastTokEnd = 0;
  6116. this.context = [types$1.braceStatement];
  6117. this.exprAllowed = true;
  6118. this.containsEsc = false;
  6119. this.octalPositions = [];
  6120. this.exportedIdentifiers = [];
  6121. this.tokensLength = 0;
  6122. }
  6123. init(options) {
  6124. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6125. this.curLine = options.startLine;
  6126. this.startLoc = this.endLoc = this.curPosition();
  6127. }
  6128. curPosition() {
  6129. return new Position(this.curLine, this.pos - this.lineStart);
  6130. }
  6131. clone(skipArrays) {
  6132. const state = new State();
  6133. const keys = Object.keys(this);
  6134. for (let i = 0, length = keys.length; i < length; i++) {
  6135. const key = keys[i];
  6136. let val = this[key];
  6137. if (!skipArrays && Array.isArray(val)) {
  6138. val = val.slice();
  6139. }
  6140. state[key] = val;
  6141. }
  6142. return state;
  6143. }
  6144. }
  6145. var _isDigit = function isDigit(code) {
  6146. return code >= 48 && code <= 57;
  6147. };
  6148. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6149. const forbiddenNumericSeparatorSiblings = {
  6150. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6151. hex: [46, 88, 95, 120]
  6152. };
  6153. const allowedNumericSeparatorSiblings = {};
  6154. allowedNumericSeparatorSiblings.bin = [48, 49];
  6155. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6156. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6157. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6158. class Token {
  6159. constructor(state) {
  6160. this.type = state.type;
  6161. this.value = state.value;
  6162. this.start = state.start;
  6163. this.end = state.end;
  6164. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  6165. }
  6166. }
  6167. class Tokenizer extends LocationParser {
  6168. constructor(options, input) {
  6169. super();
  6170. this.tokens = [];
  6171. this.state = new State();
  6172. this.state.init(options);
  6173. this.input = input;
  6174. this.length = input.length;
  6175. this.isLookahead = false;
  6176. }
  6177. pushToken(token) {
  6178. this.tokens.length = this.state.tokensLength;
  6179. this.tokens.push(token);
  6180. ++this.state.tokensLength;
  6181. }
  6182. next() {
  6183. if (!this.isLookahead) {
  6184. this.checkKeywordEscapes();
  6185. if (this.options.tokens) {
  6186. this.pushToken(new Token(this.state));
  6187. }
  6188. }
  6189. this.state.lastTokEnd = this.state.end;
  6190. this.state.lastTokStart = this.state.start;
  6191. this.state.lastTokEndLoc = this.state.endLoc;
  6192. this.state.lastTokStartLoc = this.state.startLoc;
  6193. this.nextToken();
  6194. }
  6195. eat(type) {
  6196. if (this.match(type)) {
  6197. this.next();
  6198. return true;
  6199. } else {
  6200. return false;
  6201. }
  6202. }
  6203. match(type) {
  6204. return this.state.type === type;
  6205. }
  6206. lookahead() {
  6207. const old = this.state;
  6208. this.state = old.clone(true);
  6209. this.isLookahead = true;
  6210. this.next();
  6211. this.isLookahead = false;
  6212. const curr = this.state;
  6213. this.state = old;
  6214. return curr;
  6215. }
  6216. nextTokenStart() {
  6217. const thisTokEnd = this.state.pos;
  6218. skipWhiteSpace.lastIndex = thisTokEnd;
  6219. const skip = skipWhiteSpace.exec(this.input);
  6220. return thisTokEnd + skip[0].length;
  6221. }
  6222. lookaheadCharCode() {
  6223. return this.input.charCodeAt(this.nextTokenStart());
  6224. }
  6225. setStrict(strict) {
  6226. this.state.strict = strict;
  6227. if (!this.match(types.num) && !this.match(types.string)) return;
  6228. this.state.pos = this.state.start;
  6229. while (this.state.pos < this.state.lineStart) {
  6230. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  6231. --this.state.curLine;
  6232. }
  6233. this.nextToken();
  6234. }
  6235. curContext() {
  6236. return this.state.context[this.state.context.length - 1];
  6237. }
  6238. nextToken() {
  6239. const curContext = this.curContext();
  6240. if (!curContext || !curContext.preserveSpace) this.skipSpace();
  6241. this.state.octalPositions = [];
  6242. this.state.start = this.state.pos;
  6243. this.state.startLoc = this.state.curPosition();
  6244. if (this.state.pos >= this.length) {
  6245. this.finishToken(types.eof);
  6246. return;
  6247. }
  6248. const override = curContext == null ? void 0 : curContext.override;
  6249. if (override) {
  6250. override(this);
  6251. } else {
  6252. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6253. }
  6254. }
  6255. pushComment(block, text, start, end, startLoc, endLoc) {
  6256. const comment = {
  6257. type: block ? "CommentBlock" : "CommentLine",
  6258. value: text,
  6259. start: start,
  6260. end: end,
  6261. loc: new SourceLocation(startLoc, endLoc)
  6262. };
  6263. if (this.options.tokens) this.pushToken(comment);
  6264. this.state.comments.push(comment);
  6265. this.addComment(comment);
  6266. }
  6267. skipBlockComment() {
  6268. const startLoc = this.state.curPosition();
  6269. const start = this.state.pos;
  6270. const end = this.input.indexOf("*/", this.state.pos + 2);
  6271. if (end === -1) throw this.raise(start, Errors.UnterminatedComment);
  6272. this.state.pos = end + 2;
  6273. lineBreakG.lastIndex = start;
  6274. let match;
  6275. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6276. ++this.state.curLine;
  6277. this.state.lineStart = match.index + match[0].length;
  6278. }
  6279. if (this.isLookahead) return;
  6280. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6281. }
  6282. skipLineComment(startSkip) {
  6283. const start = this.state.pos;
  6284. const startLoc = this.state.curPosition();
  6285. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6286. if (this.state.pos < this.length) {
  6287. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6288. ch = this.input.charCodeAt(this.state.pos);
  6289. }
  6290. }
  6291. if (this.isLookahead) return;
  6292. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6293. }
  6294. skipSpace() {
  6295. loop: while (this.state.pos < this.length) {
  6296. const ch = this.input.charCodeAt(this.state.pos);
  6297. switch (ch) {
  6298. case 32:
  6299. case 160:
  6300. case 9:
  6301. ++this.state.pos;
  6302. break;
  6303. case 13:
  6304. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6305. ++this.state.pos;
  6306. }
  6307. case 10:
  6308. case 8232:
  6309. case 8233:
  6310. ++this.state.pos;
  6311. ++this.state.curLine;
  6312. this.state.lineStart = this.state.pos;
  6313. break;
  6314. case 47:
  6315. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6316. case 42:
  6317. this.skipBlockComment();
  6318. break;
  6319. case 47:
  6320. this.skipLineComment(2);
  6321. break;
  6322. default:
  6323. break loop;
  6324. }
  6325. break;
  6326. default:
  6327. if (isWhitespace(ch)) {
  6328. ++this.state.pos;
  6329. } else {
  6330. break loop;
  6331. }
  6332. }
  6333. }
  6334. }
  6335. finishToken(type, val) {
  6336. this.state.end = this.state.pos;
  6337. this.state.endLoc = this.state.curPosition();
  6338. const prevType = this.state.type;
  6339. this.state.type = type;
  6340. this.state.value = val;
  6341. if (!this.isLookahead) this.updateContext(prevType);
  6342. }
  6343. readToken_numberSign() {
  6344. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6345. return;
  6346. }
  6347. const nextPos = this.state.pos + 1;
  6348. const next = this.input.charCodeAt(nextPos);
  6349. if (next >= 48 && next <= 57) {
  6350. throw this.raise(this.state.pos, Errors.UnexpectedDigitAfterHash);
  6351. }
  6352. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  6353. this.expectPlugin("recordAndTuple");
  6354. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6355. throw this.raise(this.state.pos, next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType);
  6356. }
  6357. if (next === 123) {
  6358. this.finishToken(types.braceHashL);
  6359. } else {
  6360. this.finishToken(types.bracketHashL);
  6361. }
  6362. this.state.pos += 2;
  6363. } else {
  6364. this.finishOp(types.hash, 1);
  6365. }
  6366. }
  6367. readToken_dot() {
  6368. const next = this.input.charCodeAt(this.state.pos + 1);
  6369. if (next >= 48 && next <= 57) {
  6370. this.readNumber(true);
  6371. return;
  6372. }
  6373. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6374. this.state.pos += 3;
  6375. this.finishToken(types.ellipsis);
  6376. } else {
  6377. ++this.state.pos;
  6378. this.finishToken(types.dot);
  6379. }
  6380. }
  6381. readToken_slash() {
  6382. if (this.state.exprAllowed && !this.state.inType) {
  6383. ++this.state.pos;
  6384. this.readRegexp();
  6385. return;
  6386. }
  6387. const next = this.input.charCodeAt(this.state.pos + 1);
  6388. if (next === 61) {
  6389. this.finishOp(types.assign, 2);
  6390. } else {
  6391. this.finishOp(types.slash, 1);
  6392. }
  6393. }
  6394. readToken_interpreter() {
  6395. if (this.state.pos !== 0 || this.length < 2) return false;
  6396. let ch = this.input.charCodeAt(this.state.pos + 1);
  6397. if (ch !== 33) return false;
  6398. const start = this.state.pos;
  6399. this.state.pos += 1;
  6400. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6401. ch = this.input.charCodeAt(this.state.pos);
  6402. }
  6403. const value = this.input.slice(start + 2, this.state.pos);
  6404. this.finishToken(types.interpreterDirective, value);
  6405. return true;
  6406. }
  6407. readToken_mult_modulo(code) {
  6408. let type = code === 42 ? types.star : types.modulo;
  6409. let width = 1;
  6410. let next = this.input.charCodeAt(this.state.pos + 1);
  6411. const exprAllowed = this.state.exprAllowed;
  6412. if (code === 42 && next === 42) {
  6413. width++;
  6414. next = this.input.charCodeAt(this.state.pos + 2);
  6415. type = types.exponent;
  6416. }
  6417. if (next === 61 && !exprAllowed) {
  6418. width++;
  6419. type = types.assign;
  6420. }
  6421. this.finishOp(type, width);
  6422. }
  6423. readToken_pipe_amp(code) {
  6424. const next = this.input.charCodeAt(this.state.pos + 1);
  6425. if (next === code) {
  6426. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  6427. this.finishOp(types.assign, 3);
  6428. } else {
  6429. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  6430. }
  6431. return;
  6432. }
  6433. if (code === 124) {
  6434. if (next === 62) {
  6435. this.finishOp(types.pipeline, 2);
  6436. return;
  6437. }
  6438. if (this.hasPlugin("recordAndTuple") && next === 125) {
  6439. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6440. throw this.raise(this.state.pos, Errors.RecordExpressionBarIncorrectEndSyntaxType);
  6441. }
  6442. this.finishOp(types.braceBarR, 2);
  6443. return;
  6444. }
  6445. if (this.hasPlugin("recordAndTuple") && next === 93) {
  6446. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6447. throw this.raise(this.state.pos, Errors.TupleExpressionBarIncorrectEndSyntaxType);
  6448. }
  6449. this.finishOp(types.bracketBarR, 2);
  6450. return;
  6451. }
  6452. }
  6453. if (next === 61) {
  6454. this.finishOp(types.assign, 2);
  6455. return;
  6456. }
  6457. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  6458. }
  6459. readToken_caret() {
  6460. const next = this.input.charCodeAt(this.state.pos + 1);
  6461. if (next === 61) {
  6462. this.finishOp(types.assign, 2);
  6463. } else {
  6464. this.finishOp(types.bitwiseXOR, 1);
  6465. }
  6466. }
  6467. readToken_plus_min(code) {
  6468. const next = this.input.charCodeAt(this.state.pos + 1);
  6469. if (next === code) {
  6470. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos)))) {
  6471. this.skipLineComment(3);
  6472. this.skipSpace();
  6473. this.nextToken();
  6474. return;
  6475. }
  6476. this.finishOp(types.incDec, 2);
  6477. return;
  6478. }
  6479. if (next === 61) {
  6480. this.finishOp(types.assign, 2);
  6481. } else {
  6482. this.finishOp(types.plusMin, 1);
  6483. }
  6484. }
  6485. readToken_lt_gt(code) {
  6486. const next = this.input.charCodeAt(this.state.pos + 1);
  6487. let size = 1;
  6488. if (next === code) {
  6489. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  6490. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  6491. this.finishOp(types.assign, size + 1);
  6492. return;
  6493. }
  6494. this.finishOp(types.bitShift, size);
  6495. return;
  6496. }
  6497. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  6498. this.skipLineComment(4);
  6499. this.skipSpace();
  6500. this.nextToken();
  6501. return;
  6502. }
  6503. if (next === 61) {
  6504. size = 2;
  6505. }
  6506. this.finishOp(types.relational, size);
  6507. }
  6508. readToken_eq_excl(code) {
  6509. const next = this.input.charCodeAt(this.state.pos + 1);
  6510. if (next === 61) {
  6511. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  6512. return;
  6513. }
  6514. if (code === 61 && next === 62) {
  6515. this.state.pos += 2;
  6516. this.finishToken(types.arrow);
  6517. return;
  6518. }
  6519. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  6520. }
  6521. readToken_question() {
  6522. const next = this.input.charCodeAt(this.state.pos + 1);
  6523. const next2 = this.input.charCodeAt(this.state.pos + 2);
  6524. if (next === 63 && !this.state.inType) {
  6525. if (next2 === 61) {
  6526. this.finishOp(types.assign, 3);
  6527. } else {
  6528. this.finishOp(types.nullishCoalescing, 2);
  6529. }
  6530. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  6531. this.state.pos += 2;
  6532. this.finishToken(types.questionDot);
  6533. } else {
  6534. ++this.state.pos;
  6535. this.finishToken(types.question);
  6536. }
  6537. }
  6538. getTokenFromCode(code) {
  6539. switch (code) {
  6540. case 46:
  6541. this.readToken_dot();
  6542. return;
  6543. case 40:
  6544. ++this.state.pos;
  6545. this.finishToken(types.parenL);
  6546. return;
  6547. case 41:
  6548. ++this.state.pos;
  6549. this.finishToken(types.parenR);
  6550. return;
  6551. case 59:
  6552. ++this.state.pos;
  6553. this.finishToken(types.semi);
  6554. return;
  6555. case 44:
  6556. ++this.state.pos;
  6557. this.finishToken(types.comma);
  6558. return;
  6559. case 91:
  6560. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6561. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6562. throw this.raise(this.state.pos, Errors.TupleExpressionBarIncorrectStartSyntaxType);
  6563. }
  6564. this.finishToken(types.bracketBarL);
  6565. this.state.pos += 2;
  6566. } else {
  6567. ++this.state.pos;
  6568. this.finishToken(types.bracketL);
  6569. }
  6570. return;
  6571. case 93:
  6572. ++this.state.pos;
  6573. this.finishToken(types.bracketR);
  6574. return;
  6575. case 123:
  6576. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  6577. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  6578. throw this.raise(this.state.pos, Errors.RecordExpressionBarIncorrectStartSyntaxType);
  6579. }
  6580. this.finishToken(types.braceBarL);
  6581. this.state.pos += 2;
  6582. } else {
  6583. ++this.state.pos;
  6584. this.finishToken(types.braceL);
  6585. }
  6586. return;
  6587. case 125:
  6588. ++this.state.pos;
  6589. this.finishToken(types.braceR);
  6590. return;
  6591. case 58:
  6592. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  6593. this.finishOp(types.doubleColon, 2);
  6594. } else {
  6595. ++this.state.pos;
  6596. this.finishToken(types.colon);
  6597. }
  6598. return;
  6599. case 63:
  6600. this.readToken_question();
  6601. return;
  6602. case 96:
  6603. ++this.state.pos;
  6604. this.finishToken(types.backQuote);
  6605. return;
  6606. case 48:
  6607. {
  6608. const next = this.input.charCodeAt(this.state.pos + 1);
  6609. if (next === 120 || next === 88) {
  6610. this.readRadixNumber(16);
  6611. return;
  6612. }
  6613. if (next === 111 || next === 79) {
  6614. this.readRadixNumber(8);
  6615. return;
  6616. }
  6617. if (next === 98 || next === 66) {
  6618. this.readRadixNumber(2);
  6619. return;
  6620. }
  6621. }
  6622. case 49:
  6623. case 50:
  6624. case 51:
  6625. case 52:
  6626. case 53:
  6627. case 54:
  6628. case 55:
  6629. case 56:
  6630. case 57:
  6631. this.readNumber(false);
  6632. return;
  6633. case 34:
  6634. case 39:
  6635. this.readString(code);
  6636. return;
  6637. case 47:
  6638. this.readToken_slash();
  6639. return;
  6640. case 37:
  6641. case 42:
  6642. this.readToken_mult_modulo(code);
  6643. return;
  6644. case 124:
  6645. case 38:
  6646. this.readToken_pipe_amp(code);
  6647. return;
  6648. case 94:
  6649. this.readToken_caret();
  6650. return;
  6651. case 43:
  6652. case 45:
  6653. this.readToken_plus_min(code);
  6654. return;
  6655. case 60:
  6656. case 62:
  6657. this.readToken_lt_gt(code);
  6658. return;
  6659. case 61:
  6660. case 33:
  6661. this.readToken_eq_excl(code);
  6662. return;
  6663. case 126:
  6664. this.finishOp(types.tilde, 1);
  6665. return;
  6666. case 64:
  6667. ++this.state.pos;
  6668. this.finishToken(types.at);
  6669. return;
  6670. case 35:
  6671. this.readToken_numberSign();
  6672. return;
  6673. case 92:
  6674. this.readWord();
  6675. return;
  6676. default:
  6677. if (isIdentifierStart(code)) {
  6678. this.readWord();
  6679. return;
  6680. }
  6681. }
  6682. throw this.raise(this.state.pos, Errors.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  6683. }
  6684. finishOp(type, size) {
  6685. const str = this.input.slice(this.state.pos, this.state.pos + size);
  6686. this.state.pos += size;
  6687. this.finishToken(type, str);
  6688. }
  6689. readRegexp() {
  6690. const start = this.state.pos;
  6691. let escaped, inClass;
  6692. for (;;) {
  6693. if (this.state.pos >= this.length) {
  6694. throw this.raise(start, Errors.UnterminatedRegExp);
  6695. }
  6696. const ch = this.input.charAt(this.state.pos);
  6697. if (lineBreak.test(ch)) {
  6698. throw this.raise(start, Errors.UnterminatedRegExp);
  6699. }
  6700. if (escaped) {
  6701. escaped = false;
  6702. } else {
  6703. if (ch === "[") {
  6704. inClass = true;
  6705. } else if (ch === "]" && inClass) {
  6706. inClass = false;
  6707. } else if (ch === "/" && !inClass) {
  6708. break;
  6709. }
  6710. escaped = ch === "\\";
  6711. }
  6712. ++this.state.pos;
  6713. }
  6714. const content = this.input.slice(start, this.state.pos);
  6715. ++this.state.pos;
  6716. let mods = "";
  6717. while (this.state.pos < this.length) {
  6718. const char = this.input[this.state.pos];
  6719. const charCode = this.input.codePointAt(this.state.pos);
  6720. if (VALID_REGEX_FLAGS.has(char)) {
  6721. if (mods.indexOf(char) > -1) {
  6722. this.raise(this.state.pos + 1, Errors.DuplicateRegExpFlags);
  6723. }
  6724. } else if (isIdentifierChar(charCode) || charCode === 92) {
  6725. this.raise(this.state.pos + 1, Errors.MalformedRegExpFlags);
  6726. } else {
  6727. break;
  6728. }
  6729. ++this.state.pos;
  6730. mods += char;
  6731. }
  6732. this.finishToken(types.regexp, {
  6733. pattern: content,
  6734. flags: mods
  6735. });
  6736. }
  6737. readInt(radix, len, forceLen, allowNumSeparator = true) {
  6738. const start = this.state.pos;
  6739. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  6740. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  6741. let invalid = false;
  6742. let total = 0;
  6743. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  6744. const code = this.input.charCodeAt(this.state.pos);
  6745. let val;
  6746. if (this.hasPlugin("numericSeparator")) {
  6747. if (code === 95) {
  6748. const prev = this.input.charCodeAt(this.state.pos - 1);
  6749. const next = this.input.charCodeAt(this.state.pos + 1);
  6750. if (allowedSiblings.indexOf(next) === -1) {
  6751. this.raise(this.state.pos, Errors.UnexpectedNumericSeparator);
  6752. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  6753. this.raise(this.state.pos, Errors.UnexpectedNumericSeparator);
  6754. }
  6755. if (!allowNumSeparator) {
  6756. this.raise(this.state.pos, Errors.NumericSeparatorInEscapeSequence);
  6757. }
  6758. ++this.state.pos;
  6759. continue;
  6760. }
  6761. }
  6762. if (code >= 97) {
  6763. val = code - 97 + 10;
  6764. } else if (code >= 65) {
  6765. val = code - 65 + 10;
  6766. } else if (_isDigit(code)) {
  6767. val = code - 48;
  6768. } else {
  6769. val = Infinity;
  6770. }
  6771. if (val >= radix) {
  6772. if (this.options.errorRecovery && val <= 9) {
  6773. val = 0;
  6774. this.raise(this.state.start + i + 2, Errors.InvalidDigit, radix);
  6775. } else if (forceLen) {
  6776. val = 0;
  6777. invalid = true;
  6778. } else {
  6779. break;
  6780. }
  6781. }
  6782. ++this.state.pos;
  6783. total = total * radix + val;
  6784. }
  6785. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  6786. return null;
  6787. }
  6788. return total;
  6789. }
  6790. readRadixNumber(radix) {
  6791. const start = this.state.pos;
  6792. let isBigInt = false;
  6793. this.state.pos += 2;
  6794. const val = this.readInt(radix);
  6795. if (val == null) {
  6796. this.raise(this.state.start + 2, Errors.InvalidDigit, radix);
  6797. }
  6798. const next = this.input.charCodeAt(this.state.pos);
  6799. if (next === 95) {
  6800. this.expectPlugin("numericSeparator", this.state.pos);
  6801. }
  6802. if (next === 110) {
  6803. ++this.state.pos;
  6804. isBigInt = true;
  6805. }
  6806. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6807. throw this.raise(this.state.pos, Errors.NumberIdentifier);
  6808. }
  6809. if (isBigInt) {
  6810. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6811. this.finishToken(types.bigint, str);
  6812. return;
  6813. }
  6814. this.finishToken(types.num, val);
  6815. }
  6816. readNumber(startsWithDot) {
  6817. const start = this.state.pos;
  6818. let isFloat = false;
  6819. let isBigInt = false;
  6820. let isNonOctalDecimalInt = false;
  6821. if (!startsWithDot && this.readInt(10) === null) {
  6822. this.raise(start, Errors.InvalidNumber);
  6823. }
  6824. let octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  6825. if (octal) {
  6826. if (this.state.strict) {
  6827. this.raise(start, Errors.StrictOctalLiteral);
  6828. }
  6829. if (/[89]/.test(this.input.slice(start, this.state.pos))) {
  6830. octal = false;
  6831. isNonOctalDecimalInt = true;
  6832. }
  6833. }
  6834. let next = this.input.charCodeAt(this.state.pos);
  6835. if (next === 46 && !octal) {
  6836. ++this.state.pos;
  6837. this.readInt(10);
  6838. isFloat = true;
  6839. next = this.input.charCodeAt(this.state.pos);
  6840. }
  6841. if ((next === 69 || next === 101) && !octal) {
  6842. next = this.input.charCodeAt(++this.state.pos);
  6843. if (next === 43 || next === 45) {
  6844. ++this.state.pos;
  6845. }
  6846. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  6847. isFloat = true;
  6848. next = this.input.charCodeAt(this.state.pos);
  6849. }
  6850. if (this.hasPlugin("numericSeparator") && (octal || isNonOctalDecimalInt)) {
  6851. const underscorePos = this.input.slice(start, this.state.pos).indexOf("_");
  6852. if (underscorePos > 0) {
  6853. this.raise(underscorePos + start, Errors.ZeroDigitNumericSeparator);
  6854. }
  6855. }
  6856. if (next === 95) {
  6857. this.expectPlugin("numericSeparator", this.state.pos);
  6858. }
  6859. if (next === 110) {
  6860. if (isFloat || octal || isNonOctalDecimalInt) {
  6861. this.raise(start, "Invalid BigIntLiteral");
  6862. }
  6863. ++this.state.pos;
  6864. isBigInt = true;
  6865. }
  6866. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  6867. throw this.raise(this.state.pos, Errors.NumberIdentifier);
  6868. }
  6869. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  6870. if (isBigInt) {
  6871. this.finishToken(types.bigint, str);
  6872. return;
  6873. }
  6874. const val = octal ? parseInt(str, 8) : parseFloat(str);
  6875. this.finishToken(types.num, val);
  6876. }
  6877. readCodePoint(throwOnInvalid) {
  6878. const ch = this.input.charCodeAt(this.state.pos);
  6879. let code;
  6880. if (ch === 123) {
  6881. const codePos = ++this.state.pos;
  6882. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  6883. ++this.state.pos;
  6884. if (code !== null && code > 0x10ffff) {
  6885. if (throwOnInvalid) {
  6886. this.raise(codePos, Errors.InvalidCodePoint);
  6887. } else {
  6888. return null;
  6889. }
  6890. }
  6891. } else {
  6892. code = this.readHexChar(4, false, throwOnInvalid);
  6893. }
  6894. return code;
  6895. }
  6896. readString(quote) {
  6897. let out = "",
  6898. chunkStart = ++this.state.pos;
  6899. for (;;) {
  6900. if (this.state.pos >= this.length) {
  6901. throw this.raise(this.state.start, Errors.UnterminatedString);
  6902. }
  6903. const ch = this.input.charCodeAt(this.state.pos);
  6904. if (ch === quote) break;
  6905. if (ch === 92) {
  6906. out += this.input.slice(chunkStart, this.state.pos);
  6907. out += this.readEscapedChar(false);
  6908. chunkStart = this.state.pos;
  6909. } else if (ch === 8232 || ch === 8233) {
  6910. ++this.state.pos;
  6911. ++this.state.curLine;
  6912. this.state.lineStart = this.state.pos;
  6913. } else if (isNewLine(ch)) {
  6914. throw this.raise(this.state.start, Errors.UnterminatedString);
  6915. } else {
  6916. ++this.state.pos;
  6917. }
  6918. }
  6919. out += this.input.slice(chunkStart, this.state.pos++);
  6920. this.finishToken(types.string, out);
  6921. }
  6922. readTmplToken() {
  6923. let out = "",
  6924. chunkStart = this.state.pos,
  6925. containsInvalid = false;
  6926. for (;;) {
  6927. if (this.state.pos >= this.length) {
  6928. throw this.raise(this.state.start, Errors.UnterminatedTemplate);
  6929. }
  6930. const ch = this.input.charCodeAt(this.state.pos);
  6931. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  6932. if (this.state.pos === this.state.start && this.match(types.template)) {
  6933. if (ch === 36) {
  6934. this.state.pos += 2;
  6935. this.finishToken(types.dollarBraceL);
  6936. return;
  6937. } else {
  6938. ++this.state.pos;
  6939. this.finishToken(types.backQuote);
  6940. return;
  6941. }
  6942. }
  6943. out += this.input.slice(chunkStart, this.state.pos);
  6944. this.finishToken(types.template, containsInvalid ? null : out);
  6945. return;
  6946. }
  6947. if (ch === 92) {
  6948. out += this.input.slice(chunkStart, this.state.pos);
  6949. const escaped = this.readEscapedChar(true);
  6950. if (escaped === null) {
  6951. containsInvalid = true;
  6952. } else {
  6953. out += escaped;
  6954. }
  6955. chunkStart = this.state.pos;
  6956. } else if (isNewLine(ch)) {
  6957. out += this.input.slice(chunkStart, this.state.pos);
  6958. ++this.state.pos;
  6959. switch (ch) {
  6960. case 13:
  6961. if (this.input.charCodeAt(this.state.pos) === 10) {
  6962. ++this.state.pos;
  6963. }
  6964. case 10:
  6965. out += "\n";
  6966. break;
  6967. default:
  6968. out += String.fromCharCode(ch);
  6969. break;
  6970. }
  6971. ++this.state.curLine;
  6972. this.state.lineStart = this.state.pos;
  6973. chunkStart = this.state.pos;
  6974. } else {
  6975. ++this.state.pos;
  6976. }
  6977. }
  6978. }
  6979. readEscapedChar(inTemplate) {
  6980. const throwOnInvalid = !inTemplate;
  6981. const ch = this.input.charCodeAt(++this.state.pos);
  6982. ++this.state.pos;
  6983. switch (ch) {
  6984. case 110:
  6985. return "\n";
  6986. case 114:
  6987. return "\r";
  6988. case 120:
  6989. {
  6990. const code = this.readHexChar(2, false, throwOnInvalid);
  6991. return code === null ? null : String.fromCharCode(code);
  6992. }
  6993. case 117:
  6994. {
  6995. const code = this.readCodePoint(throwOnInvalid);
  6996. return code === null ? null : String.fromCodePoint(code);
  6997. }
  6998. case 116:
  6999. return "\t";
  7000. case 98:
  7001. return "\b";
  7002. case 118:
  7003. return "\u000b";
  7004. case 102:
  7005. return "\f";
  7006. case 13:
  7007. if (this.input.charCodeAt(this.state.pos) === 10) {
  7008. ++this.state.pos;
  7009. }
  7010. case 10:
  7011. this.state.lineStart = this.state.pos;
  7012. ++this.state.curLine;
  7013. case 8232:
  7014. case 8233:
  7015. return "";
  7016. case 56:
  7017. case 57:
  7018. if (inTemplate) {
  7019. return null;
  7020. }
  7021. default:
  7022. if (ch >= 48 && ch <= 55) {
  7023. const codePos = this.state.pos - 1;
  7024. let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
  7025. let octal = parseInt(octalStr, 8);
  7026. if (octal > 255) {
  7027. octalStr = octalStr.slice(0, -1);
  7028. octal = parseInt(octalStr, 8);
  7029. }
  7030. this.state.pos += octalStr.length - 1;
  7031. const next = this.input.charCodeAt(this.state.pos);
  7032. if (octalStr !== "0" || next === 56 || next === 57) {
  7033. if (inTemplate) {
  7034. return null;
  7035. } else if (this.state.strict) {
  7036. this.raise(codePos, Errors.StrictOctalLiteral);
  7037. } else {
  7038. this.state.octalPositions.push(codePos);
  7039. }
  7040. }
  7041. return String.fromCharCode(octal);
  7042. }
  7043. return String.fromCharCode(ch);
  7044. }
  7045. }
  7046. readHexChar(len, forceLen, throwOnInvalid) {
  7047. const codePos = this.state.pos;
  7048. const n = this.readInt(16, len, forceLen, false);
  7049. if (n === null) {
  7050. if (throwOnInvalid) {
  7051. this.raise(codePos, Errors.InvalidEscapeSequence);
  7052. } else {
  7053. this.state.pos = codePos - 1;
  7054. }
  7055. }
  7056. return n;
  7057. }
  7058. readWord1() {
  7059. let word = "";
  7060. this.state.containsEsc = false;
  7061. const start = this.state.pos;
  7062. let chunkStart = this.state.pos;
  7063. while (this.state.pos < this.length) {
  7064. const ch = this.input.codePointAt(this.state.pos);
  7065. if (isIdentifierChar(ch)) {
  7066. this.state.pos += ch <= 0xffff ? 1 : 2;
  7067. } else if (this.state.isIterator && ch === 64) {
  7068. ++this.state.pos;
  7069. } else if (ch === 92) {
  7070. this.state.containsEsc = true;
  7071. word += this.input.slice(chunkStart, this.state.pos);
  7072. const escStart = this.state.pos;
  7073. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  7074. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  7075. this.raise(this.state.pos, Errors.MissingUnicodeEscape);
  7076. continue;
  7077. }
  7078. ++this.state.pos;
  7079. const esc = this.readCodePoint(true);
  7080. if (esc !== null) {
  7081. if (!identifierCheck(esc)) {
  7082. this.raise(escStart, Errors.EscapedCharNotAnIdentifier);
  7083. }
  7084. word += String.fromCodePoint(esc);
  7085. }
  7086. chunkStart = this.state.pos;
  7087. } else {
  7088. break;
  7089. }
  7090. }
  7091. return word + this.input.slice(chunkStart, this.state.pos);
  7092. }
  7093. isIterator(word) {
  7094. return word === "@@iterator" || word === "@@asyncIterator";
  7095. }
  7096. readWord() {
  7097. const word = this.readWord1();
  7098. const type = keywords.get(word) || types.name;
  7099. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  7100. this.raise(this.state.pos, Errors.InvalidIdentifier, word);
  7101. }
  7102. this.finishToken(type, word);
  7103. }
  7104. checkKeywordEscapes() {
  7105. const kw = this.state.type.keyword;
  7106. if (kw && this.state.containsEsc) {
  7107. this.raise(this.state.start, Errors.InvalidEscapedReservedWord, kw);
  7108. }
  7109. }
  7110. braceIsBlock(prevType) {
  7111. const parent = this.curContext();
  7112. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  7113. return true;
  7114. }
  7115. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  7116. return !parent.isExpr;
  7117. }
  7118. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  7119. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7120. }
  7121. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  7122. return true;
  7123. }
  7124. if (prevType === types.braceL) {
  7125. return parent === types$1.braceStatement;
  7126. }
  7127. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  7128. return false;
  7129. }
  7130. if (prevType === types.relational) {
  7131. return true;
  7132. }
  7133. return !this.state.exprAllowed;
  7134. }
  7135. updateContext(prevType) {
  7136. const type = this.state.type;
  7137. let update;
  7138. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  7139. this.state.exprAllowed = false;
  7140. } else if (update = type.updateContext) {
  7141. update.call(this, prevType);
  7142. } else {
  7143. this.state.exprAllowed = type.beforeExpr;
  7144. }
  7145. }
  7146. }
  7147. class UtilParser extends Tokenizer {
  7148. addExtra(node, key, val) {
  7149. if (!node) return;
  7150. const extra = node.extra = node.extra || {};
  7151. extra[key] = val;
  7152. }
  7153. isRelational(op) {
  7154. return this.match(types.relational) && this.state.value === op;
  7155. }
  7156. isLookaheadRelational(op) {
  7157. const next = this.nextTokenStart();
  7158. if (this.input.charAt(next) === op) {
  7159. if (next + 1 === this.input.length) {
  7160. return true;
  7161. }
  7162. const afterNext = this.input.charCodeAt(next + 1);
  7163. return afterNext !== op.charCodeAt(0) && afterNext !== 61;
  7164. }
  7165. return false;
  7166. }
  7167. expectRelational(op) {
  7168. if (this.isRelational(op)) {
  7169. this.next();
  7170. } else {
  7171. this.unexpected(null, types.relational);
  7172. }
  7173. }
  7174. isContextual(name) {
  7175. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  7176. }
  7177. isUnparsedContextual(nameStart, name) {
  7178. const nameEnd = nameStart + name.length;
  7179. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  7180. }
  7181. isLookaheadContextual(name) {
  7182. const next = this.nextTokenStart();
  7183. return this.isUnparsedContextual(next, name);
  7184. }
  7185. eatContextual(name) {
  7186. return this.isContextual(name) && this.eat(types.name);
  7187. }
  7188. expectContextual(name, message) {
  7189. if (!this.eatContextual(name)) this.unexpected(null, message);
  7190. }
  7191. canInsertSemicolon() {
  7192. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  7193. }
  7194. hasPrecedingLineBreak() {
  7195. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7196. }
  7197. isLineTerminator() {
  7198. return this.eat(types.semi) || this.canInsertSemicolon();
  7199. }
  7200. semicolon() {
  7201. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  7202. }
  7203. expect(type, pos) {
  7204. this.eat(type) || this.unexpected(pos, type);
  7205. }
  7206. assertNoSpace(message = "Unexpected space.") {
  7207. if (this.state.start > this.state.lastTokEnd) {
  7208. this.raise(this.state.lastTokEnd, message);
  7209. }
  7210. }
  7211. unexpected(pos, messageOrType = "Unexpected token") {
  7212. if (typeof messageOrType !== "string") {
  7213. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  7214. }
  7215. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  7216. }
  7217. expectPlugin(name, pos) {
  7218. if (!this.hasPlugin(name)) {
  7219. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7220. missingPlugin: [name]
  7221. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  7222. }
  7223. return true;
  7224. }
  7225. expectOnePlugin(names, pos) {
  7226. if (!names.some(n => this.hasPlugin(n))) {
  7227. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7228. missingPlugin: names
  7229. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  7230. }
  7231. }
  7232. checkYieldAwaitInDefaultParams() {
  7233. if (this.state.yieldPos !== -1 && (this.state.awaitPos === -1 || this.state.yieldPos < this.state.awaitPos)) {
  7234. this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function");
  7235. }
  7236. if (this.state.awaitPos !== -1) {
  7237. this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function");
  7238. }
  7239. }
  7240. tryParse(fn, oldState = this.state.clone()) {
  7241. const abortSignal = {
  7242. node: null
  7243. };
  7244. try {
  7245. const node = fn((node = null) => {
  7246. abortSignal.node = node;
  7247. throw abortSignal;
  7248. });
  7249. if (this.state.errors.length > oldState.errors.length) {
  7250. const failState = this.state;
  7251. this.state = oldState;
  7252. return {
  7253. node,
  7254. error: failState.errors[oldState.errors.length],
  7255. thrown: false,
  7256. aborted: false,
  7257. failState
  7258. };
  7259. }
  7260. return {
  7261. node,
  7262. error: null,
  7263. thrown: false,
  7264. aborted: false,
  7265. failState: null
  7266. };
  7267. } catch (error) {
  7268. const failState = this.state;
  7269. this.state = oldState;
  7270. if (error instanceof SyntaxError) {
  7271. return {
  7272. node: null,
  7273. error,
  7274. thrown: true,
  7275. aborted: false,
  7276. failState
  7277. };
  7278. }
  7279. if (error === abortSignal) {
  7280. return {
  7281. node: abortSignal.node,
  7282. error: null,
  7283. thrown: false,
  7284. aborted: true,
  7285. failState
  7286. };
  7287. }
  7288. throw error;
  7289. }
  7290. }
  7291. checkExpressionErrors(refExpressionErrors, andThrow) {
  7292. if (!refExpressionErrors) return false;
  7293. const {
  7294. shorthandAssign,
  7295. doubleProto
  7296. } = refExpressionErrors;
  7297. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  7298. if (shorthandAssign >= 0) {
  7299. this.unexpected(shorthandAssign);
  7300. }
  7301. if (doubleProto >= 0) {
  7302. this.raise(doubleProto, Errors.DuplicateProto);
  7303. }
  7304. }
  7305. }
  7306. class ExpressionErrors {
  7307. constructor() {
  7308. this.shorthandAssign = -1;
  7309. this.doubleProto = -1;
  7310. }
  7311. }
  7312. class Node {
  7313. constructor(parser, pos, loc) {
  7314. this.type = "";
  7315. this.start = pos;
  7316. this.end = 0;
  7317. this.loc = new SourceLocation(loc);
  7318. if (parser && parser.options.ranges) this.range = [pos, 0];
  7319. if (parser && parser.filename) this.loc.filename = parser.filename;
  7320. }
  7321. __clone() {
  7322. const newNode = new Node();
  7323. const keys = Object.keys(this);
  7324. for (let i = 0, length = keys.length; i < length; i++) {
  7325. const key = keys[i];
  7326. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  7327. newNode[key] = this[key];
  7328. }
  7329. }
  7330. return newNode;
  7331. }
  7332. }
  7333. class NodeUtils extends UtilParser {
  7334. startNode() {
  7335. return new Node(this, this.state.start, this.state.startLoc);
  7336. }
  7337. startNodeAt(pos, loc) {
  7338. return new Node(this, pos, loc);
  7339. }
  7340. startNodeAtNode(type) {
  7341. return this.startNodeAt(type.start, type.loc.start);
  7342. }
  7343. finishNode(node, type) {
  7344. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  7345. }
  7346. finishNodeAt(node, type, pos, loc) {
  7347. node.type = type;
  7348. node.end = pos;
  7349. node.loc.end = loc;
  7350. if (this.options.ranges) node.range[1] = pos;
  7351. this.processComment(node);
  7352. return node;
  7353. }
  7354. resetStartLocation(node, start, startLoc) {
  7355. node.start = start;
  7356. node.loc.start = startLoc;
  7357. if (this.options.ranges) node.range[0] = start;
  7358. }
  7359. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  7360. node.end = end;
  7361. node.loc.end = endLoc;
  7362. if (this.options.ranges) node.range[1] = end;
  7363. }
  7364. resetStartLocationFromNode(node, locationNode) {
  7365. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  7366. }
  7367. }
  7368. const unwrapParenthesizedExpression = node => {
  7369. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  7370. };
  7371. class LValParser extends NodeUtils {
  7372. toAssignable(node) {
  7373. var _node$extra, _node$extra3;
  7374. let parenthesized = undefined;
  7375. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  7376. parenthesized = unwrapParenthesizedExpression(node);
  7377. if (parenthesized.type !== "Identifier" && parenthesized.type !== "MemberExpression") {
  7378. this.raise(node.start, Errors.InvalidParenthesizedAssignment);
  7379. }
  7380. }
  7381. switch (node.type) {
  7382. case "Identifier":
  7383. case "ObjectPattern":
  7384. case "ArrayPattern":
  7385. case "AssignmentPattern":
  7386. break;
  7387. case "ObjectExpression":
  7388. node.type = "ObjectPattern";
  7389. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  7390. var _node$extra2;
  7391. const prop = node.properties[i];
  7392. const isLast = i === last;
  7393. this.toAssignableObjectExpressionProp(prop, isLast);
  7394. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  7395. this.raiseRestNotLast(node.extra.trailingComma);
  7396. }
  7397. }
  7398. break;
  7399. case "ObjectProperty":
  7400. this.toAssignable(node.value);
  7401. break;
  7402. case "SpreadElement":
  7403. {
  7404. this.checkToRestConversion(node);
  7405. node.type = "RestElement";
  7406. const arg = node.argument;
  7407. this.toAssignable(arg);
  7408. break;
  7409. }
  7410. case "ArrayExpression":
  7411. node.type = "ArrayPattern";
  7412. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma);
  7413. break;
  7414. case "AssignmentExpression":
  7415. if (node.operator !== "=") {
  7416. this.raise(node.left.end, Errors.MissingEqInAssignment);
  7417. }
  7418. node.type = "AssignmentPattern";
  7419. delete node.operator;
  7420. this.toAssignable(node.left);
  7421. break;
  7422. case "ParenthesizedExpression":
  7423. this.toAssignable(parenthesized);
  7424. break;
  7425. }
  7426. return node;
  7427. }
  7428. toAssignableObjectExpressionProp(prop, isLast) {
  7429. if (prop.type === "ObjectMethod") {
  7430. const error = prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod;
  7431. this.raise(prop.key.start, error);
  7432. } else if (prop.type === "SpreadElement" && !isLast) {
  7433. this.raiseRestNotLast(prop.start);
  7434. } else {
  7435. this.toAssignable(prop);
  7436. }
  7437. }
  7438. toAssignableList(exprList, trailingCommaPos) {
  7439. let end = exprList.length;
  7440. if (end) {
  7441. const last = exprList[end - 1];
  7442. if (last && last.type === "RestElement") {
  7443. --end;
  7444. } else if (last && last.type === "SpreadElement") {
  7445. last.type = "RestElement";
  7446. const arg = last.argument;
  7447. this.toAssignable(arg);
  7448. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  7449. this.unexpected(arg.start);
  7450. }
  7451. if (trailingCommaPos) {
  7452. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  7453. }
  7454. --end;
  7455. }
  7456. }
  7457. for (let i = 0; i < end; i++) {
  7458. const elt = exprList[i];
  7459. if (elt) {
  7460. this.toAssignable(elt);
  7461. if (elt.type === "RestElement") {
  7462. this.raiseRestNotLast(elt.start);
  7463. }
  7464. }
  7465. }
  7466. return exprList;
  7467. }
  7468. toReferencedList(exprList, isParenthesizedExpr) {
  7469. return exprList;
  7470. }
  7471. toReferencedListDeep(exprList, isParenthesizedExpr) {
  7472. this.toReferencedList(exprList, isParenthesizedExpr);
  7473. for (let _i = 0; _i < exprList.length; _i++) {
  7474. const expr = exprList[_i];
  7475. if (expr && expr.type === "ArrayExpression") {
  7476. this.toReferencedListDeep(expr.elements);
  7477. }
  7478. }
  7479. }
  7480. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  7481. const node = this.startNode();
  7482. this.next();
  7483. node.argument = this.parseMaybeAssign(false, refExpressionErrors, undefined, refNeedsArrowPos);
  7484. return this.finishNode(node, "SpreadElement");
  7485. }
  7486. parseRestBinding() {
  7487. const node = this.startNode();
  7488. this.next();
  7489. node.argument = this.parseBindingAtom();
  7490. return this.finishNode(node, "RestElement");
  7491. }
  7492. parseBindingAtom() {
  7493. switch (this.state.type) {
  7494. case types.bracketL:
  7495. {
  7496. const node = this.startNode();
  7497. this.next();
  7498. node.elements = this.parseBindingList(types.bracketR, 93, true);
  7499. return this.finishNode(node, "ArrayPattern");
  7500. }
  7501. case types.braceL:
  7502. return this.parseObj(types.braceR, true);
  7503. }
  7504. return this.parseIdentifier();
  7505. }
  7506. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  7507. const elts = [];
  7508. let first = true;
  7509. while (!this.eat(close)) {
  7510. if (first) {
  7511. first = false;
  7512. } else {
  7513. this.expect(types.comma);
  7514. }
  7515. if (allowEmpty && this.match(types.comma)) {
  7516. elts.push(null);
  7517. } else if (this.eat(close)) {
  7518. break;
  7519. } else if (this.match(types.ellipsis)) {
  7520. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  7521. this.checkCommaAfterRest(closeCharCode);
  7522. this.expect(close);
  7523. break;
  7524. } else {
  7525. const decorators = [];
  7526. if (this.match(types.at) && this.hasPlugin("decorators")) {
  7527. this.raise(this.state.start, Errors.UnsupportedParameterDecorator);
  7528. }
  7529. while (this.match(types.at)) {
  7530. decorators.push(this.parseDecorator());
  7531. }
  7532. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  7533. }
  7534. }
  7535. return elts;
  7536. }
  7537. parseAssignableListItem(allowModifiers, decorators) {
  7538. const left = this.parseMaybeDefault();
  7539. this.parseAssignableListItemTypes(left);
  7540. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  7541. if (decorators.length) {
  7542. left.decorators = decorators;
  7543. }
  7544. return elt;
  7545. }
  7546. parseAssignableListItemTypes(param) {
  7547. return param;
  7548. }
  7549. parseMaybeDefault(startPos, startLoc, left) {
  7550. startLoc = startLoc || this.state.startLoc;
  7551. startPos = startPos || this.state.start;
  7552. left = left || this.parseBindingAtom();
  7553. if (!this.eat(types.eq)) return left;
  7554. const node = this.startNodeAt(startPos, startLoc);
  7555. node.left = left;
  7556. node.right = this.parseMaybeAssign();
  7557. return this.finishNode(node, "AssignmentPattern");
  7558. }
  7559. checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription, disallowLetBinding, strictModeChanged = false) {
  7560. switch (expr.type) {
  7561. case "Identifier":
  7562. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) {
  7563. this.raise(expr.start, bindingType === BIND_NONE ? Errors.StrictEvalArguments : Errors.StrictEvalArgumentsBinding, expr.name);
  7564. }
  7565. if (checkClashes) {
  7566. const key = `_${expr.name}`;
  7567. if (checkClashes[key]) {
  7568. this.raise(expr.start, Errors.ParamDupe);
  7569. } else {
  7570. checkClashes[key] = true;
  7571. }
  7572. }
  7573. if (disallowLetBinding && expr.name === "let") {
  7574. this.raise(expr.start, Errors.LetInLexicalBinding);
  7575. }
  7576. if (!(bindingType & BIND_NONE)) {
  7577. this.scope.declareName(expr.name, bindingType, expr.start);
  7578. }
  7579. break;
  7580. case "MemberExpression":
  7581. if (bindingType !== BIND_NONE) {
  7582. this.raise(expr.start, Errors.InvalidPropertyBindingPattern);
  7583. }
  7584. break;
  7585. case "ObjectPattern":
  7586. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  7587. let prop = _expr$properties[_i2];
  7588. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  7589. this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding);
  7590. }
  7591. break;
  7592. case "ArrayPattern":
  7593. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  7594. const elem = _expr$elements[_i3];
  7595. if (elem) {
  7596. this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding);
  7597. }
  7598. }
  7599. break;
  7600. case "AssignmentPattern":
  7601. this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern");
  7602. break;
  7603. case "RestElement":
  7604. this.checkLVal(expr.argument, bindingType, checkClashes, "rest element");
  7605. break;
  7606. case "ParenthesizedExpression":
  7607. this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression");
  7608. break;
  7609. default:
  7610. {
  7611. this.raise(expr.start, bindingType === BIND_NONE ? Errors.InvalidLhs : Errors.InvalidLhsBinding, contextDescription);
  7612. }
  7613. }
  7614. }
  7615. checkToRestConversion(node) {
  7616. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  7617. this.raise(node.argument.start, Errors.InvalidRestAssignmentPattern);
  7618. }
  7619. }
  7620. checkCommaAfterRest(close) {
  7621. if (this.match(types.comma)) {
  7622. if (this.lookaheadCharCode() === close) {
  7623. this.raiseTrailingCommaAfterRest(this.state.start);
  7624. } else {
  7625. this.raiseRestNotLast(this.state.start);
  7626. }
  7627. }
  7628. }
  7629. raiseRestNotLast(pos) {
  7630. throw this.raise(pos, Errors.ElementAfterRest);
  7631. }
  7632. raiseTrailingCommaAfterRest(pos) {
  7633. this.raise(pos, Errors.RestTrailingComma);
  7634. }
  7635. }
  7636. class ExpressionParser extends LValParser {
  7637. checkDuplicatedProto(prop, protoRef, refExpressionErrors) {
  7638. if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) {
  7639. return;
  7640. }
  7641. const key = prop.key;
  7642. const name = key.type === "Identifier" ? key.name : String(key.value);
  7643. if (name === "__proto__") {
  7644. if (protoRef.used) {
  7645. if (refExpressionErrors) {
  7646. if (refExpressionErrors.doubleProto === -1) {
  7647. refExpressionErrors.doubleProto = key.start;
  7648. }
  7649. } else {
  7650. this.raise(key.start, Errors.DuplicateProto);
  7651. }
  7652. }
  7653. protoRef.used = true;
  7654. }
  7655. }
  7656. getExpression() {
  7657. let paramFlags = PARAM;
  7658. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  7659. paramFlags |= PARAM_AWAIT;
  7660. }
  7661. this.scope.enter(SCOPE_PROGRAM);
  7662. this.prodParam.enter(paramFlags);
  7663. this.nextToken();
  7664. const expr = this.parseExpression();
  7665. if (!this.match(types.eof)) {
  7666. this.unexpected();
  7667. }
  7668. expr.comments = this.state.comments;
  7669. expr.errors = this.state.errors;
  7670. return expr;
  7671. }
  7672. parseExpression(noIn, refExpressionErrors) {
  7673. const startPos = this.state.start;
  7674. const startLoc = this.state.startLoc;
  7675. const expr = this.parseMaybeAssign(noIn, refExpressionErrors);
  7676. if (this.match(types.comma)) {
  7677. const node = this.startNodeAt(startPos, startLoc);
  7678. node.expressions = [expr];
  7679. while (this.eat(types.comma)) {
  7680. node.expressions.push(this.parseMaybeAssign(noIn, refExpressionErrors));
  7681. }
  7682. this.toReferencedList(node.expressions);
  7683. return this.finishNode(node, "SequenceExpression");
  7684. }
  7685. return expr;
  7686. }
  7687. parseMaybeAssign(noIn, refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  7688. const startPos = this.state.start;
  7689. const startLoc = this.state.startLoc;
  7690. if (this.isContextual("yield")) {
  7691. if (this.prodParam.hasYield) {
  7692. let left = this.parseYield(noIn);
  7693. if (afterLeftParse) {
  7694. left = afterLeftParse.call(this, left, startPos, startLoc);
  7695. }
  7696. return left;
  7697. } else {
  7698. this.state.exprAllowed = false;
  7699. }
  7700. }
  7701. let ownExpressionErrors;
  7702. if (refExpressionErrors) {
  7703. ownExpressionErrors = false;
  7704. } else {
  7705. refExpressionErrors = new ExpressionErrors();
  7706. ownExpressionErrors = true;
  7707. }
  7708. if (this.match(types.parenL) || this.match(types.name)) {
  7709. this.state.potentialArrowAt = this.state.start;
  7710. }
  7711. let left = this.parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos);
  7712. if (afterLeftParse) {
  7713. left = afterLeftParse.call(this, left, startPos, startLoc);
  7714. }
  7715. if (this.state.type.isAssign) {
  7716. const node = this.startNodeAt(startPos, startLoc);
  7717. const operator = this.state.value;
  7718. node.operator = operator;
  7719. if (operator === "??=") {
  7720. this.expectPlugin("logicalAssignment");
  7721. }
  7722. if (operator === "||=" || operator === "&&=") {
  7723. this.expectPlugin("logicalAssignment");
  7724. }
  7725. if (this.match(types.eq)) {
  7726. node.left = this.toAssignable(left);
  7727. refExpressionErrors.doubleProto = -1;
  7728. } else {
  7729. node.left = left;
  7730. }
  7731. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  7732. refExpressionErrors.shorthandAssign = -1;
  7733. }
  7734. this.checkLVal(left, undefined, undefined, "assignment expression");
  7735. this.next();
  7736. node.right = this.parseMaybeAssign(noIn);
  7737. return this.finishNode(node, "AssignmentExpression");
  7738. } else if (ownExpressionErrors) {
  7739. this.checkExpressionErrors(refExpressionErrors, true);
  7740. }
  7741. return left;
  7742. }
  7743. parseMaybeConditional(noIn, refExpressionErrors, refNeedsArrowPos) {
  7744. const startPos = this.state.start;
  7745. const startLoc = this.state.startLoc;
  7746. const potentialArrowAt = this.state.potentialArrowAt;
  7747. const expr = this.parseExprOps(noIn, refExpressionErrors);
  7748. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7749. return expr;
  7750. }
  7751. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7752. return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  7753. }
  7754. parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  7755. if (this.eat(types.question)) {
  7756. const node = this.startNodeAt(startPos, startLoc);
  7757. node.test = expr;
  7758. node.consequent = this.parseMaybeAssign();
  7759. this.expect(types.colon);
  7760. node.alternate = this.parseMaybeAssign(noIn);
  7761. return this.finishNode(node, "ConditionalExpression");
  7762. }
  7763. return expr;
  7764. }
  7765. parseExprOps(noIn, refExpressionErrors) {
  7766. const startPos = this.state.start;
  7767. const startLoc = this.state.startLoc;
  7768. const potentialArrowAt = this.state.potentialArrowAt;
  7769. const expr = this.parseMaybeUnary(refExpressionErrors);
  7770. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7771. return expr;
  7772. }
  7773. if (this.checkExpressionErrors(refExpressionErrors, false)) {
  7774. return expr;
  7775. }
  7776. return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  7777. }
  7778. parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  7779. let prec = this.state.type.binop;
  7780. if (prec != null && (!noIn || !this.match(types._in))) {
  7781. if (prec > minPrec) {
  7782. const operator = this.state.value;
  7783. if (operator === "|>" && this.state.inFSharpPipelineDirectBody) {
  7784. return left;
  7785. }
  7786. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  7787. node.left = left;
  7788. node.operator = operator;
  7789. if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  7790. this.raise(left.argument.start, Errors.UnexpectedTokenUnaryExponentiation);
  7791. }
  7792. const op = this.state.type;
  7793. const logical = op === types.logicalOR || op === types.logicalAND;
  7794. const coalesce = op === types.nullishCoalescing;
  7795. if (op === types.pipeline) {
  7796. this.expectPlugin("pipelineOperator");
  7797. this.state.inPipeline = true;
  7798. this.checkPipelineAtInfixOperator(left, leftStartPos);
  7799. } else if (coalesce) {
  7800. prec = types.logicalAND.binop;
  7801. }
  7802. this.next();
  7803. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  7804. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  7805. throw this.raise(this.state.start, Errors.UnexpectedAwaitAfterPipelineBody);
  7806. }
  7807. }
  7808. node.right = this.parseExprOpRightExpr(op, prec, noIn);
  7809. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  7810. const nextOp = this.state.type;
  7811. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  7812. throw this.raise(this.state.start, Errors.MixingCoalesceWithLogical);
  7813. }
  7814. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  7815. }
  7816. }
  7817. return left;
  7818. }
  7819. parseExprOpRightExpr(op, prec, noIn) {
  7820. const startPos = this.state.start;
  7821. const startLoc = this.state.startLoc;
  7822. switch (op) {
  7823. case types.pipeline:
  7824. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  7825. case "smart":
  7826. return this.withTopicPermittingContext(() => {
  7827. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc);
  7828. });
  7829. case "fsharp":
  7830. return this.withSoloAwaitPermittingContext(() => {
  7831. return this.parseFSharpPipelineBody(prec, noIn);
  7832. });
  7833. }
  7834. default:
  7835. return this.parseExprOpBaseRightExpr(op, prec, noIn);
  7836. }
  7837. }
  7838. parseExprOpBaseRightExpr(op, prec, noIn) {
  7839. const startPos = this.state.start;
  7840. const startLoc = this.state.startLoc;
  7841. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
  7842. }
  7843. parseMaybeUnary(refExpressionErrors) {
  7844. if (this.isContextual("await") && this.isAwaitAllowed()) {
  7845. return this.parseAwait();
  7846. } else if (this.state.type.prefix) {
  7847. const node = this.startNode();
  7848. const update = this.match(types.incDec);
  7849. node.operator = this.state.value;
  7850. node.prefix = true;
  7851. if (node.operator === "throw") {
  7852. this.expectPlugin("throwExpressions");
  7853. }
  7854. this.next();
  7855. node.argument = this.parseMaybeUnary();
  7856. this.checkExpressionErrors(refExpressionErrors, true);
  7857. if (update) {
  7858. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  7859. } else if (this.state.strict && node.operator === "delete") {
  7860. const arg = node.argument;
  7861. if (arg.type === "Identifier") {
  7862. this.raise(node.start, Errors.StrictDelete);
  7863. } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") {
  7864. this.raise(node.start, Errors.DeletePrivateField);
  7865. }
  7866. }
  7867. return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  7868. }
  7869. const startPos = this.state.start;
  7870. const startLoc = this.state.startLoc;
  7871. let expr = this.parseExprSubscripts(refExpressionErrors);
  7872. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  7873. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  7874. const node = this.startNodeAt(startPos, startLoc);
  7875. node.operator = this.state.value;
  7876. node.prefix = false;
  7877. node.argument = expr;
  7878. this.checkLVal(expr, undefined, undefined, "postfix operation");
  7879. this.next();
  7880. expr = this.finishNode(node, "UpdateExpression");
  7881. }
  7882. return expr;
  7883. }
  7884. parseExprSubscripts(refExpressionErrors) {
  7885. const startPos = this.state.start;
  7886. const startLoc = this.state.startLoc;
  7887. const potentialArrowAt = this.state.potentialArrowAt;
  7888. const expr = this.parseExprAtom(refExpressionErrors);
  7889. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  7890. return expr;
  7891. }
  7892. return this.parseSubscripts(expr, startPos, startLoc);
  7893. }
  7894. parseSubscripts(base, startPos, startLoc, noCalls) {
  7895. const state = {
  7896. optionalChainMember: false,
  7897. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  7898. stop: false
  7899. };
  7900. do {
  7901. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  7902. if (state.maybeAsyncArrow) {
  7903. this.state.maybeInAsyncArrowHead = true;
  7904. }
  7905. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  7906. state.maybeAsyncArrow = false;
  7907. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  7908. } while (!state.stop);
  7909. return base;
  7910. }
  7911. parseSubscript(base, startPos, startLoc, noCalls, state) {
  7912. if (!noCalls && this.eat(types.doubleColon)) {
  7913. const node = this.startNodeAt(startPos, startLoc);
  7914. node.object = base;
  7915. node.callee = this.parseNoCallExpr();
  7916. state.stop = true;
  7917. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  7918. }
  7919. let optional = false;
  7920. if (this.match(types.questionDot)) {
  7921. state.optionalChainMember = optional = true;
  7922. if (noCalls && this.lookaheadCharCode() === 40) {
  7923. state.stop = true;
  7924. return base;
  7925. }
  7926. this.next();
  7927. }
  7928. const computed = this.eat(types.bracketL);
  7929. if (optional && !this.match(types.parenL) && !this.match(types.backQuote) || computed || this.eat(types.dot)) {
  7930. const node = this.startNodeAt(startPos, startLoc);
  7931. node.object = base;
  7932. node.property = computed ? this.parseExpression() : optional ? this.parseIdentifier(true) : this.parseMaybePrivateName(true);
  7933. node.computed = computed;
  7934. if (node.property.type === "PrivateName") {
  7935. if (node.object.type === "Super") {
  7936. this.raise(startPos, Errors.SuperPrivateField);
  7937. }
  7938. this.classScope.usePrivateName(node.property.id.name, node.property.start);
  7939. }
  7940. if (computed) {
  7941. this.expect(types.bracketR);
  7942. }
  7943. if (state.optionalChainMember) {
  7944. node.optional = optional;
  7945. return this.finishNode(node, "OptionalMemberExpression");
  7946. } else {
  7947. return this.finishNode(node, "MemberExpression");
  7948. }
  7949. } else if (!noCalls && this.match(types.parenL)) {
  7950. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  7951. const oldYieldPos = this.state.yieldPos;
  7952. const oldAwaitPos = this.state.awaitPos;
  7953. this.state.maybeInArrowParameters = true;
  7954. this.state.yieldPos = -1;
  7955. this.state.awaitPos = -1;
  7956. this.next();
  7957. let node = this.startNodeAt(startPos, startLoc);
  7958. node.callee = base;
  7959. if (optional) {
  7960. node.optional = true;
  7961. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  7962. } else {
  7963. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  7964. }
  7965. this.finishCallExpression(node, state.optionalChainMember);
  7966. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  7967. state.stop = true;
  7968. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  7969. this.checkYieldAwaitInDefaultParams();
  7970. this.state.yieldPos = oldYieldPos;
  7971. this.state.awaitPos = oldAwaitPos;
  7972. } else {
  7973. this.toReferencedListDeep(node.arguments);
  7974. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  7975. if (!this.isAwaitAllowed() && !oldMaybeInArrowParameters || oldAwaitPos !== -1) {
  7976. this.state.awaitPos = oldAwaitPos;
  7977. }
  7978. }
  7979. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  7980. return node;
  7981. } else if (this.match(types.backQuote)) {
  7982. return this.parseTaggedTemplateExpression(startPos, startLoc, base, state);
  7983. } else {
  7984. state.stop = true;
  7985. return base;
  7986. }
  7987. }
  7988. parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) {
  7989. const node = this.startNodeAt(startPos, startLoc);
  7990. node.tag = base;
  7991. node.quasi = this.parseTemplate(true);
  7992. if (typeArguments) node.typeParameters = typeArguments;
  7993. if (state.optionalChainMember) {
  7994. this.raise(startPos, Errors.OptionalChainingNoTemplate);
  7995. }
  7996. return this.finishNode(node, "TaggedTemplateExpression");
  7997. }
  7998. atPossibleAsyncArrow(base) {
  7999. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  8000. }
  8001. finishCallExpression(node, optional) {
  8002. if (node.callee.type === "Import") {
  8003. if (node.arguments.length !== 1) {
  8004. this.raise(node.start, Errors.ImportCallArity);
  8005. } else {
  8006. const importArg = node.arguments[0];
  8007. if (importArg && importArg.type === "SpreadElement") {
  8008. this.raise(importArg.start, Errors.ImportCallSpreadArgument);
  8009. }
  8010. }
  8011. }
  8012. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  8013. }
  8014. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  8015. const elts = [];
  8016. let innerParenStart;
  8017. let first = true;
  8018. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8019. this.state.inFSharpPipelineDirectBody = false;
  8020. while (!this.eat(close)) {
  8021. if (first) {
  8022. first = false;
  8023. } else {
  8024. this.expect(types.comma);
  8025. if (this.match(close)) {
  8026. if (dynamicImport) {
  8027. this.raise(this.state.lastTokStart, Errors.ImportCallArgumentTrailingComma);
  8028. }
  8029. if (nodeForExtra) {
  8030. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8031. }
  8032. this.next();
  8033. break;
  8034. }
  8035. }
  8036. if (this.match(types.parenL) && !innerParenStart) {
  8037. innerParenStart = this.state.start;
  8038. }
  8039. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8040. start: 0
  8041. } : undefined, allowPlaceholder));
  8042. }
  8043. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  8044. this.unexpected();
  8045. }
  8046. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8047. return elts;
  8048. }
  8049. shouldParseAsyncArrow() {
  8050. return this.match(types.arrow) && !this.canInsertSemicolon();
  8051. }
  8052. parseAsyncArrowFromCallExpression(node, call) {
  8053. var _call$extra;
  8054. this.expect(types.arrow);
  8055. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8056. return node;
  8057. }
  8058. parseNoCallExpr() {
  8059. const startPos = this.state.start;
  8060. const startLoc = this.state.startLoc;
  8061. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8062. }
  8063. parseExprAtom(refExpressionErrors) {
  8064. if (this.state.type === types.slash) this.readRegexp();
  8065. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8066. let node;
  8067. switch (this.state.type) {
  8068. case types._super:
  8069. node = this.startNode();
  8070. this.next();
  8071. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  8072. this.raise(node.start, Errors.SuperNotAllowed);
  8073. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  8074. this.raise(node.start, Errors.UnexpectedSuper);
  8075. }
  8076. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  8077. this.raise(node.start, Errors.UnsupportedSuper);
  8078. }
  8079. return this.finishNode(node, "Super");
  8080. case types._import:
  8081. node = this.startNode();
  8082. this.next();
  8083. if (this.match(types.dot)) {
  8084. return this.parseImportMetaProperty(node);
  8085. }
  8086. if (!this.match(types.parenL)) {
  8087. this.raise(this.state.lastTokStart, Errors.UnsupportedImport);
  8088. }
  8089. return this.finishNode(node, "Import");
  8090. case types._this:
  8091. node = this.startNode();
  8092. this.next();
  8093. return this.finishNode(node, "ThisExpression");
  8094. case types.name:
  8095. {
  8096. node = this.startNode();
  8097. const containsEsc = this.state.containsEsc;
  8098. const id = this.parseIdentifier();
  8099. if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) {
  8100. const last = this.state.context.length - 1;
  8101. if (this.state.context[last] !== types$1.functionStatement) {
  8102. throw new Error("Internal error");
  8103. }
  8104. this.state.context[last] = types$1.functionExpression;
  8105. this.next();
  8106. return this.parseFunction(node, undefined, true);
  8107. } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) {
  8108. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8109. const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
  8110. const oldYieldPos = this.state.yieldPos;
  8111. const oldAwaitPos = this.state.awaitPos;
  8112. this.state.maybeInArrowParameters = true;
  8113. this.state.maybeInAsyncArrowHead = true;
  8114. this.state.yieldPos = -1;
  8115. this.state.awaitPos = -1;
  8116. const params = [this.parseIdentifier()];
  8117. this.expect(types.arrow);
  8118. this.checkYieldAwaitInDefaultParams();
  8119. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8120. this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
  8121. this.state.yieldPos = oldYieldPos;
  8122. this.state.awaitPos = oldAwaitPos;
  8123. this.parseArrowExpression(node, params, true);
  8124. return node;
  8125. }
  8126. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8127. this.next();
  8128. this.parseArrowExpression(node, [id], false);
  8129. return node;
  8130. }
  8131. return id;
  8132. }
  8133. case types._do:
  8134. {
  8135. this.expectPlugin("doExpressions");
  8136. const node = this.startNode();
  8137. this.next();
  8138. const oldLabels = this.state.labels;
  8139. this.state.labels = [];
  8140. node.body = this.parseBlock();
  8141. this.state.labels = oldLabels;
  8142. return this.finishNode(node, "DoExpression");
  8143. }
  8144. case types.regexp:
  8145. {
  8146. const value = this.state.value;
  8147. node = this.parseLiteral(value.value, "RegExpLiteral");
  8148. node.pattern = value.pattern;
  8149. node.flags = value.flags;
  8150. return node;
  8151. }
  8152. case types.num:
  8153. return this.parseLiteral(this.state.value, "NumericLiteral");
  8154. case types.bigint:
  8155. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8156. case types.string:
  8157. return this.parseLiteral(this.state.value, "StringLiteral");
  8158. case types._null:
  8159. node = this.startNode();
  8160. this.next();
  8161. return this.finishNode(node, "NullLiteral");
  8162. case types._true:
  8163. case types._false:
  8164. return this.parseBooleanLiteral();
  8165. case types.parenL:
  8166. return this.parseParenAndDistinguishExpression(canBeArrow);
  8167. case types.bracketBarL:
  8168. case types.bracketHashL:
  8169. {
  8170. this.expectPlugin("recordAndTuple");
  8171. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8172. const close = this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR;
  8173. this.state.inFSharpPipelineDirectBody = false;
  8174. node = this.startNode();
  8175. this.next();
  8176. node.elements = this.parseExprList(close, true, refExpressionErrors, node);
  8177. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8178. return this.finishNode(node, "TupleExpression");
  8179. }
  8180. case types.bracketL:
  8181. {
  8182. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8183. this.state.inFSharpPipelineDirectBody = false;
  8184. node = this.startNode();
  8185. this.next();
  8186. node.elements = this.parseExprList(types.bracketR, true, refExpressionErrors, node);
  8187. if (!this.state.maybeInArrowParameters) {
  8188. this.toReferencedList(node.elements);
  8189. }
  8190. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8191. return this.finishNode(node, "ArrayExpression");
  8192. }
  8193. case types.braceBarL:
  8194. case types.braceHashL:
  8195. {
  8196. this.expectPlugin("recordAndTuple");
  8197. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8198. const close = this.state.type === types.braceBarL ? types.braceBarR : types.braceR;
  8199. this.state.inFSharpPipelineDirectBody = false;
  8200. const ret = this.parseObj(close, false, true, refExpressionErrors);
  8201. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8202. return ret;
  8203. }
  8204. case types.braceL:
  8205. {
  8206. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8207. this.state.inFSharpPipelineDirectBody = false;
  8208. const ret = this.parseObj(types.braceR, false, false, refExpressionErrors);
  8209. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8210. return ret;
  8211. }
  8212. case types._function:
  8213. return this.parseFunctionExpression();
  8214. case types.at:
  8215. this.parseDecorators();
  8216. case types._class:
  8217. node = this.startNode();
  8218. this.takeDecorators(node);
  8219. return this.parseClass(node, false);
  8220. case types._new:
  8221. return this.parseNew();
  8222. case types.backQuote:
  8223. return this.parseTemplate(false);
  8224. case types.doubleColon:
  8225. {
  8226. node = this.startNode();
  8227. this.next();
  8228. node.object = null;
  8229. const callee = node.callee = this.parseNoCallExpr();
  8230. if (callee.type === "MemberExpression") {
  8231. return this.finishNode(node, "BindExpression");
  8232. } else {
  8233. throw this.raise(callee.start, Errors.UnsupportedBind);
  8234. }
  8235. }
  8236. case types.hash:
  8237. {
  8238. if (this.state.inPipeline) {
  8239. node = this.startNode();
  8240. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  8241. this.raise(node.start, Errors.PrimaryTopicRequiresSmartPipeline);
  8242. }
  8243. this.next();
  8244. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  8245. this.raise(node.start, Errors.PrimaryTopicNotAllowed);
  8246. }
  8247. this.registerTopicReference();
  8248. return this.finishNode(node, "PipelinePrimaryTopicReference");
  8249. }
  8250. }
  8251. default:
  8252. throw this.unexpected();
  8253. }
  8254. }
  8255. parseBooleanLiteral() {
  8256. const node = this.startNode();
  8257. node.value = this.match(types._true);
  8258. this.next();
  8259. return this.finishNode(node, "BooleanLiteral");
  8260. }
  8261. parseMaybePrivateName(isPrivateNameAllowed) {
  8262. const isPrivate = this.match(types.hash);
  8263. if (isPrivate) {
  8264. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  8265. if (!isPrivateNameAllowed) {
  8266. this.raise(this.state.pos, Errors.UnexpectedPrivateField);
  8267. }
  8268. const node = this.startNode();
  8269. this.next();
  8270. this.assertNoSpace("Unexpected space between # and identifier");
  8271. node.id = this.parseIdentifier(true);
  8272. return this.finishNode(node, "PrivateName");
  8273. } else {
  8274. return this.parseIdentifier(true);
  8275. }
  8276. }
  8277. parseFunctionExpression() {
  8278. const node = this.startNode();
  8279. let meta = this.startNode();
  8280. this.next();
  8281. meta = this.createIdentifier(meta, "function");
  8282. if (this.prodParam.hasYield && this.eat(types.dot)) {
  8283. return this.parseMetaProperty(node, meta, "sent");
  8284. }
  8285. return this.parseFunction(node);
  8286. }
  8287. parseMetaProperty(node, meta, propertyName) {
  8288. node.meta = meta;
  8289. if (meta.name === "function" && propertyName === "sent") {
  8290. if (this.isContextual(propertyName)) {
  8291. this.expectPlugin("functionSent");
  8292. } else if (!this.hasPlugin("functionSent")) {
  8293. this.unexpected();
  8294. }
  8295. }
  8296. const containsEsc = this.state.containsEsc;
  8297. node.property = this.parseIdentifier(true);
  8298. if (node.property.name !== propertyName || containsEsc) {
  8299. this.raise(node.property.start, Errors.UnsupportedMetaProperty, meta.name, propertyName);
  8300. }
  8301. return this.finishNode(node, "MetaProperty");
  8302. }
  8303. parseImportMetaProperty(node) {
  8304. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  8305. this.expect(types.dot);
  8306. if (this.isContextual("meta")) {
  8307. this.expectPlugin("importMeta");
  8308. if (!this.inModule) {
  8309. this.raiseWithData(id.start, {
  8310. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  8311. }, Errors.ImportMetaOutsideModule);
  8312. }
  8313. this.sawUnambiguousESM = true;
  8314. } else if (!this.hasPlugin("importMeta")) {
  8315. this.raise(id.start, Errors.ImportCallArityLtOne);
  8316. }
  8317. return this.parseMetaProperty(node, id, "meta");
  8318. }
  8319. parseLiteral(value, type, startPos, startLoc) {
  8320. startPos = startPos || this.state.start;
  8321. startLoc = startLoc || this.state.startLoc;
  8322. const node = this.startNodeAt(startPos, startLoc);
  8323. this.addExtra(node, "rawValue", value);
  8324. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  8325. node.value = value;
  8326. this.next();
  8327. return this.finishNode(node, type);
  8328. }
  8329. parseParenAndDistinguishExpression(canBeArrow) {
  8330. const startPos = this.state.start;
  8331. const startLoc = this.state.startLoc;
  8332. let val;
  8333. this.expect(types.parenL);
  8334. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8335. const oldYieldPos = this.state.yieldPos;
  8336. const oldAwaitPos = this.state.awaitPos;
  8337. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8338. this.state.maybeInArrowParameters = true;
  8339. this.state.yieldPos = -1;
  8340. this.state.awaitPos = -1;
  8341. this.state.inFSharpPipelineDirectBody = false;
  8342. const innerStartPos = this.state.start;
  8343. const innerStartLoc = this.state.startLoc;
  8344. const exprList = [];
  8345. const refExpressionErrors = new ExpressionErrors();
  8346. const refNeedsArrowPos = {
  8347. start: 0
  8348. };
  8349. let first = true;
  8350. let spreadStart;
  8351. let optionalCommaStart;
  8352. while (!this.match(types.parenR)) {
  8353. if (first) {
  8354. first = false;
  8355. } else {
  8356. this.expect(types.comma, refNeedsArrowPos.start || null);
  8357. if (this.match(types.parenR)) {
  8358. optionalCommaStart = this.state.start;
  8359. break;
  8360. }
  8361. }
  8362. if (this.match(types.ellipsis)) {
  8363. const spreadNodeStartPos = this.state.start;
  8364. const spreadNodeStartLoc = this.state.startLoc;
  8365. spreadStart = this.state.start;
  8366. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  8367. this.checkCommaAfterRest(41);
  8368. break;
  8369. } else {
  8370. exprList.push(this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  8371. }
  8372. }
  8373. const innerEndPos = this.state.start;
  8374. const innerEndLoc = this.state.startLoc;
  8375. this.expect(types.parenR);
  8376. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8377. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8378. let arrowNode = this.startNodeAt(startPos, startLoc);
  8379. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  8380. if (!this.isAwaitAllowed() && !this.state.maybeInAsyncArrowHead) {
  8381. this.state.awaitPos = oldAwaitPos;
  8382. }
  8383. this.checkYieldAwaitInDefaultParams();
  8384. this.state.yieldPos = oldYieldPos;
  8385. this.state.awaitPos = oldAwaitPos;
  8386. for (let _i = 0; _i < exprList.length; _i++) {
  8387. const param = exprList[_i];
  8388. if (param.extra && param.extra.parenthesized) {
  8389. this.unexpected(param.extra.parenStart);
  8390. }
  8391. }
  8392. this.parseArrowExpression(arrowNode, exprList, false);
  8393. return arrowNode;
  8394. }
  8395. if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
  8396. if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
  8397. if (!exprList.length) {
  8398. this.unexpected(this.state.lastTokStart);
  8399. }
  8400. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  8401. if (spreadStart) this.unexpected(spreadStart);
  8402. this.checkExpressionErrors(refExpressionErrors, true);
  8403. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  8404. this.toReferencedListDeep(exprList, true);
  8405. if (exprList.length > 1) {
  8406. val = this.startNodeAt(innerStartPos, innerStartLoc);
  8407. val.expressions = exprList;
  8408. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  8409. } else {
  8410. val = exprList[0];
  8411. }
  8412. if (!this.options.createParenthesizedExpressions) {
  8413. this.addExtra(val, "parenthesized", true);
  8414. this.addExtra(val, "parenStart", startPos);
  8415. return val;
  8416. }
  8417. const parenExpression = this.startNodeAt(startPos, startLoc);
  8418. parenExpression.expression = val;
  8419. this.finishNode(parenExpression, "ParenthesizedExpression");
  8420. return parenExpression;
  8421. }
  8422. shouldParseArrow() {
  8423. return !this.canInsertSemicolon();
  8424. }
  8425. parseArrow(node) {
  8426. if (this.eat(types.arrow)) {
  8427. return node;
  8428. }
  8429. }
  8430. parseParenItem(node, startPos, startLoc) {
  8431. return node;
  8432. }
  8433. parseNew() {
  8434. const node = this.startNode();
  8435. let meta = this.startNode();
  8436. this.next();
  8437. meta = this.createIdentifier(meta, "new");
  8438. if (this.eat(types.dot)) {
  8439. const metaProp = this.parseMetaProperty(node, meta, "target");
  8440. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  8441. let error = Errors.UnexpectedNewTarget;
  8442. if (this.hasPlugin("classProperties")) {
  8443. error += " or class properties";
  8444. }
  8445. this.raise(metaProp.start, error);
  8446. }
  8447. return metaProp;
  8448. }
  8449. node.callee = this.parseNoCallExpr();
  8450. if (node.callee.type === "Import") {
  8451. this.raise(node.callee.start, Errors.ImportCallNotNewExpression);
  8452. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  8453. this.raise(this.state.lastTokEnd, Errors.OptionalChainingNoNew);
  8454. } else if (this.eat(types.questionDot)) {
  8455. this.raise(this.state.start, Errors.OptionalChainingNoNew);
  8456. }
  8457. this.parseNewArguments(node);
  8458. return this.finishNode(node, "NewExpression");
  8459. }
  8460. parseNewArguments(node) {
  8461. if (this.eat(types.parenL)) {
  8462. const args = this.parseExprList(types.parenR);
  8463. this.toReferencedList(args);
  8464. node.arguments = args;
  8465. } else {
  8466. node.arguments = [];
  8467. }
  8468. }
  8469. parseTemplateElement(isTagged) {
  8470. const elem = this.startNode();
  8471. if (this.state.value === null) {
  8472. if (!isTagged) {
  8473. this.raise(this.state.start + 1, Errors.InvalidEscapeSequenceTemplate);
  8474. }
  8475. }
  8476. elem.value = {
  8477. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  8478. cooked: this.state.value
  8479. };
  8480. this.next();
  8481. elem.tail = this.match(types.backQuote);
  8482. return this.finishNode(elem, "TemplateElement");
  8483. }
  8484. parseTemplate(isTagged) {
  8485. const node = this.startNode();
  8486. this.next();
  8487. node.expressions = [];
  8488. let curElt = this.parseTemplateElement(isTagged);
  8489. node.quasis = [curElt];
  8490. while (!curElt.tail) {
  8491. this.expect(types.dollarBraceL);
  8492. node.expressions.push(this.parseExpression());
  8493. this.expect(types.braceR);
  8494. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  8495. }
  8496. this.next();
  8497. return this.finishNode(node, "TemplateLiteral");
  8498. }
  8499. parseObj(close, isPattern, isRecord, refExpressionErrors) {
  8500. const propHash = Object.create(null);
  8501. let first = true;
  8502. const node = this.startNode();
  8503. node.properties = [];
  8504. this.next();
  8505. while (!this.eat(close)) {
  8506. if (first) {
  8507. first = false;
  8508. } else {
  8509. this.expect(types.comma);
  8510. if (this.match(close)) {
  8511. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  8512. this.next();
  8513. break;
  8514. }
  8515. }
  8516. const prop = this.parseObjectMember(isPattern, refExpressionErrors);
  8517. if (!isPattern) {
  8518. this.checkDuplicatedProto(prop, propHash, refExpressionErrors);
  8519. }
  8520. if (prop.shorthand) {
  8521. this.addExtra(prop, "shorthand", true);
  8522. }
  8523. node.properties.push(prop);
  8524. }
  8525. let type = "ObjectExpression";
  8526. if (isPattern) {
  8527. type = "ObjectPattern";
  8528. } else if (isRecord) {
  8529. type = "RecordExpression";
  8530. }
  8531. return this.finishNode(node, type);
  8532. }
  8533. isAsyncProp(prop) {
  8534. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.match(types.name) || this.match(types.num) || this.match(types.string) || this.match(types.bracketL) || this.state.type.keyword || this.match(types.star)) && !this.hasPrecedingLineBreak();
  8535. }
  8536. parseObjectMember(isPattern, refExpressionErrors) {
  8537. let decorators = [];
  8538. if (this.match(types.at)) {
  8539. if (this.hasPlugin("decorators")) {
  8540. this.raise(this.state.start, Errors.UnsupportedPropertyDecorator);
  8541. }
  8542. while (this.match(types.at)) {
  8543. decorators.push(this.parseDecorator());
  8544. }
  8545. }
  8546. const prop = this.startNode();
  8547. let isGenerator = false;
  8548. let isAsync = false;
  8549. let startPos;
  8550. let startLoc;
  8551. if (this.match(types.ellipsis)) {
  8552. if (decorators.length) this.unexpected();
  8553. if (isPattern) {
  8554. this.next();
  8555. prop.argument = this.parseIdentifier();
  8556. this.checkCommaAfterRest(125);
  8557. return this.finishNode(prop, "RestElement");
  8558. }
  8559. return this.parseSpread();
  8560. }
  8561. if (decorators.length) {
  8562. prop.decorators = decorators;
  8563. decorators = [];
  8564. }
  8565. prop.method = false;
  8566. if (isPattern || refExpressionErrors) {
  8567. startPos = this.state.start;
  8568. startLoc = this.state.startLoc;
  8569. }
  8570. if (!isPattern) {
  8571. isGenerator = this.eat(types.star);
  8572. }
  8573. const containsEsc = this.state.containsEsc;
  8574. this.parsePropertyName(prop, false);
  8575. if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) {
  8576. isAsync = true;
  8577. isGenerator = this.eat(types.star);
  8578. this.parsePropertyName(prop, false);
  8579. } else {
  8580. isAsync = false;
  8581. }
  8582. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc);
  8583. return prop;
  8584. }
  8585. isGetterOrSetterMethod(prop, isPattern) {
  8586. return !isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.match(types.string) || this.match(types.num) || this.match(types.bracketL) || this.match(types.name) || !!this.state.type.keyword);
  8587. }
  8588. getGetterSetterExpectedParamCount(method) {
  8589. return method.kind === "get" ? 0 : 1;
  8590. }
  8591. checkGetterSetterParams(method) {
  8592. const paramCount = this.getGetterSetterExpectedParamCount(method);
  8593. const start = method.start;
  8594. if (method.params.length !== paramCount) {
  8595. if (method.kind === "get") {
  8596. this.raise(start, Errors.BadGetterArity);
  8597. } else {
  8598. this.raise(start, Errors.BadSetterArity);
  8599. }
  8600. }
  8601. if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") {
  8602. this.raise(start, Errors.BadSetterRestParameter);
  8603. }
  8604. }
  8605. parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) {
  8606. if (isAsync || isGenerator || this.match(types.parenL)) {
  8607. if (isPattern) this.unexpected();
  8608. prop.kind = "method";
  8609. prop.method = true;
  8610. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  8611. }
  8612. if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) {
  8613. if (isGenerator || isAsync) this.unexpected();
  8614. prop.kind = prop.key.name;
  8615. this.parsePropertyName(prop, false);
  8616. this.parseMethod(prop, false, false, false, false, "ObjectMethod");
  8617. this.checkGetterSetterParams(prop);
  8618. return prop;
  8619. }
  8620. }
  8621. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  8622. prop.shorthand = false;
  8623. if (this.eat(types.colon)) {
  8624. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refExpressionErrors);
  8625. return this.finishNode(prop, "ObjectProperty");
  8626. }
  8627. if (!prop.computed && prop.key.type === "Identifier") {
  8628. this.checkReservedWord(prop.key.name, prop.key.start, true, true);
  8629. if (isPattern) {
  8630. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8631. } else if (this.match(types.eq) && refExpressionErrors) {
  8632. if (refExpressionErrors.shorthandAssign === -1) {
  8633. refExpressionErrors.shorthandAssign = this.state.start;
  8634. }
  8635. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  8636. } else {
  8637. prop.value = prop.key.__clone();
  8638. }
  8639. prop.shorthand = true;
  8640. return this.finishNode(prop, "ObjectProperty");
  8641. }
  8642. }
  8643. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refExpressionErrors, containsEsc) {
  8644. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  8645. if (!node) this.unexpected();
  8646. return node;
  8647. }
  8648. parsePropertyName(prop, isPrivateNameAllowed) {
  8649. if (this.eat(types.bracketL)) {
  8650. prop.computed = true;
  8651. prop.key = this.parseMaybeAssign();
  8652. this.expect(types.bracketR);
  8653. } else {
  8654. const oldInPropertyName = this.state.inPropertyName;
  8655. this.state.inPropertyName = true;
  8656. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  8657. if (prop.key.type !== "PrivateName") {
  8658. prop.computed = false;
  8659. }
  8660. this.state.inPropertyName = oldInPropertyName;
  8661. }
  8662. return prop.key;
  8663. }
  8664. initFunction(node, isAsync) {
  8665. node.id = null;
  8666. node.generator = false;
  8667. node.async = !!isAsync;
  8668. }
  8669. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  8670. const oldYieldPos = this.state.yieldPos;
  8671. const oldAwaitPos = this.state.awaitPos;
  8672. this.state.yieldPos = -1;
  8673. this.state.awaitPos = -1;
  8674. this.initFunction(node, isAsync);
  8675. node.generator = !!isGenerator;
  8676. const allowModifiers = isConstructor;
  8677. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  8678. this.prodParam.enter(functionFlags(isAsync, node.generator));
  8679. this.parseFunctionParams(node, allowModifiers);
  8680. this.parseFunctionBodyAndFinish(node, type, true);
  8681. this.prodParam.exit();
  8682. this.scope.exit();
  8683. this.state.yieldPos = oldYieldPos;
  8684. this.state.awaitPos = oldAwaitPos;
  8685. return node;
  8686. }
  8687. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  8688. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  8689. this.prodParam.enter(functionFlags(isAsync, false));
  8690. this.initFunction(node, isAsync);
  8691. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8692. const oldYieldPos = this.state.yieldPos;
  8693. const oldAwaitPos = this.state.awaitPos;
  8694. if (params) {
  8695. this.state.maybeInArrowParameters = true;
  8696. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  8697. }
  8698. this.state.maybeInArrowParameters = false;
  8699. this.state.yieldPos = -1;
  8700. this.state.awaitPos = -1;
  8701. this.parseFunctionBody(node, true);
  8702. this.prodParam.exit();
  8703. this.scope.exit();
  8704. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8705. this.state.yieldPos = oldYieldPos;
  8706. this.state.awaitPos = oldAwaitPos;
  8707. return this.finishNode(node, "ArrowFunctionExpression");
  8708. }
  8709. setArrowFunctionParameters(node, params, trailingCommaPos) {
  8710. node.params = this.toAssignableList(params, trailingCommaPos);
  8711. }
  8712. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8713. this.parseFunctionBody(node, false, isMethod);
  8714. this.finishNode(node, type);
  8715. }
  8716. parseFunctionBody(node, allowExpression, isMethod = false) {
  8717. const isExpression = allowExpression && !this.match(types.braceL);
  8718. const oldInParameters = this.state.inParameters;
  8719. this.state.inParameters = false;
  8720. if (isExpression) {
  8721. node.body = this.parseMaybeAssign();
  8722. this.checkParams(node, false, allowExpression, false);
  8723. } else {
  8724. const oldStrict = this.state.strict;
  8725. const oldLabels = this.state.labels;
  8726. this.state.labels = [];
  8727. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  8728. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  8729. const nonSimple = !this.isSimpleParamList(node.params);
  8730. if (hasStrictModeDirective && nonSimple) {
  8731. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  8732. this.raise(errorPos, Errors.IllegalLanguageModeDirective);
  8733. }
  8734. const strictModeChanged = !oldStrict && this.state.strict;
  8735. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  8736. if (this.state.strict && node.id) {
  8737. this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, strictModeChanged);
  8738. }
  8739. });
  8740. this.prodParam.exit();
  8741. this.state.labels = oldLabels;
  8742. }
  8743. this.state.inParameters = oldInParameters;
  8744. }
  8745. isSimpleParamList(params) {
  8746. for (let i = 0, len = params.length; i < len; i++) {
  8747. if (params[i].type !== "Identifier") return false;
  8748. }
  8749. return true;
  8750. }
  8751. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  8752. const nameHash = Object.create(null);
  8753. for (let i = 0; i < node.params.length; i++) {
  8754. this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged);
  8755. }
  8756. }
  8757. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  8758. const elts = [];
  8759. let first = true;
  8760. while (!this.eat(close)) {
  8761. if (first) {
  8762. first = false;
  8763. } else {
  8764. this.expect(types.comma);
  8765. if (this.match(close)) {
  8766. if (nodeForExtra) {
  8767. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8768. }
  8769. this.next();
  8770. break;
  8771. }
  8772. }
  8773. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  8774. }
  8775. return elts;
  8776. }
  8777. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  8778. let elt;
  8779. if (allowEmpty && this.match(types.comma)) {
  8780. elt = null;
  8781. } else if (this.match(types.ellipsis)) {
  8782. const spreadNodeStartPos = this.state.start;
  8783. const spreadNodeStartLoc = this.state.startLoc;
  8784. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  8785. } else if (this.match(types.question)) {
  8786. this.expectPlugin("partialApplication");
  8787. if (!allowPlaceholder) {
  8788. this.raise(this.state.start, Errors.UnexpectedArgumentPlaceholder);
  8789. }
  8790. const node = this.startNode();
  8791. this.next();
  8792. elt = this.finishNode(node, "ArgumentPlaceholder");
  8793. } else {
  8794. elt = this.parseMaybeAssign(false, refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  8795. }
  8796. return elt;
  8797. }
  8798. parseIdentifier(liberal) {
  8799. const node = this.startNode();
  8800. const name = this.parseIdentifierName(node.start, liberal);
  8801. return this.createIdentifier(node, name);
  8802. }
  8803. createIdentifier(node, name) {
  8804. node.name = name;
  8805. node.loc.identifierName = name;
  8806. return this.finishNode(node, "Identifier");
  8807. }
  8808. parseIdentifierName(pos, liberal) {
  8809. let name;
  8810. if (this.match(types.name)) {
  8811. name = this.state.value;
  8812. } else if (this.state.type.keyword) {
  8813. name = this.state.type.keyword;
  8814. const context = this.state.context;
  8815. if ((name === "class" || name === "function") && context[context.length - 1].token === "function") {
  8816. context.pop();
  8817. }
  8818. } else {
  8819. throw this.unexpected();
  8820. }
  8821. if (liberal) {
  8822. this.state.type = types.name;
  8823. } else {
  8824. this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false);
  8825. }
  8826. this.next();
  8827. return name;
  8828. }
  8829. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  8830. if (this.prodParam.hasYield && word === "yield") {
  8831. this.raise(startLoc, Errors.YieldBindingIdentifier);
  8832. return;
  8833. }
  8834. if (word === "await") {
  8835. if (this.prodParam.hasAwait) {
  8836. this.raise(startLoc, Errors.AwaitBindingIdentifier);
  8837. return;
  8838. }
  8839. if (this.state.awaitPos === -1 && (this.state.maybeInAsyncArrowHead || this.isAwaitAllowed())) {
  8840. this.state.awaitPos = this.state.start;
  8841. }
  8842. }
  8843. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  8844. this.raise(startLoc, Errors.ArgumentsDisallowedInInitializer);
  8845. return;
  8846. }
  8847. if (checkKeywords && isKeyword(word)) {
  8848. this.raise(startLoc, Errors.UnexpectedKeyword, word);
  8849. return;
  8850. }
  8851. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  8852. if (reservedTest(word, this.inModule)) {
  8853. if (!this.prodParam.hasAwait && word === "await") {
  8854. this.raise(startLoc, Errors.AwaitNotInAsyncFunction);
  8855. } else {
  8856. this.raise(startLoc, Errors.UnexpectedReservedWord, word);
  8857. }
  8858. }
  8859. }
  8860. isAwaitAllowed() {
  8861. if (this.scope.inFunction) return this.prodParam.hasAwait;
  8862. if (this.options.allowAwaitOutsideFunction) return true;
  8863. if (this.hasPlugin("topLevelAwait")) {
  8864. return this.inModule && this.prodParam.hasAwait;
  8865. }
  8866. return false;
  8867. }
  8868. parseAwait() {
  8869. const node = this.startNode();
  8870. this.next();
  8871. if (this.state.inParameters) {
  8872. this.raise(node.start, Errors.AwaitExpressionFormalParameter);
  8873. } else if (this.state.awaitPos === -1) {
  8874. this.state.awaitPos = node.start;
  8875. }
  8876. if (this.eat(types.star)) {
  8877. this.raise(node.start, Errors.ObsoleteAwaitStar);
  8878. }
  8879. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  8880. if (this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo)) {
  8881. this.ambiguousScriptDifferentAst = true;
  8882. } else {
  8883. this.sawUnambiguousESM = true;
  8884. }
  8885. }
  8886. if (!this.state.soloAwait) {
  8887. node.argument = this.parseMaybeUnary();
  8888. }
  8889. return this.finishNode(node, "AwaitExpression");
  8890. }
  8891. parseYield(noIn) {
  8892. const node = this.startNode();
  8893. if (this.state.inParameters) {
  8894. this.raise(node.start, Errors.YieldInParameter);
  8895. } else if (this.state.yieldPos === -1) {
  8896. this.state.yieldPos = node.start;
  8897. }
  8898. this.next();
  8899. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  8900. node.delegate = false;
  8901. node.argument = null;
  8902. } else {
  8903. node.delegate = this.eat(types.star);
  8904. node.argument = this.parseMaybeAssign(noIn);
  8905. }
  8906. return this.finishNode(node, "YieldExpression");
  8907. }
  8908. checkPipelineAtInfixOperator(left, leftStartPos) {
  8909. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  8910. if (left.type === "SequenceExpression") {
  8911. this.raise(leftStartPos, Errors.PipelineHeadSequenceExpression);
  8912. }
  8913. }
  8914. }
  8915. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  8916. const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
  8917. this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos);
  8918. return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc);
  8919. }
  8920. checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) {
  8921. if (this.match(types.arrow)) {
  8922. throw this.raise(this.state.start, Errors.PipelineBodyNoArrow);
  8923. } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") {
  8924. this.raise(startPos, Errors.PipelineBodySequenceExpression);
  8925. }
  8926. }
  8927. parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) {
  8928. const bodyNode = this.startNodeAt(startPos, startLoc);
  8929. switch (pipelineStyle) {
  8930. case "PipelineBareFunction":
  8931. bodyNode.callee = childExpression;
  8932. break;
  8933. case "PipelineBareConstructor":
  8934. bodyNode.callee = childExpression.callee;
  8935. break;
  8936. case "PipelineBareAwaitedFunction":
  8937. bodyNode.callee = childExpression.argument;
  8938. break;
  8939. case "PipelineTopicExpression":
  8940. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  8941. this.raise(startPos, Errors.PipelineTopicUnused);
  8942. }
  8943. bodyNode.expression = childExpression;
  8944. break;
  8945. default:
  8946. throw new Error(`Internal @babel/parser error: Unknown pipeline style (${pipelineStyle})`);
  8947. }
  8948. return this.finishNode(bodyNode, pipelineStyle);
  8949. }
  8950. checkSmartPipelineBodyStyle(expression) {
  8951. switch (expression.type) {
  8952. default:
  8953. return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression";
  8954. }
  8955. }
  8956. isSimpleReference(expression) {
  8957. switch (expression.type) {
  8958. case "MemberExpression":
  8959. return !expression.computed && this.isSimpleReference(expression.object);
  8960. case "Identifier":
  8961. return true;
  8962. default:
  8963. return false;
  8964. }
  8965. }
  8966. withTopicPermittingContext(callback) {
  8967. const outerContextTopicState = this.state.topicContext;
  8968. this.state.topicContext = {
  8969. maxNumOfResolvableTopics: 1,
  8970. maxTopicIndex: null
  8971. };
  8972. try {
  8973. return callback();
  8974. } finally {
  8975. this.state.topicContext = outerContextTopicState;
  8976. }
  8977. }
  8978. withTopicForbiddingContext(callback) {
  8979. const outerContextTopicState = this.state.topicContext;
  8980. this.state.topicContext = {
  8981. maxNumOfResolvableTopics: 0,
  8982. maxTopicIndex: null
  8983. };
  8984. try {
  8985. return callback();
  8986. } finally {
  8987. this.state.topicContext = outerContextTopicState;
  8988. }
  8989. }
  8990. withSoloAwaitPermittingContext(callback) {
  8991. const outerContextSoloAwaitState = this.state.soloAwait;
  8992. this.state.soloAwait = true;
  8993. try {
  8994. return callback();
  8995. } finally {
  8996. this.state.soloAwait = outerContextSoloAwaitState;
  8997. }
  8998. }
  8999. registerTopicReference() {
  9000. this.state.topicContext.maxTopicIndex = 0;
  9001. }
  9002. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  9003. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  9004. }
  9005. topicReferenceWasUsedInCurrentTopicContext() {
  9006. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  9007. }
  9008. parseFSharpPipelineBody(prec, noIn) {
  9009. const startPos = this.state.start;
  9010. const startLoc = this.state.startLoc;
  9011. this.state.potentialArrowAt = this.state.start;
  9012. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9013. this.state.inFSharpPipelineDirectBody = true;
  9014. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
  9015. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9016. return ret;
  9017. }
  9018. }
  9019. const loopLabel = {
  9020. kind: "loop"
  9021. },
  9022. switchLabel = {
  9023. kind: "switch"
  9024. };
  9025. const FUNC_NO_FLAGS = 0b000,
  9026. FUNC_STATEMENT = 0b001,
  9027. FUNC_HANGING_STATEMENT = 0b010,
  9028. FUNC_NULLABLE_ID = 0b100;
  9029. class StatementParser extends ExpressionParser {
  9030. parseTopLevel(file, program) {
  9031. program.sourceType = this.options.sourceType;
  9032. program.interpreter = this.parseInterpreterDirective();
  9033. this.parseBlockBody(program, true, true, types.eof);
  9034. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9035. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  9036. const [name] = _Array$from[_i];
  9037. const pos = this.scope.undefinedExports.get(name);
  9038. this.raise(pos, Errors.ModuleExportUndefined, name);
  9039. }
  9040. }
  9041. file.program = this.finishNode(program, "Program");
  9042. file.comments = this.state.comments;
  9043. if (this.options.tokens) file.tokens = this.tokens;
  9044. return this.finishNode(file, "File");
  9045. }
  9046. stmtToDirective(stmt) {
  9047. const expr = stmt.expression;
  9048. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9049. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9050. const raw = this.input.slice(expr.start, expr.end);
  9051. const val = directiveLiteral.value = raw.slice(1, -1);
  9052. this.addExtra(directiveLiteral, "raw", raw);
  9053. this.addExtra(directiveLiteral, "rawValue", val);
  9054. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9055. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9056. }
  9057. parseInterpreterDirective() {
  9058. if (!this.match(types.interpreterDirective)) {
  9059. return null;
  9060. }
  9061. const node = this.startNode();
  9062. node.value = this.state.value;
  9063. this.next();
  9064. return this.finishNode(node, "InterpreterDirective");
  9065. }
  9066. isLet(context) {
  9067. if (!this.isContextual("let")) {
  9068. return false;
  9069. }
  9070. const next = this.nextTokenStart();
  9071. const nextCh = this.input.charCodeAt(next);
  9072. if (nextCh === 91) return true;
  9073. if (context) return false;
  9074. if (nextCh === 123) return true;
  9075. if (isIdentifierStart(nextCh)) {
  9076. let pos = next + 1;
  9077. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9078. ++pos;
  9079. }
  9080. const ident = this.input.slice(next, pos);
  9081. if (!keywordRelationalOperator.test(ident)) return true;
  9082. }
  9083. return false;
  9084. }
  9085. parseStatement(context, topLevel) {
  9086. if (this.match(types.at)) {
  9087. this.parseDecorators(true);
  9088. }
  9089. return this.parseStatementContent(context, topLevel);
  9090. }
  9091. parseStatementContent(context, topLevel) {
  9092. let starttype = this.state.type;
  9093. const node = this.startNode();
  9094. let kind;
  9095. if (this.isLet(context)) {
  9096. starttype = types._var;
  9097. kind = "let";
  9098. }
  9099. switch (starttype) {
  9100. case types._break:
  9101. case types._continue:
  9102. return this.parseBreakContinueStatement(node, starttype.keyword);
  9103. case types._debugger:
  9104. return this.parseDebuggerStatement(node);
  9105. case types._do:
  9106. return this.parseDoStatement(node);
  9107. case types._for:
  9108. return this.parseForStatement(node);
  9109. case types._function:
  9110. if (this.lookaheadCharCode() === 46) break;
  9111. if (context) {
  9112. if (this.state.strict) {
  9113. this.raise(this.state.start, Errors.StrictFunction);
  9114. } else if (context !== "if" && context !== "label") {
  9115. this.raise(this.state.start, Errors.SloppyFunction);
  9116. }
  9117. }
  9118. return this.parseFunctionStatement(node, false, !context);
  9119. case types._class:
  9120. if (context) this.unexpected();
  9121. return this.parseClass(node, true);
  9122. case types._if:
  9123. return this.parseIfStatement(node);
  9124. case types._return:
  9125. return this.parseReturnStatement(node);
  9126. case types._switch:
  9127. return this.parseSwitchStatement(node);
  9128. case types._throw:
  9129. return this.parseThrowStatement(node);
  9130. case types._try:
  9131. return this.parseTryStatement(node);
  9132. case types._const:
  9133. case types._var:
  9134. kind = kind || this.state.value;
  9135. if (context && kind !== "var") {
  9136. this.raise(this.state.start, Errors.UnexpectedLexicalDeclaration);
  9137. }
  9138. return this.parseVarStatement(node, kind);
  9139. case types._while:
  9140. return this.parseWhileStatement(node);
  9141. case types._with:
  9142. return this.parseWithStatement(node);
  9143. case types.braceL:
  9144. return this.parseBlock();
  9145. case types.semi:
  9146. return this.parseEmptyStatement(node);
  9147. case types._export:
  9148. case types._import:
  9149. {
  9150. const nextTokenCharCode = this.lookaheadCharCode();
  9151. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  9152. break;
  9153. }
  9154. if (!this.options.allowImportExportEverywhere && !topLevel) {
  9155. this.raise(this.state.start, Errors.UnexpectedImportExport);
  9156. }
  9157. this.next();
  9158. let result;
  9159. if (starttype === types._import) {
  9160. result = this.parseImport(node);
  9161. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  9162. this.sawUnambiguousESM = true;
  9163. }
  9164. } else {
  9165. result = this.parseExport(node);
  9166. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  9167. this.sawUnambiguousESM = true;
  9168. }
  9169. }
  9170. this.assertModuleNodeAllowed(node);
  9171. return result;
  9172. }
  9173. default:
  9174. {
  9175. if (this.isAsyncFunction()) {
  9176. if (context) {
  9177. this.raise(this.state.start, Errors.AsyncFunctionInSingleStatementContext);
  9178. }
  9179. this.next();
  9180. return this.parseFunctionStatement(node, true, !context);
  9181. }
  9182. }
  9183. }
  9184. const maybeName = this.state.value;
  9185. const expr = this.parseExpression();
  9186. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  9187. return this.parseLabeledStatement(node, maybeName, expr, context);
  9188. } else {
  9189. return this.parseExpressionStatement(node, expr);
  9190. }
  9191. }
  9192. assertModuleNodeAllowed(node) {
  9193. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  9194. this.raiseWithData(node.start, {
  9195. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9196. }, Errors.ImportOutsideModule);
  9197. }
  9198. }
  9199. takeDecorators(node) {
  9200. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9201. if (decorators.length) {
  9202. node.decorators = decorators;
  9203. this.resetStartLocationFromNode(node, decorators[0]);
  9204. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  9205. }
  9206. }
  9207. canHaveLeadingDecorator() {
  9208. return this.match(types._class);
  9209. }
  9210. parseDecorators(allowExport) {
  9211. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  9212. while (this.match(types.at)) {
  9213. const decorator = this.parseDecorator();
  9214. currentContextDecorators.push(decorator);
  9215. }
  9216. if (this.match(types._export)) {
  9217. if (!allowExport) {
  9218. this.unexpected();
  9219. }
  9220. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  9221. this.raise(this.state.start, Errors.DecoratorExportClass);
  9222. }
  9223. } else if (!this.canHaveLeadingDecorator()) {
  9224. throw this.raise(this.state.start, Errors.UnexpectedLeadingDecorator);
  9225. }
  9226. }
  9227. parseDecorator() {
  9228. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  9229. const node = this.startNode();
  9230. this.next();
  9231. if (this.hasPlugin("decorators")) {
  9232. this.state.decoratorStack.push([]);
  9233. const startPos = this.state.start;
  9234. const startLoc = this.state.startLoc;
  9235. let expr;
  9236. if (this.eat(types.parenL)) {
  9237. expr = this.parseExpression();
  9238. this.expect(types.parenR);
  9239. } else {
  9240. expr = this.parseIdentifier(false);
  9241. while (this.eat(types.dot)) {
  9242. const node = this.startNodeAt(startPos, startLoc);
  9243. node.object = expr;
  9244. node.property = this.parseIdentifier(true);
  9245. node.computed = false;
  9246. expr = this.finishNode(node, "MemberExpression");
  9247. }
  9248. }
  9249. node.expression = this.parseMaybeDecoratorArguments(expr);
  9250. this.state.decoratorStack.pop();
  9251. } else {
  9252. node.expression = this.parseExprSubscripts();
  9253. }
  9254. return this.finishNode(node, "Decorator");
  9255. }
  9256. parseMaybeDecoratorArguments(expr) {
  9257. if (this.eat(types.parenL)) {
  9258. const node = this.startNodeAtNode(expr);
  9259. node.callee = expr;
  9260. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  9261. this.toReferencedList(node.arguments);
  9262. return this.finishNode(node, "CallExpression");
  9263. }
  9264. return expr;
  9265. }
  9266. parseBreakContinueStatement(node, keyword) {
  9267. const isBreak = keyword === "break";
  9268. this.next();
  9269. if (this.isLineTerminator()) {
  9270. node.label = null;
  9271. } else {
  9272. node.label = this.parseIdentifier();
  9273. this.semicolon();
  9274. }
  9275. this.verifyBreakContinue(node, keyword);
  9276. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  9277. }
  9278. verifyBreakContinue(node, keyword) {
  9279. const isBreak = keyword === "break";
  9280. let i;
  9281. for (i = 0; i < this.state.labels.length; ++i) {
  9282. const lab = this.state.labels[i];
  9283. if (node.label == null || lab.name === node.label.name) {
  9284. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  9285. if (node.label && isBreak) break;
  9286. }
  9287. }
  9288. if (i === this.state.labels.length) {
  9289. this.raise(node.start, Errors.IllegalBreakContinue, keyword);
  9290. }
  9291. }
  9292. parseDebuggerStatement(node) {
  9293. this.next();
  9294. this.semicolon();
  9295. return this.finishNode(node, "DebuggerStatement");
  9296. }
  9297. parseHeaderExpression() {
  9298. this.expect(types.parenL);
  9299. const val = this.parseExpression();
  9300. this.expect(types.parenR);
  9301. return val;
  9302. }
  9303. parseDoStatement(node) {
  9304. this.next();
  9305. this.state.labels.push(loopLabel);
  9306. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  9307. this.state.labels.pop();
  9308. this.expect(types._while);
  9309. node.test = this.parseHeaderExpression();
  9310. this.eat(types.semi);
  9311. return this.finishNode(node, "DoWhileStatement");
  9312. }
  9313. parseForStatement(node) {
  9314. this.next();
  9315. this.state.labels.push(loopLabel);
  9316. let awaitAt = -1;
  9317. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  9318. awaitAt = this.state.lastTokStart;
  9319. }
  9320. this.scope.enter(SCOPE_OTHER);
  9321. this.expect(types.parenL);
  9322. if (this.match(types.semi)) {
  9323. if (awaitAt > -1) {
  9324. this.unexpected(awaitAt);
  9325. }
  9326. return this.parseFor(node, null);
  9327. }
  9328. const isLet = this.isLet();
  9329. if (this.match(types._var) || this.match(types._const) || isLet) {
  9330. const init = this.startNode();
  9331. const kind = isLet ? "let" : this.state.value;
  9332. this.next();
  9333. this.parseVar(init, true, kind);
  9334. this.finishNode(init, "VariableDeclaration");
  9335. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  9336. return this.parseForIn(node, init, awaitAt);
  9337. }
  9338. if (awaitAt > -1) {
  9339. this.unexpected(awaitAt);
  9340. }
  9341. return this.parseFor(node, init);
  9342. }
  9343. const refExpressionErrors = new ExpressionErrors();
  9344. const init = this.parseExpression(true, refExpressionErrors);
  9345. if (this.match(types._in) || this.isContextual("of")) {
  9346. this.toAssignable(init);
  9347. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  9348. this.checkLVal(init, undefined, undefined, description);
  9349. return this.parseForIn(node, init, awaitAt);
  9350. } else {
  9351. this.checkExpressionErrors(refExpressionErrors, true);
  9352. }
  9353. if (awaitAt > -1) {
  9354. this.unexpected(awaitAt);
  9355. }
  9356. return this.parseFor(node, init);
  9357. }
  9358. parseFunctionStatement(node, isAsync, declarationPosition) {
  9359. this.next();
  9360. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  9361. }
  9362. parseIfStatement(node) {
  9363. this.next();
  9364. node.test = this.parseHeaderExpression();
  9365. node.consequent = this.parseStatement("if");
  9366. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  9367. return this.finishNode(node, "IfStatement");
  9368. }
  9369. parseReturnStatement(node) {
  9370. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  9371. this.raise(this.state.start, Errors.IllegalReturn);
  9372. }
  9373. this.next();
  9374. if (this.isLineTerminator()) {
  9375. node.argument = null;
  9376. } else {
  9377. node.argument = this.parseExpression();
  9378. this.semicolon();
  9379. }
  9380. return this.finishNode(node, "ReturnStatement");
  9381. }
  9382. parseSwitchStatement(node) {
  9383. this.next();
  9384. node.discriminant = this.parseHeaderExpression();
  9385. const cases = node.cases = [];
  9386. this.expect(types.braceL);
  9387. this.state.labels.push(switchLabel);
  9388. this.scope.enter(SCOPE_OTHER);
  9389. let cur;
  9390. for (let sawDefault; !this.match(types.braceR);) {
  9391. if (this.match(types._case) || this.match(types._default)) {
  9392. const isCase = this.match(types._case);
  9393. if (cur) this.finishNode(cur, "SwitchCase");
  9394. cases.push(cur = this.startNode());
  9395. cur.consequent = [];
  9396. this.next();
  9397. if (isCase) {
  9398. cur.test = this.parseExpression();
  9399. } else {
  9400. if (sawDefault) {
  9401. this.raise(this.state.lastTokStart, Errors.MultipleDefaultsInSwitch);
  9402. }
  9403. sawDefault = true;
  9404. cur.test = null;
  9405. }
  9406. this.expect(types.colon);
  9407. } else {
  9408. if (cur) {
  9409. cur.consequent.push(this.parseStatement(null));
  9410. } else {
  9411. this.unexpected();
  9412. }
  9413. }
  9414. }
  9415. this.scope.exit();
  9416. if (cur) this.finishNode(cur, "SwitchCase");
  9417. this.next();
  9418. this.state.labels.pop();
  9419. return this.finishNode(node, "SwitchStatement");
  9420. }
  9421. parseThrowStatement(node) {
  9422. this.next();
  9423. if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) {
  9424. this.raise(this.state.lastTokEnd, Errors.NewlineAfterThrow);
  9425. }
  9426. node.argument = this.parseExpression();
  9427. this.semicolon();
  9428. return this.finishNode(node, "ThrowStatement");
  9429. }
  9430. parseTryStatement(node) {
  9431. this.next();
  9432. node.block = this.parseBlock();
  9433. node.handler = null;
  9434. if (this.match(types._catch)) {
  9435. const clause = this.startNode();
  9436. this.next();
  9437. if (this.match(types.parenL)) {
  9438. this.expect(types.parenL);
  9439. clause.param = this.parseBindingAtom();
  9440. const simple = clause.param.type === "Identifier";
  9441. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  9442. this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause");
  9443. this.expect(types.parenR);
  9444. } else {
  9445. clause.param = null;
  9446. this.scope.enter(SCOPE_OTHER);
  9447. }
  9448. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  9449. this.scope.exit();
  9450. node.handler = this.finishNode(clause, "CatchClause");
  9451. }
  9452. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  9453. if (!node.handler && !node.finalizer) {
  9454. this.raise(node.start, Errors.NoCatchOrFinally);
  9455. }
  9456. return this.finishNode(node, "TryStatement");
  9457. }
  9458. parseVarStatement(node, kind) {
  9459. this.next();
  9460. this.parseVar(node, false, kind);
  9461. this.semicolon();
  9462. return this.finishNode(node, "VariableDeclaration");
  9463. }
  9464. parseWhileStatement(node) {
  9465. this.next();
  9466. node.test = this.parseHeaderExpression();
  9467. this.state.labels.push(loopLabel);
  9468. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  9469. this.state.labels.pop();
  9470. return this.finishNode(node, "WhileStatement");
  9471. }
  9472. parseWithStatement(node) {
  9473. if (this.state.strict) {
  9474. this.raise(this.state.start, Errors.StrictWith);
  9475. }
  9476. this.next();
  9477. node.object = this.parseHeaderExpression();
  9478. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  9479. return this.finishNode(node, "WithStatement");
  9480. }
  9481. parseEmptyStatement(node) {
  9482. this.next();
  9483. return this.finishNode(node, "EmptyStatement");
  9484. }
  9485. parseLabeledStatement(node, maybeName, expr, context) {
  9486. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  9487. const label = _this$state$labels[_i2];
  9488. if (label.name === maybeName) {
  9489. this.raise(expr.start, Errors.LabelRedeclaration, maybeName);
  9490. }
  9491. }
  9492. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  9493. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  9494. const label = this.state.labels[i];
  9495. if (label.statementStart === node.start) {
  9496. label.statementStart = this.state.start;
  9497. label.kind = kind;
  9498. } else {
  9499. break;
  9500. }
  9501. }
  9502. this.state.labels.push({
  9503. name: maybeName,
  9504. kind: kind,
  9505. statementStart: this.state.start
  9506. });
  9507. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  9508. this.state.labels.pop();
  9509. node.label = expr;
  9510. return this.finishNode(node, "LabeledStatement");
  9511. }
  9512. parseExpressionStatement(node, expr) {
  9513. node.expression = expr;
  9514. this.semicolon();
  9515. return this.finishNode(node, "ExpressionStatement");
  9516. }
  9517. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  9518. const node = this.startNode();
  9519. this.expect(types.braceL);
  9520. if (createNewLexicalScope) {
  9521. this.scope.enter(SCOPE_OTHER);
  9522. }
  9523. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  9524. if (createNewLexicalScope) {
  9525. this.scope.exit();
  9526. }
  9527. return this.finishNode(node, "BlockStatement");
  9528. }
  9529. isValidDirective(stmt) {
  9530. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  9531. }
  9532. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  9533. const body = node.body = [];
  9534. const directives = node.directives = [];
  9535. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  9536. }
  9537. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  9538. const octalPositions = [];
  9539. const oldStrict = this.state.strict;
  9540. let hasStrictModeDirective = false;
  9541. let parsedNonDirective = false;
  9542. while (!this.match(end)) {
  9543. if (!parsedNonDirective && this.state.octalPositions.length) {
  9544. octalPositions.push(...this.state.octalPositions);
  9545. }
  9546. const stmt = this.parseStatement(null, topLevel);
  9547. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  9548. const directive = this.stmtToDirective(stmt);
  9549. directives.push(directive);
  9550. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  9551. hasStrictModeDirective = true;
  9552. this.setStrict(true);
  9553. }
  9554. continue;
  9555. }
  9556. parsedNonDirective = true;
  9557. body.push(stmt);
  9558. }
  9559. if (this.state.strict && octalPositions.length) {
  9560. for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
  9561. const pos = octalPositions[_i3];
  9562. this.raise(pos, Errors.StrictOctalLiteral);
  9563. }
  9564. }
  9565. if (afterBlockParse) {
  9566. afterBlockParse.call(this, hasStrictModeDirective);
  9567. }
  9568. if (!oldStrict) {
  9569. this.setStrict(false);
  9570. }
  9571. this.next();
  9572. }
  9573. parseFor(node, init) {
  9574. node.init = init;
  9575. this.expect(types.semi);
  9576. node.test = this.match(types.semi) ? null : this.parseExpression();
  9577. this.expect(types.semi);
  9578. node.update = this.match(types.parenR) ? null : this.parseExpression();
  9579. this.expect(types.parenR);
  9580. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9581. this.scope.exit();
  9582. this.state.labels.pop();
  9583. return this.finishNode(node, "ForStatement");
  9584. }
  9585. parseForIn(node, init, awaitAt) {
  9586. const isForIn = this.match(types._in);
  9587. this.next();
  9588. if (isForIn) {
  9589. if (awaitAt > -1) this.unexpected(awaitAt);
  9590. } else {
  9591. node.await = awaitAt > -1;
  9592. }
  9593. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  9594. this.raise(init.start, Errors.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  9595. } else if (init.type === "AssignmentPattern") {
  9596. this.raise(init.start, Errors.InvalidLhs, "for-loop");
  9597. }
  9598. node.left = init;
  9599. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  9600. this.expect(types.parenR);
  9601. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  9602. this.scope.exit();
  9603. this.state.labels.pop();
  9604. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  9605. }
  9606. parseVar(node, isFor, kind) {
  9607. const declarations = node.declarations = [];
  9608. const isTypescript = this.hasPlugin("typescript");
  9609. node.kind = kind;
  9610. for (;;) {
  9611. const decl = this.startNode();
  9612. this.parseVarId(decl, kind);
  9613. if (this.eat(types.eq)) {
  9614. decl.init = this.parseMaybeAssign(isFor);
  9615. } else {
  9616. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  9617. if (!isTypescript) {
  9618. this.unexpected();
  9619. }
  9620. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  9621. this.raise(this.state.lastTokEnd, Errors.DeclarationMissingInitializer, "Complex binding patterns");
  9622. }
  9623. decl.init = null;
  9624. }
  9625. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  9626. if (!this.eat(types.comma)) break;
  9627. }
  9628. return node;
  9629. }
  9630. parseVarId(decl, kind) {
  9631. decl.id = this.parseBindingAtom();
  9632. this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var");
  9633. }
  9634. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  9635. const isStatement = statement & FUNC_STATEMENT;
  9636. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  9637. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  9638. this.initFunction(node, isAsync);
  9639. if (this.match(types.star) && isHangingStatement) {
  9640. this.raise(this.state.start, Errors.GeneratorInSingleStatementContext);
  9641. }
  9642. node.generator = this.eat(types.star);
  9643. if (isStatement) {
  9644. node.id = this.parseFunctionId(requireId);
  9645. }
  9646. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9647. const oldYieldPos = this.state.yieldPos;
  9648. const oldAwaitPos = this.state.awaitPos;
  9649. this.state.maybeInArrowParameters = false;
  9650. this.state.yieldPos = -1;
  9651. this.state.awaitPos = -1;
  9652. this.scope.enter(SCOPE_FUNCTION);
  9653. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9654. if (!isStatement) {
  9655. node.id = this.parseFunctionId();
  9656. }
  9657. this.parseFunctionParams(node);
  9658. this.withTopicForbiddingContext(() => {
  9659. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  9660. });
  9661. this.prodParam.exit();
  9662. this.scope.exit();
  9663. if (isStatement && !isHangingStatement) {
  9664. this.registerFunctionStatementId(node);
  9665. }
  9666. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9667. this.state.yieldPos = oldYieldPos;
  9668. this.state.awaitPos = oldAwaitPos;
  9669. return node;
  9670. }
  9671. parseFunctionId(requireId) {
  9672. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  9673. }
  9674. parseFunctionParams(node, allowModifiers) {
  9675. const oldInParameters = this.state.inParameters;
  9676. this.state.inParameters = true;
  9677. this.expect(types.parenL);
  9678. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  9679. this.state.inParameters = oldInParameters;
  9680. this.checkYieldAwaitInDefaultParams();
  9681. }
  9682. registerFunctionStatementId(node) {
  9683. if (!node.id) return;
  9684. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start);
  9685. }
  9686. parseClass(node, isStatement, optionalId) {
  9687. this.next();
  9688. this.takeDecorators(node);
  9689. const oldStrict = this.state.strict;
  9690. this.state.strict = true;
  9691. this.parseClassId(node, isStatement, optionalId);
  9692. this.parseClassSuper(node);
  9693. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  9694. this.state.strict = oldStrict;
  9695. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  9696. }
  9697. isClassProperty() {
  9698. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  9699. }
  9700. isClassMethod() {
  9701. return this.match(types.parenL);
  9702. }
  9703. isNonstaticConstructor(method) {
  9704. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  9705. }
  9706. parseClassBody(constructorAllowsSuper, oldStrict) {
  9707. this.classScope.enter();
  9708. const state = {
  9709. hadConstructor: false
  9710. };
  9711. let decorators = [];
  9712. const classBody = this.startNode();
  9713. classBody.body = [];
  9714. this.expect(types.braceL);
  9715. this.withTopicForbiddingContext(() => {
  9716. while (!this.match(types.braceR)) {
  9717. if (this.eat(types.semi)) {
  9718. if (decorators.length > 0) {
  9719. throw this.raise(this.state.lastTokEnd, Errors.DecoratorSemicolon);
  9720. }
  9721. continue;
  9722. }
  9723. if (this.match(types.at)) {
  9724. decorators.push(this.parseDecorator());
  9725. continue;
  9726. }
  9727. const member = this.startNode();
  9728. if (decorators.length) {
  9729. member.decorators = decorators;
  9730. this.resetStartLocationFromNode(member, decorators[0]);
  9731. decorators = [];
  9732. }
  9733. this.parseClassMember(classBody, member, state, constructorAllowsSuper);
  9734. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  9735. this.raise(member.start, Errors.DecoratorConstructor);
  9736. }
  9737. }
  9738. });
  9739. if (!oldStrict) {
  9740. this.state.strict = false;
  9741. }
  9742. this.next();
  9743. if (decorators.length) {
  9744. throw this.raise(this.state.start, Errors.TrailingDecorator);
  9745. }
  9746. this.classScope.exit();
  9747. return this.finishNode(classBody, "ClassBody");
  9748. }
  9749. parseClassMemberFromModifier(classBody, member) {
  9750. const containsEsc = this.state.containsEsc;
  9751. const key = this.parseIdentifier(true);
  9752. if (this.isClassMethod()) {
  9753. const method = member;
  9754. method.kind = "method";
  9755. method.computed = false;
  9756. method.key = key;
  9757. method.static = false;
  9758. this.pushClassMethod(classBody, method, false, false, false, false);
  9759. return true;
  9760. } else if (this.isClassProperty()) {
  9761. const prop = member;
  9762. prop.computed = false;
  9763. prop.key = key;
  9764. prop.static = false;
  9765. classBody.body.push(this.parseClassProperty(prop));
  9766. return true;
  9767. } else if (containsEsc) {
  9768. throw this.unexpected();
  9769. }
  9770. return false;
  9771. }
  9772. parseClassMember(classBody, member, state, constructorAllowsSuper) {
  9773. const isStatic = this.isContextual("static");
  9774. if (isStatic && this.parseClassMemberFromModifier(classBody, member)) {
  9775. return;
  9776. }
  9777. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper);
  9778. }
  9779. parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) {
  9780. const publicMethod = member;
  9781. const privateMethod = member;
  9782. const publicProp = member;
  9783. const privateProp = member;
  9784. const method = publicMethod;
  9785. const publicMember = publicMethod;
  9786. member.static = isStatic;
  9787. if (this.eat(types.star)) {
  9788. method.kind = "method";
  9789. this.parseClassPropertyName(method);
  9790. if (method.key.type === "PrivateName") {
  9791. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  9792. return;
  9793. }
  9794. if (this.isNonstaticConstructor(publicMethod)) {
  9795. this.raise(publicMethod.key.start, Errors.ConstructorIsGenerator);
  9796. }
  9797. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  9798. return;
  9799. }
  9800. const containsEsc = this.state.containsEsc;
  9801. const key = this.parseClassPropertyName(member);
  9802. const isPrivate = key.type === "PrivateName";
  9803. const isSimple = key.type === "Identifier";
  9804. const maybeQuestionTokenStart = this.state.start;
  9805. this.parsePostMemberNameModifiers(publicMember);
  9806. if (this.isClassMethod()) {
  9807. method.kind = "method";
  9808. if (isPrivate) {
  9809. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9810. return;
  9811. }
  9812. const isConstructor = this.isNonstaticConstructor(publicMethod);
  9813. let allowsDirectSuper = false;
  9814. if (isConstructor) {
  9815. publicMethod.kind = "constructor";
  9816. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  9817. this.raise(key.start, Errors.DuplicateConstructor);
  9818. }
  9819. state.hadConstructor = true;
  9820. allowsDirectSuper = constructorAllowsSuper;
  9821. }
  9822. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  9823. } else if (this.isClassProperty()) {
  9824. if (isPrivate) {
  9825. this.pushClassPrivateProperty(classBody, privateProp);
  9826. } else {
  9827. this.pushClassProperty(classBody, publicProp);
  9828. }
  9829. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  9830. const isGenerator = this.eat(types.star);
  9831. if (publicMember.optional) {
  9832. this.unexpected(maybeQuestionTokenStart);
  9833. }
  9834. method.kind = "method";
  9835. this.parseClassPropertyName(method);
  9836. this.parsePostMemberNameModifiers(publicMember);
  9837. if (method.key.type === "PrivateName") {
  9838. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  9839. } else {
  9840. if (this.isNonstaticConstructor(publicMethod)) {
  9841. this.raise(publicMethod.key.start, Errors.ConstructorIsAsync);
  9842. }
  9843. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  9844. }
  9845. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  9846. method.kind = key.name;
  9847. this.parseClassPropertyName(publicMethod);
  9848. if (method.key.type === "PrivateName") {
  9849. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  9850. } else {
  9851. if (this.isNonstaticConstructor(publicMethod)) {
  9852. this.raise(publicMethod.key.start, Errors.ConstructorIsAccessor);
  9853. }
  9854. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  9855. }
  9856. this.checkGetterSetterParams(publicMethod);
  9857. } else if (this.isLineTerminator()) {
  9858. if (isPrivate) {
  9859. this.pushClassPrivateProperty(classBody, privateProp);
  9860. } else {
  9861. this.pushClassProperty(classBody, publicProp);
  9862. }
  9863. } else {
  9864. this.unexpected();
  9865. }
  9866. }
  9867. parseClassPropertyName(member) {
  9868. const key = this.parsePropertyName(member, true);
  9869. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  9870. this.raise(key.start, Errors.StaticPrototype);
  9871. }
  9872. if (key.type === "PrivateName" && key.id.name === "constructor") {
  9873. this.raise(key.start, Errors.ConstructorClassPrivateField);
  9874. }
  9875. return key;
  9876. }
  9877. pushClassProperty(classBody, prop) {
  9878. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  9879. this.raise(prop.key.start, Errors.ConstructorClassField);
  9880. }
  9881. classBody.body.push(this.parseClassProperty(prop));
  9882. }
  9883. pushClassPrivateProperty(classBody, prop) {
  9884. this.expectPlugin("classPrivateProperties", prop.key.start);
  9885. const node = this.parseClassPrivateProperty(prop);
  9886. classBody.body.push(node);
  9887. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  9888. }
  9889. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  9890. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  9891. }
  9892. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  9893. this.expectPlugin("classPrivateMethods", method.key.start);
  9894. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  9895. classBody.body.push(node);
  9896. const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER;
  9897. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  9898. }
  9899. parsePostMemberNameModifiers(methodOrProp) {}
  9900. parseAccessModifier() {
  9901. return undefined;
  9902. }
  9903. parseClassPrivateProperty(node) {
  9904. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9905. this.prodParam.enter(PARAM);
  9906. node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null;
  9907. this.semicolon();
  9908. this.prodParam.exit();
  9909. this.scope.exit();
  9910. return this.finishNode(node, "ClassPrivateProperty");
  9911. }
  9912. parseClassProperty(node) {
  9913. if (!node.typeAnnotation) {
  9914. this.expectPlugin("classProperties");
  9915. }
  9916. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  9917. this.prodParam.enter(PARAM);
  9918. if (this.match(types.eq)) {
  9919. this.expectPlugin("classProperties");
  9920. this.next();
  9921. node.value = this.parseMaybeAssign();
  9922. } else {
  9923. node.value = null;
  9924. }
  9925. this.semicolon();
  9926. this.prodParam.exit();
  9927. this.scope.exit();
  9928. return this.finishNode(node, "ClassProperty");
  9929. }
  9930. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  9931. if (this.match(types.name)) {
  9932. node.id = this.parseIdentifier();
  9933. if (isStatement) {
  9934. this.checkLVal(node.id, bindingType, undefined, "class name");
  9935. }
  9936. } else {
  9937. if (optionalId || !isStatement) {
  9938. node.id = null;
  9939. } else {
  9940. this.unexpected(null, Errors.MissingClassName);
  9941. }
  9942. }
  9943. }
  9944. parseClassSuper(node) {
  9945. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  9946. }
  9947. parseExport(node) {
  9948. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  9949. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  9950. const hasStar = parseAfterDefault && this.eatExportStar(node);
  9951. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  9952. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  9953. const isFromRequired = hasDefault || hasStar;
  9954. if (hasStar && !hasNamespace) {
  9955. if (hasDefault) this.unexpected();
  9956. this.parseExportFrom(node, true);
  9957. return this.finishNode(node, "ExportAllDeclaration");
  9958. }
  9959. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  9960. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  9961. throw this.unexpected(null, types.braceL);
  9962. }
  9963. let hasDeclaration;
  9964. if (isFromRequired || hasSpecifiers) {
  9965. hasDeclaration = false;
  9966. this.parseExportFrom(node, isFromRequired);
  9967. } else {
  9968. hasDeclaration = this.maybeParseExportDeclaration(node);
  9969. }
  9970. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  9971. this.checkExport(node, true, false, !!node.source);
  9972. return this.finishNode(node, "ExportNamedDeclaration");
  9973. }
  9974. if (this.eat(types._default)) {
  9975. node.declaration = this.parseExportDefaultExpression();
  9976. this.checkExport(node, true, true);
  9977. return this.finishNode(node, "ExportDefaultDeclaration");
  9978. }
  9979. throw this.unexpected(null, types.braceL);
  9980. }
  9981. eatExportStar(node) {
  9982. return this.eat(types.star);
  9983. }
  9984. maybeParseExportDefaultSpecifier(node) {
  9985. if (this.isExportDefaultSpecifier()) {
  9986. this.expectPlugin("exportDefaultFrom");
  9987. const specifier = this.startNode();
  9988. specifier.exported = this.parseIdentifier(true);
  9989. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9990. return true;
  9991. }
  9992. return false;
  9993. }
  9994. maybeParseExportNamespaceSpecifier(node) {
  9995. if (this.isContextual("as")) {
  9996. if (!node.specifiers) node.specifiers = [];
  9997. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  9998. this.next();
  9999. specifier.exported = this.parseIdentifier(true);
  10000. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  10001. return true;
  10002. }
  10003. return false;
  10004. }
  10005. maybeParseExportNamedSpecifiers(node) {
  10006. if (this.match(types.braceL)) {
  10007. if (!node.specifiers) node.specifiers = [];
  10008. node.specifiers.push(...this.parseExportSpecifiers());
  10009. node.source = null;
  10010. node.declaration = null;
  10011. return true;
  10012. }
  10013. return false;
  10014. }
  10015. maybeParseExportDeclaration(node) {
  10016. if (this.shouldParseExportDeclaration()) {
  10017. if (this.isContextual("async")) {
  10018. const next = this.nextTokenStart();
  10019. if (!this.isUnparsedContextual(next, "function")) {
  10020. this.unexpected(next, types._function);
  10021. }
  10022. }
  10023. node.specifiers = [];
  10024. node.source = null;
  10025. node.declaration = this.parseExportDeclaration(node);
  10026. return true;
  10027. }
  10028. return false;
  10029. }
  10030. isAsyncFunction() {
  10031. if (!this.isContextual("async")) return false;
  10032. const next = this.nextTokenStart();
  10033. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10034. }
  10035. parseExportDefaultExpression() {
  10036. const expr = this.startNode();
  10037. const isAsync = this.isAsyncFunction();
  10038. if (this.match(types._function) || isAsync) {
  10039. this.next();
  10040. if (isAsync) {
  10041. this.next();
  10042. }
  10043. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10044. } else if (this.match(types._class)) {
  10045. return this.parseClass(expr, true, true);
  10046. } else if (this.match(types.at)) {
  10047. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10048. this.raise(this.state.start, Errors.DecoratorBeforeExport);
  10049. }
  10050. this.parseDecorators(false);
  10051. return this.parseClass(expr, true, true);
  10052. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10053. throw this.raise(this.state.start, Errors.UnsupportedDefaultExport);
  10054. } else {
  10055. const res = this.parseMaybeAssign();
  10056. this.semicolon();
  10057. return res;
  10058. }
  10059. }
  10060. parseExportDeclaration(node) {
  10061. return this.parseStatement(null);
  10062. }
  10063. isExportDefaultSpecifier() {
  10064. if (this.match(types.name)) {
  10065. const value = this.state.value;
  10066. if (value === "async" || value === "let") {
  10067. return false;
  10068. }
  10069. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  10070. const l = this.lookahead();
  10071. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  10072. this.expectOnePlugin(["flow", "typescript"]);
  10073. return false;
  10074. }
  10075. }
  10076. } else if (!this.match(types._default)) {
  10077. return false;
  10078. }
  10079. const next = this.nextTokenStart();
  10080. return this.input.charCodeAt(next) === 44 || this.isUnparsedContextual(next, "from");
  10081. }
  10082. parseExportFrom(node, expect) {
  10083. if (this.eatContextual("from")) {
  10084. node.source = this.parseImportSource();
  10085. this.checkExport(node);
  10086. } else {
  10087. if (expect) {
  10088. this.unexpected();
  10089. } else {
  10090. node.source = null;
  10091. }
  10092. }
  10093. this.semicolon();
  10094. }
  10095. shouldParseExportDeclaration() {
  10096. if (this.match(types.at)) {
  10097. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  10098. if (this.hasPlugin("decorators")) {
  10099. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10100. this.unexpected(this.state.start, Errors.DecoratorBeforeExport);
  10101. } else {
  10102. return true;
  10103. }
  10104. }
  10105. }
  10106. return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction();
  10107. }
  10108. checkExport(node, checkNames, isDefault, isFrom) {
  10109. if (checkNames) {
  10110. if (isDefault) {
  10111. this.checkDuplicateExports(node, "default");
  10112. } else if (node.specifiers && node.specifiers.length) {
  10113. for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
  10114. const specifier = _node$specifiers[_i4];
  10115. this.checkDuplicateExports(specifier, specifier.exported.name);
  10116. if (!isFrom && specifier.local) {
  10117. this.checkReservedWord(specifier.local.name, specifier.local.start, true, false);
  10118. this.scope.checkLocalExport(specifier.local);
  10119. }
  10120. }
  10121. } else if (node.declaration) {
  10122. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  10123. const id = node.declaration.id;
  10124. if (!id) throw new Error("Assertion failure");
  10125. this.checkDuplicateExports(node, id.name);
  10126. } else if (node.declaration.type === "VariableDeclaration") {
  10127. for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
  10128. const declaration = _node$declaration$dec[_i5];
  10129. this.checkDeclaration(declaration.id);
  10130. }
  10131. }
  10132. }
  10133. }
  10134. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10135. if (currentContextDecorators.length) {
  10136. const isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
  10137. if (!node.declaration || !isClass) {
  10138. throw this.raise(node.start, Errors.UnsupportedDecoratorExport);
  10139. }
  10140. this.takeDecorators(node.declaration);
  10141. }
  10142. }
  10143. checkDeclaration(node) {
  10144. if (node.type === "Identifier") {
  10145. this.checkDuplicateExports(node, node.name);
  10146. } else if (node.type === "ObjectPattern") {
  10147. for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
  10148. const prop = _node$properties[_i6];
  10149. this.checkDeclaration(prop);
  10150. }
  10151. } else if (node.type === "ArrayPattern") {
  10152. for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
  10153. const elem = _node$elements[_i7];
  10154. if (elem) {
  10155. this.checkDeclaration(elem);
  10156. }
  10157. }
  10158. } else if (node.type === "ObjectProperty") {
  10159. this.checkDeclaration(node.value);
  10160. } else if (node.type === "RestElement") {
  10161. this.checkDeclaration(node.argument);
  10162. } else if (node.type === "AssignmentPattern") {
  10163. this.checkDeclaration(node.left);
  10164. }
  10165. }
  10166. checkDuplicateExports(node, name) {
  10167. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  10168. this.raise(node.start, name === "default" ? Errors.DuplicateDefaultExport : Errors.DuplicateExport, name);
  10169. }
  10170. this.state.exportedIdentifiers.push(name);
  10171. }
  10172. parseExportSpecifiers() {
  10173. const nodes = [];
  10174. let first = true;
  10175. this.expect(types.braceL);
  10176. while (!this.eat(types.braceR)) {
  10177. if (first) {
  10178. first = false;
  10179. } else {
  10180. this.expect(types.comma);
  10181. if (this.eat(types.braceR)) break;
  10182. }
  10183. const node = this.startNode();
  10184. node.local = this.parseIdentifier(true);
  10185. node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
  10186. nodes.push(this.finishNode(node, "ExportSpecifier"));
  10187. }
  10188. return nodes;
  10189. }
  10190. parseImport(node) {
  10191. node.specifiers = [];
  10192. if (!this.match(types.string)) {
  10193. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  10194. const parseNext = !hasDefault || this.eat(types.comma);
  10195. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  10196. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  10197. this.expectContextual("from");
  10198. }
  10199. node.source = this.parseImportSource();
  10200. this.semicolon();
  10201. return this.finishNode(node, "ImportDeclaration");
  10202. }
  10203. parseImportSource() {
  10204. if (!this.match(types.string)) this.unexpected();
  10205. return this.parseExprAtom();
  10206. }
  10207. shouldParseDefaultImport(node) {
  10208. return this.match(types.name);
  10209. }
  10210. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  10211. specifier.local = this.parseIdentifier();
  10212. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription);
  10213. node.specifiers.push(this.finishNode(specifier, type));
  10214. }
  10215. maybeParseDefaultImportSpecifier(node) {
  10216. if (this.shouldParseDefaultImport(node)) {
  10217. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  10218. return true;
  10219. }
  10220. return false;
  10221. }
  10222. maybeParseStarImportSpecifier(node) {
  10223. if (this.match(types.star)) {
  10224. const specifier = this.startNode();
  10225. this.next();
  10226. this.expectContextual("as");
  10227. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  10228. return true;
  10229. }
  10230. return false;
  10231. }
  10232. parseNamedImportSpecifiers(node) {
  10233. let first = true;
  10234. this.expect(types.braceL);
  10235. while (!this.eat(types.braceR)) {
  10236. if (first) {
  10237. first = false;
  10238. } else {
  10239. if (this.eat(types.colon)) {
  10240. throw this.raise(this.state.start, Errors.DestructureNamedImport);
  10241. }
  10242. this.expect(types.comma);
  10243. if (this.eat(types.braceR)) break;
  10244. }
  10245. this.parseImportSpecifier(node);
  10246. }
  10247. }
  10248. parseImportSpecifier(node) {
  10249. const specifier = this.startNode();
  10250. specifier.imported = this.parseIdentifier(true);
  10251. if (this.eatContextual("as")) {
  10252. specifier.local = this.parseIdentifier();
  10253. } else {
  10254. this.checkReservedWord(specifier.imported.name, specifier.start, true, true);
  10255. specifier.local = specifier.imported.__clone();
  10256. }
  10257. this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier");
  10258. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  10259. }
  10260. }
  10261. class ClassScope {
  10262. constructor() {
  10263. this.privateNames = new Set();
  10264. this.loneAccessors = new Map();
  10265. this.undefinedPrivateNames = new Map();
  10266. }
  10267. }
  10268. class ClassScopeHandler {
  10269. constructor(raise) {
  10270. this.stack = [];
  10271. this.undefinedPrivateNames = new Map();
  10272. this.raise = raise;
  10273. }
  10274. current() {
  10275. return this.stack[this.stack.length - 1];
  10276. }
  10277. enter() {
  10278. this.stack.push(new ClassScope());
  10279. }
  10280. exit() {
  10281. const oldClassScope = this.stack.pop();
  10282. const current = this.current();
  10283. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  10284. const [name, pos] = _Array$from[_i];
  10285. if (current) {
  10286. if (!current.undefinedPrivateNames.has(name)) {
  10287. current.undefinedPrivateNames.set(name, pos);
  10288. }
  10289. } else {
  10290. this.raise(pos, Errors.InvalidPrivateFieldResolution, name);
  10291. }
  10292. }
  10293. }
  10294. declarePrivateName(name, elementType, pos) {
  10295. const classScope = this.current();
  10296. let redefined = classScope.privateNames.has(name);
  10297. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  10298. const accessor = redefined && classScope.loneAccessors.get(name);
  10299. if (accessor) {
  10300. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  10301. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  10302. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  10303. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  10304. redefined = oldKind === newKind || oldStatic !== newStatic;
  10305. if (!redefined) classScope.loneAccessors.delete(name);
  10306. } else if (!redefined) {
  10307. classScope.loneAccessors.set(name, elementType);
  10308. }
  10309. }
  10310. if (redefined) {
  10311. this.raise(pos, Errors.PrivateNameRedeclaration, name);
  10312. }
  10313. classScope.privateNames.add(name);
  10314. classScope.undefinedPrivateNames.delete(name);
  10315. }
  10316. usePrivateName(name, pos) {
  10317. let classScope;
  10318. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  10319. classScope = _this$stack[_i2];
  10320. if (classScope.privateNames.has(name)) return;
  10321. }
  10322. if (classScope) {
  10323. classScope.undefinedPrivateNames.set(name, pos);
  10324. } else {
  10325. this.raise(pos, Errors.InvalidPrivateFieldResolution, name);
  10326. }
  10327. }
  10328. }
  10329. class Parser extends StatementParser {
  10330. constructor(options, input) {
  10331. options = getOptions(options);
  10332. super(options, input);
  10333. const ScopeHandler = this.getScopeHandler();
  10334. this.options = options;
  10335. this.inModule = this.options.sourceType === "module";
  10336. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  10337. this.prodParam = new ProductionParameterHandler();
  10338. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  10339. this.plugins = pluginsMap(this.options.plugins);
  10340. this.filename = options.sourceFilename;
  10341. }
  10342. getScopeHandler() {
  10343. return ScopeHandler;
  10344. }
  10345. parse() {
  10346. let paramFlags = PARAM;
  10347. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  10348. paramFlags |= PARAM_AWAIT;
  10349. }
  10350. this.scope.enter(SCOPE_PROGRAM);
  10351. this.prodParam.enter(paramFlags);
  10352. const file = this.startNode();
  10353. const program = this.startNode();
  10354. this.nextToken();
  10355. file.errors = null;
  10356. this.parseTopLevel(file, program);
  10357. file.errors = this.state.errors;
  10358. return file;
  10359. }
  10360. }
  10361. function pluginsMap(plugins) {
  10362. const pluginMap = new Map();
  10363. for (let _i = 0; _i < plugins.length; _i++) {
  10364. const plugin = plugins[_i];
  10365. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  10366. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  10367. }
  10368. return pluginMap;
  10369. }
  10370. function parse(input, options) {
  10371. if (options && options.sourceType === "unambiguous") {
  10372. options = Object.assign({}, options);
  10373. try {
  10374. options.sourceType = "module";
  10375. const parser = getParser(options, input);
  10376. const ast = parser.parse();
  10377. if (parser.sawUnambiguousESM) {
  10378. return ast;
  10379. }
  10380. if (parser.ambiguousScriptDifferentAst) {
  10381. try {
  10382. options.sourceType = "script";
  10383. return getParser(options, input).parse();
  10384. } catch (_unused) {}
  10385. } else {
  10386. ast.program.sourceType = "script";
  10387. }
  10388. return ast;
  10389. } catch (moduleError) {
  10390. try {
  10391. options.sourceType = "script";
  10392. return getParser(options, input).parse();
  10393. } catch (_unused2) {}
  10394. throw moduleError;
  10395. }
  10396. } else {
  10397. return getParser(options, input).parse();
  10398. }
  10399. }
  10400. function parseExpression(input, options) {
  10401. const parser = getParser(options, input);
  10402. if (parser.options.strictMode) {
  10403. parser.state.strict = true;
  10404. }
  10405. return parser.getExpression();
  10406. }
  10407. function getParser(options, input) {
  10408. let cls = Parser;
  10409. if (options && options.plugins) {
  10410. validatePlugins(options.plugins);
  10411. cls = getParserClass(options.plugins);
  10412. }
  10413. return new cls(options, input);
  10414. }
  10415. const parserClassCache = {};
  10416. function getParserClass(pluginsFromOptions) {
  10417. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  10418. const key = pluginList.join("/");
  10419. let cls = parserClassCache[key];
  10420. if (!cls) {
  10421. cls = Parser;
  10422. for (let _i = 0; _i < pluginList.length; _i++) {
  10423. const plugin = pluginList[_i];
  10424. cls = mixinPlugins[plugin](cls);
  10425. }
  10426. parserClassCache[key] = cls;
  10427. }
  10428. return cls;
  10429. }
  10430. exports.parse = parse;
  10431. exports.parseExpression = parseExpression;
  10432. exports.tokTypes = types;
  10433. //# sourceMappingURL=index.js.map