index.js 231 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. /* eslint max-len: 0 */
  4. // This is a trick taken from Esprima. It turns out that, on
  5. // non-Chrome browsers, to check whether a string is in a set, a
  6. // predicate containing a big ugly `switch` statement is faster than
  7. // a regular expression, and on Chrome the two are about on par.
  8. // This function uses `eval` (non-lexical) to produce such a
  9. // predicate from a space-separated string of words.
  10. //
  11. // It starts by sorting the words by length.
  12. function makePredicate(words) {
  13. words = words.split(" ");
  14. return function (str) {
  15. return words.indexOf(str) >= 0;
  16. };
  17. }
  18. // Reserved word lists for various dialects of the language
  19. var reservedWords = {
  20. 6: makePredicate("enum await"),
  21. strict: makePredicate("implements interface let package private protected public static yield"),
  22. strictBind: makePredicate("eval arguments")
  23. };
  24. // And the keywords
  25. var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super");
  26. // ## Character categories
  27. // Big ugly regular expressions that match characters in the
  28. // whitespace, identifier, and identifier-start categories. These
  29. // are only applied when a character is found to actually have a
  30. // code point above 128.
  31. // Generated by `bin/generate-identifier-regex.js`.
  32. var 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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u1877\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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";
  33. var 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\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\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\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\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\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\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA900-\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";
  34. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  35. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  36. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  37. // These are a run-length and offset encoded representation of the
  38. // >0xffff code points that are a valid part of identifiers. The
  39. // offset starts at 0x10000, and each pair of numbers represents an
  40. // offset to the next range, and then a size of the range. They were
  41. // generated by `bin/generate-identifier-regex.js`.
  42. // eslint-disable-next-line comma-spacing
  43. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 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, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 785, 52, 76, 44, 33, 24, 27, 35, 42, 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, 54, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 86, 25, 391, 63, 32, 0, 449, 56, 264, 8, 2, 36, 18, 0, 50, 29, 881, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 65, 0, 32, 6124, 20, 754, 9486, 1, 3071, 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, 4149, 196, 60, 67, 1213, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 10591, 541];
  44. // eslint-disable-next-line comma-spacing
  45. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 10, 2, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 87, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 423, 9, 838, 7, 2, 7, 17, 9, 57, 21, 2, 13, 19882, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 2214, 6, 110, 6, 6, 9, 792487, 239];
  46. // This has a complexity linear to the value of the code. The
  47. // assumption is that looking up astral identifier characters is
  48. // rare.
  49. function isInAstralSet(code, set) {
  50. var pos = 0x10000;
  51. for (var i = 0; i < set.length; i += 2) {
  52. pos += set[i];
  53. if (pos > code) return false;
  54. pos += set[i + 1];
  55. if (pos >= code) return true;
  56. }
  57. }
  58. // Test whether a given character code starts an identifier.
  59. function isIdentifierStart(code) {
  60. if (code < 65) return code === 36;
  61. if (code < 91) return true;
  62. if (code < 97) return code === 95;
  63. if (code < 123) return true;
  64. if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  65. return isInAstralSet(code, astralIdentifierStartCodes);
  66. }
  67. // Test whether a given character is part of an identifier.
  68. function isIdentifierChar(code) {
  69. if (code < 48) return code === 36;
  70. if (code < 58) return true;
  71. if (code < 65) return false;
  72. if (code < 91) return true;
  73. if (code < 97) return code === 95;
  74. if (code < 123) return true;
  75. if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  76. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  77. }
  78. // A second optional argument can be given to further configure
  79. var defaultOptions = {
  80. // Source type ("script" or "module") for different semantics
  81. sourceType: "script",
  82. // Source filename.
  83. sourceFilename: undefined,
  84. // Line from which to start counting source. Useful for
  85. // integration with other tools.
  86. startLine: 1,
  87. // When enabled, a return at the top level is not considered an
  88. // error.
  89. allowReturnOutsideFunction: false,
  90. // When enabled, import/export statements are not constrained to
  91. // appearing at the top of the program.
  92. allowImportExportEverywhere: false,
  93. // TODO
  94. allowSuperOutsideMethod: false,
  95. // An array of plugins to enable
  96. plugins: [],
  97. // TODO
  98. strictMode: null
  99. };
  100. // Interpret and default an options object
  101. function getOptions(opts) {
  102. var options = {};
  103. for (var key in defaultOptions) {
  104. options[key] = opts && key in opts ? opts[key] : defaultOptions[key];
  105. }
  106. return options;
  107. }
  108. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  109. return typeof obj;
  110. } : function (obj) {
  111. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  112. };
  113. var classCallCheck = function (instance, Constructor) {
  114. if (!(instance instanceof Constructor)) {
  115. throw new TypeError("Cannot call a class as a function");
  116. }
  117. };
  118. var inherits = function (subClass, superClass) {
  119. if (typeof superClass !== "function" && superClass !== null) {
  120. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  121. }
  122. subClass.prototype = Object.create(superClass && superClass.prototype, {
  123. constructor: {
  124. value: subClass,
  125. enumerable: false,
  126. writable: true,
  127. configurable: true
  128. }
  129. });
  130. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  131. };
  132. var possibleConstructorReturn = function (self, call) {
  133. if (!self) {
  134. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  135. }
  136. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  137. };
  138. // ## Token types
  139. // The assignment of fine-grained, information-carrying type objects
  140. // allows the tokenizer to store the information it has about a
  141. // token in a way that is very cheap for the parser to look up.
  142. // All token type variables start with an underscore, to make them
  143. // easy to recognize.
  144. // The `beforeExpr` property is used to disambiguate between regular
  145. // expressions and divisions. It is set on all token types that can
  146. // be followed by an expression (thus, a slash after them would be a
  147. // regular expression).
  148. //
  149. // `isLoop` marks a keyword as starting a loop, which is important
  150. // to know when parsing a label, in order to allow or disallow
  151. // continue jumps to that label.
  152. var beforeExpr = true;
  153. var startsExpr = true;
  154. var isLoop = true;
  155. var isAssign = true;
  156. var prefix = true;
  157. var postfix = true;
  158. var TokenType = function TokenType(label) {
  159. var conf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  160. classCallCheck(this, TokenType);
  161. this.label = label;
  162. this.keyword = conf.keyword;
  163. this.beforeExpr = !!conf.beforeExpr;
  164. this.startsExpr = !!conf.startsExpr;
  165. this.rightAssociative = !!conf.rightAssociative;
  166. this.isLoop = !!conf.isLoop;
  167. this.isAssign = !!conf.isAssign;
  168. this.prefix = !!conf.prefix;
  169. this.postfix = !!conf.postfix;
  170. this.binop = conf.binop || null;
  171. this.updateContext = null;
  172. };
  173. var KeywordTokenType = function (_TokenType) {
  174. inherits(KeywordTokenType, _TokenType);
  175. function KeywordTokenType(name) {
  176. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  177. classCallCheck(this, KeywordTokenType);
  178. options.keyword = name;
  179. return possibleConstructorReturn(this, _TokenType.call(this, name, options));
  180. }
  181. return KeywordTokenType;
  182. }(TokenType);
  183. var BinopTokenType = function (_TokenType2) {
  184. inherits(BinopTokenType, _TokenType2);
  185. function BinopTokenType(name, prec) {
  186. classCallCheck(this, BinopTokenType);
  187. return possibleConstructorReturn(this, _TokenType2.call(this, name, { beforeExpr: beforeExpr, binop: prec }));
  188. }
  189. return BinopTokenType;
  190. }(TokenType);
  191. var types = {
  192. num: new TokenType("num", { startsExpr: startsExpr }),
  193. regexp: new TokenType("regexp", { startsExpr: startsExpr }),
  194. string: new TokenType("string", { startsExpr: startsExpr }),
  195. name: new TokenType("name", { startsExpr: startsExpr }),
  196. eof: new TokenType("eof"),
  197. // Punctuation token types.
  198. bracketL: new TokenType("[", { beforeExpr: beforeExpr, startsExpr: startsExpr }),
  199. bracketR: new TokenType("]"),
  200. braceL: new TokenType("{", { beforeExpr: beforeExpr, startsExpr: startsExpr }),
  201. braceBarL: new TokenType("{|", { beforeExpr: beforeExpr, startsExpr: startsExpr }),
  202. braceR: new TokenType("}"),
  203. braceBarR: new TokenType("|}"),
  204. parenL: new TokenType("(", { beforeExpr: beforeExpr, startsExpr: startsExpr }),
  205. parenR: new TokenType(")"),
  206. comma: new TokenType(",", { beforeExpr: beforeExpr }),
  207. semi: new TokenType(";", { beforeExpr: beforeExpr }),
  208. colon: new TokenType(":", { beforeExpr: beforeExpr }),
  209. doubleColon: new TokenType("::", { beforeExpr: beforeExpr }),
  210. dot: new TokenType("."),
  211. question: new TokenType("?", { beforeExpr: beforeExpr }),
  212. arrow: new TokenType("=>", { beforeExpr: beforeExpr }),
  213. template: new TokenType("template"),
  214. ellipsis: new TokenType("...", { beforeExpr: beforeExpr }),
  215. backQuote: new TokenType("`", { startsExpr: startsExpr }),
  216. dollarBraceL: new TokenType("${", { beforeExpr: beforeExpr, startsExpr: startsExpr }),
  217. at: new TokenType("@"),
  218. // Operators. These carry several kinds of properties to help the
  219. // parser use them properly (the presence of these properties is
  220. // what categorizes them as operators).
  221. //
  222. // `binop`, when present, specifies that this operator is a binary
  223. // operator, and will refer to its precedence.
  224. //
  225. // `prefix` and `postfix` mark the operator as a prefix or postfix
  226. // unary operator.
  227. //
  228. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  229. // binary operators with a very low precedence, that should result
  230. // in AssignmentExpression nodes.
  231. eq: new TokenType("=", { beforeExpr: beforeExpr, isAssign: isAssign }),
  232. assign: new TokenType("_=", { beforeExpr: beforeExpr, isAssign: isAssign }),
  233. incDec: new TokenType("++/--", { prefix: prefix, postfix: postfix, startsExpr: startsExpr }),
  234. prefix: new TokenType("prefix", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }),
  235. logicalOR: new BinopTokenType("||", 1),
  236. logicalAND: new BinopTokenType("&&", 2),
  237. bitwiseOR: new BinopTokenType("|", 3),
  238. bitwiseXOR: new BinopTokenType("^", 4),
  239. bitwiseAND: new BinopTokenType("&", 5),
  240. equality: new BinopTokenType("==/!=", 6),
  241. relational: new BinopTokenType("</>", 7),
  242. bitShift: new BinopTokenType("<</>>", 8),
  243. plusMin: new TokenType("+/-", { beforeExpr: beforeExpr, binop: 9, prefix: prefix, startsExpr: startsExpr }),
  244. modulo: new BinopTokenType("%", 10),
  245. star: new BinopTokenType("*", 10),
  246. slash: new BinopTokenType("/", 10),
  247. exponent: new TokenType("**", { beforeExpr: beforeExpr, binop: 11, rightAssociative: true })
  248. };
  249. var keywords = {
  250. "break": new KeywordTokenType("break"),
  251. "case": new KeywordTokenType("case", { beforeExpr: beforeExpr }),
  252. "catch": new KeywordTokenType("catch"),
  253. "continue": new KeywordTokenType("continue"),
  254. "debugger": new KeywordTokenType("debugger"),
  255. "default": new KeywordTokenType("default", { beforeExpr: beforeExpr }),
  256. "do": new KeywordTokenType("do", { isLoop: isLoop, beforeExpr: beforeExpr }),
  257. "else": new KeywordTokenType("else", { beforeExpr: beforeExpr }),
  258. "finally": new KeywordTokenType("finally"),
  259. "for": new KeywordTokenType("for", { isLoop: isLoop }),
  260. "function": new KeywordTokenType("function", { startsExpr: startsExpr }),
  261. "if": new KeywordTokenType("if"),
  262. "return": new KeywordTokenType("return", { beforeExpr: beforeExpr }),
  263. "switch": new KeywordTokenType("switch"),
  264. "throw": new KeywordTokenType("throw", { beforeExpr: beforeExpr }),
  265. "try": new KeywordTokenType("try"),
  266. "var": new KeywordTokenType("var"),
  267. "let": new KeywordTokenType("let"),
  268. "const": new KeywordTokenType("const"),
  269. "while": new KeywordTokenType("while", { isLoop: isLoop }),
  270. "with": new KeywordTokenType("with"),
  271. "new": new KeywordTokenType("new", { beforeExpr: beforeExpr, startsExpr: startsExpr }),
  272. "this": new KeywordTokenType("this", { startsExpr: startsExpr }),
  273. "super": new KeywordTokenType("super", { startsExpr: startsExpr }),
  274. "class": new KeywordTokenType("class"),
  275. "extends": new KeywordTokenType("extends", { beforeExpr: beforeExpr }),
  276. "export": new KeywordTokenType("export"),
  277. "import": new KeywordTokenType("import", { startsExpr: startsExpr }),
  278. "yield": new KeywordTokenType("yield", { beforeExpr: beforeExpr, startsExpr: startsExpr }),
  279. "null": new KeywordTokenType("null", { startsExpr: startsExpr }),
  280. "true": new KeywordTokenType("true", { startsExpr: startsExpr }),
  281. "false": new KeywordTokenType("false", { startsExpr: startsExpr }),
  282. "in": new KeywordTokenType("in", { beforeExpr: beforeExpr, binop: 7 }),
  283. "instanceof": new KeywordTokenType("instanceof", { beforeExpr: beforeExpr, binop: 7 }),
  284. "typeof": new KeywordTokenType("typeof", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }),
  285. "void": new KeywordTokenType("void", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }),
  286. "delete": new KeywordTokenType("delete", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr })
  287. };
  288. // Map keyword names to token types.
  289. Object.keys(keywords).forEach(function (name) {
  290. types["_" + name] = keywords[name];
  291. });
  292. // Matches a whole line break (where CRLF is considered a single
  293. // line break). Used to count lines.
  294. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  295. var lineBreakG = new RegExp(lineBreak.source, "g");
  296. function isNewLine(code) {
  297. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
  298. }
  299. var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  300. // The algorithm used to determine whether a regexp can appear at a
  301. // given point in the program is loosely based on sweet.js' approach.
  302. // See https://github.com/mozilla/sweet.js/wiki/design
  303. var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
  304. classCallCheck(this, TokContext);
  305. this.token = token;
  306. this.isExpr = !!isExpr;
  307. this.preserveSpace = !!preserveSpace;
  308. this.override = override;
  309. };
  310. var types$1 = {
  311. braceStatement: new TokContext("{", false),
  312. braceExpression: new TokContext("{", true),
  313. templateQuasi: new TokContext("${", true),
  314. parenStatement: new TokContext("(", false),
  315. parenExpression: new TokContext("(", true),
  316. template: new TokContext("`", true, true, function (p) {
  317. return p.readTmplToken();
  318. }),
  319. functionExpression: new TokContext("function", true)
  320. };
  321. // Token-specific context update code
  322. types.parenR.updateContext = types.braceR.updateContext = function () {
  323. if (this.state.context.length === 1) {
  324. this.state.exprAllowed = true;
  325. return;
  326. }
  327. var out = this.state.context.pop();
  328. if (out === types$1.braceStatement && this.curContext() === types$1.functionExpression) {
  329. this.state.context.pop();
  330. this.state.exprAllowed = false;
  331. } else if (out === types$1.templateQuasi) {
  332. this.state.exprAllowed = true;
  333. } else {
  334. this.state.exprAllowed = !out.isExpr;
  335. }
  336. };
  337. types.name.updateContext = function (prevType) {
  338. this.state.exprAllowed = false;
  339. if (prevType === types._let || prevType === types._const || prevType === types._var) {
  340. if (lineBreak.test(this.input.slice(this.state.end))) {
  341. this.state.exprAllowed = true;
  342. }
  343. }
  344. };
  345. types.braceL.updateContext = function (prevType) {
  346. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  347. this.state.exprAllowed = true;
  348. };
  349. types.dollarBraceL.updateContext = function () {
  350. this.state.context.push(types$1.templateQuasi);
  351. this.state.exprAllowed = true;
  352. };
  353. types.parenL.updateContext = function (prevType) {
  354. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  355. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  356. this.state.exprAllowed = true;
  357. };
  358. types.incDec.updateContext = function () {
  359. // tokExprAllowed stays unchanged
  360. };
  361. types._function.updateContext = function () {
  362. if (this.curContext() !== types$1.braceStatement) {
  363. this.state.context.push(types$1.functionExpression);
  364. }
  365. this.state.exprAllowed = false;
  366. };
  367. types.backQuote.updateContext = function () {
  368. if (this.curContext() === types$1.template) {
  369. this.state.context.pop();
  370. } else {
  371. this.state.context.push(types$1.template);
  372. }
  373. this.state.exprAllowed = false;
  374. };
  375. // These are used when `options.locations` is on, for the
  376. // `startLoc` and `endLoc` properties.
  377. var Position = function Position(line, col) {
  378. classCallCheck(this, Position);
  379. this.line = line;
  380. this.column = col;
  381. };
  382. var SourceLocation = function SourceLocation(start, end) {
  383. classCallCheck(this, SourceLocation);
  384. this.start = start;
  385. this.end = end;
  386. };
  387. // The `getLineInfo` function is mostly useful when the
  388. // `locations` option is off (for performance reasons) and you
  389. // want to find the line/column position for a given character
  390. // offset. `input` should be the code string that the offset refers
  391. // into.
  392. function getLineInfo(input, offset) {
  393. for (var line = 1, cur = 0;;) {
  394. lineBreakG.lastIndex = cur;
  395. var match = lineBreakG.exec(input);
  396. if (match && match.index < offset) {
  397. ++line;
  398. cur = match.index + match[0].length;
  399. } else {
  400. return new Position(line, offset - cur);
  401. }
  402. }
  403. }
  404. var State = function () {
  405. function State() {
  406. classCallCheck(this, State);
  407. }
  408. State.prototype.init = function init(options, input) {
  409. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  410. this.input = input;
  411. this.potentialArrowAt = -1;
  412. this.inMethod = this.inFunction = this.inGenerator = this.inAsync = this.inPropertyName = this.inType = this.inClassProperty = this.noAnonFunctionType = false;
  413. this.labels = [];
  414. this.decorators = [];
  415. this.tokens = [];
  416. this.comments = [];
  417. this.trailingComments = [];
  418. this.leadingComments = [];
  419. this.commentStack = [];
  420. this.pos = this.lineStart = 0;
  421. this.curLine = options.startLine;
  422. this.type = types.eof;
  423. this.value = null;
  424. this.start = this.end = this.pos;
  425. this.startLoc = this.endLoc = this.curPosition();
  426. this.lastTokEndLoc = this.lastTokStartLoc = null;
  427. this.lastTokStart = this.lastTokEnd = this.pos;
  428. this.context = [types$1.braceStatement];
  429. this.exprAllowed = true;
  430. this.containsEsc = this.containsOctal = false;
  431. this.octalPosition = null;
  432. this.invalidTemplateEscapePosition = null;
  433. this.exportedIdentifiers = [];
  434. return this;
  435. };
  436. // TODO
  437. // TODO
  438. // Used to signify the start of a potential arrow function
  439. // Flags to track whether we are in a function, a generator.
  440. // Labels in scope.
  441. // Leading decorators.
  442. // Token store.
  443. // Comment store.
  444. // Comment attachment store
  445. // The current position of the tokenizer in the input.
  446. // Properties of the current token:
  447. // Its type
  448. // For tokens that include more information than their type, the value
  449. // Its start and end offset
  450. // And, if locations are used, the {line, column} object
  451. // corresponding to those offsets
  452. // Position information for the previous token
  453. // The context stack is used to superficially track syntactic
  454. // context to predict whether a regular expression is allowed in a
  455. // given position.
  456. // Used to signal to callers of `readWord1` whether the word
  457. // contained any escape sequences. This is needed because words with
  458. // escape sequences must not be interpreted as keywords.
  459. // TODO
  460. // Names of exports store. `default` is stored as a name for both
  461. // `export default foo;` and `export { foo as default };`.
  462. State.prototype.curPosition = function curPosition() {
  463. return new Position(this.curLine, this.pos - this.lineStart);
  464. };
  465. State.prototype.clone = function clone(skipArrays) {
  466. var state = new State();
  467. for (var key in this) {
  468. var val = this[key];
  469. if ((!skipArrays || key === "context") && Array.isArray(val)) {
  470. val = val.slice();
  471. }
  472. state[key] = val;
  473. }
  474. return state;
  475. };
  476. return State;
  477. }();
  478. // Object type used to represent tokens. Note that normally, tokens
  479. // simply exist as properties on the parser object. This is only
  480. // used for the onToken callback and the external tokenizer.
  481. var Token = function Token(state) {
  482. classCallCheck(this, Token);
  483. this.type = state.type;
  484. this.value = state.value;
  485. this.start = state.start;
  486. this.end = state.end;
  487. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  488. };
  489. // ## Tokenizer
  490. function codePointToString(code) {
  491. // UTF-16 Decoding
  492. if (code <= 0xFFFF) {
  493. return String.fromCharCode(code);
  494. } else {
  495. return String.fromCharCode((code - 0x10000 >> 10) + 0xD800, (code - 0x10000 & 1023) + 0xDC00);
  496. }
  497. }
  498. var Tokenizer = function () {
  499. function Tokenizer(options, input) {
  500. classCallCheck(this, Tokenizer);
  501. this.state = new State();
  502. this.state.init(options, input);
  503. }
  504. // Move to the next token
  505. Tokenizer.prototype.next = function next() {
  506. if (!this.isLookahead) {
  507. this.state.tokens.push(new Token(this.state));
  508. }
  509. this.state.lastTokEnd = this.state.end;
  510. this.state.lastTokStart = this.state.start;
  511. this.state.lastTokEndLoc = this.state.endLoc;
  512. this.state.lastTokStartLoc = this.state.startLoc;
  513. this.nextToken();
  514. };
  515. // TODO
  516. Tokenizer.prototype.eat = function eat(type) {
  517. if (this.match(type)) {
  518. this.next();
  519. return true;
  520. } else {
  521. return false;
  522. }
  523. };
  524. // TODO
  525. Tokenizer.prototype.match = function match(type) {
  526. return this.state.type === type;
  527. };
  528. // TODO
  529. Tokenizer.prototype.isKeyword = function isKeyword$$1(word) {
  530. return isKeyword(word);
  531. };
  532. // TODO
  533. Tokenizer.prototype.lookahead = function lookahead() {
  534. var old = this.state;
  535. this.state = old.clone(true);
  536. this.isLookahead = true;
  537. this.next();
  538. this.isLookahead = false;
  539. var curr = this.state.clone(true);
  540. this.state = old;
  541. return curr;
  542. };
  543. // Toggle strict mode. Re-reads the next number or string to please
  544. // pedantic tests (`"use strict"; 010;` should fail).
  545. Tokenizer.prototype.setStrict = function setStrict(strict) {
  546. this.state.strict = strict;
  547. if (!this.match(types.num) && !this.match(types.string)) return;
  548. this.state.pos = this.state.start;
  549. while (this.state.pos < this.state.lineStart) {
  550. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  551. --this.state.curLine;
  552. }
  553. this.nextToken();
  554. };
  555. Tokenizer.prototype.curContext = function curContext() {
  556. return this.state.context[this.state.context.length - 1];
  557. };
  558. // Read a single token, updating the parser object's token-related
  559. // properties.
  560. Tokenizer.prototype.nextToken = function nextToken() {
  561. var curContext = this.curContext();
  562. if (!curContext || !curContext.preserveSpace) this.skipSpace();
  563. this.state.containsOctal = false;
  564. this.state.octalPosition = null;
  565. this.state.start = this.state.pos;
  566. this.state.startLoc = this.state.curPosition();
  567. if (this.state.pos >= this.input.length) return this.finishToken(types.eof);
  568. if (curContext.override) {
  569. return curContext.override(this);
  570. } else {
  571. return this.readToken(this.fullCharCodeAtPos());
  572. }
  573. };
  574. Tokenizer.prototype.readToken = function readToken(code) {
  575. // Identifier or keyword. '\uXXXX' sequences are allowed in
  576. // identifiers, so '\' also dispatches to that.
  577. if (isIdentifierStart(code) || code === 92 /* '\' */) {
  578. return this.readWord();
  579. } else {
  580. return this.getTokenFromCode(code);
  581. }
  582. };
  583. Tokenizer.prototype.fullCharCodeAtPos = function fullCharCodeAtPos() {
  584. var code = this.input.charCodeAt(this.state.pos);
  585. if (code <= 0xd7ff || code >= 0xe000) return code;
  586. var next = this.input.charCodeAt(this.state.pos + 1);
  587. return (code << 10) + next - 0x35fdc00;
  588. };
  589. Tokenizer.prototype.pushComment = function pushComment(block, text, start, end, startLoc, endLoc) {
  590. var comment = {
  591. type: block ? "CommentBlock" : "CommentLine",
  592. value: text,
  593. start: start,
  594. end: end,
  595. loc: new SourceLocation(startLoc, endLoc)
  596. };
  597. if (!this.isLookahead) {
  598. this.state.tokens.push(comment);
  599. this.state.comments.push(comment);
  600. this.addComment(comment);
  601. }
  602. };
  603. Tokenizer.prototype.skipBlockComment = function skipBlockComment() {
  604. var startLoc = this.state.curPosition();
  605. var start = this.state.pos;
  606. var end = this.input.indexOf("*/", this.state.pos += 2);
  607. if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment");
  608. this.state.pos = end + 2;
  609. lineBreakG.lastIndex = start;
  610. var match = void 0;
  611. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  612. ++this.state.curLine;
  613. this.state.lineStart = match.index + match[0].length;
  614. }
  615. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  616. };
  617. Tokenizer.prototype.skipLineComment = function skipLineComment(startSkip) {
  618. var start = this.state.pos;
  619. var startLoc = this.state.curPosition();
  620. var ch = this.input.charCodeAt(this.state.pos += startSkip);
  621. while (this.state.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
  622. ++this.state.pos;
  623. ch = this.input.charCodeAt(this.state.pos);
  624. }
  625. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  626. };
  627. // Called at the start of the parse and after every token. Skips
  628. // whitespace and comments, and.
  629. Tokenizer.prototype.skipSpace = function skipSpace() {
  630. loop: while (this.state.pos < this.input.length) {
  631. var ch = this.input.charCodeAt(this.state.pos);
  632. switch (ch) {
  633. case 32:case 160:
  634. // ' '
  635. ++this.state.pos;
  636. break;
  637. case 13:
  638. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  639. ++this.state.pos;
  640. }
  641. case 10:case 8232:case 8233:
  642. ++this.state.pos;
  643. ++this.state.curLine;
  644. this.state.lineStart = this.state.pos;
  645. break;
  646. case 47:
  647. // '/'
  648. switch (this.input.charCodeAt(this.state.pos + 1)) {
  649. case 42:
  650. // '*'
  651. this.skipBlockComment();
  652. break;
  653. case 47:
  654. this.skipLineComment(2);
  655. break;
  656. default:
  657. break loop;
  658. }
  659. break;
  660. default:
  661. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  662. ++this.state.pos;
  663. } else {
  664. break loop;
  665. }
  666. }
  667. }
  668. };
  669. // Called at the end of every token. Sets `end`, `val`, and
  670. // maintains `context` and `exprAllowed`, and skips the space after
  671. // the token, so that the next one's `start` will point at the
  672. // right position.
  673. Tokenizer.prototype.finishToken = function finishToken(type, val) {
  674. this.state.end = this.state.pos;
  675. this.state.endLoc = this.state.curPosition();
  676. var prevType = this.state.type;
  677. this.state.type = type;
  678. this.state.value = val;
  679. this.updateContext(prevType);
  680. };
  681. // ### Token reading
  682. // This is the function that is called to fetch the next token. It
  683. // is somewhat obscure, because it works in character codes rather
  684. // than characters, and because operator parsing has been inlined
  685. // into it.
  686. //
  687. // All in the name of speed.
  688. //
  689. Tokenizer.prototype.readToken_dot = function readToken_dot() {
  690. var next = this.input.charCodeAt(this.state.pos + 1);
  691. if (next >= 48 && next <= 57) {
  692. return this.readNumber(true);
  693. }
  694. var next2 = this.input.charCodeAt(this.state.pos + 2);
  695. if (next === 46 && next2 === 46) {
  696. // 46 = dot '.'
  697. this.state.pos += 3;
  698. return this.finishToken(types.ellipsis);
  699. } else {
  700. ++this.state.pos;
  701. return this.finishToken(types.dot);
  702. }
  703. };
  704. Tokenizer.prototype.readToken_slash = function readToken_slash() {
  705. // '/'
  706. if (this.state.exprAllowed) {
  707. ++this.state.pos;
  708. return this.readRegexp();
  709. }
  710. var next = this.input.charCodeAt(this.state.pos + 1);
  711. if (next === 61) {
  712. return this.finishOp(types.assign, 2);
  713. } else {
  714. return this.finishOp(types.slash, 1);
  715. }
  716. };
  717. Tokenizer.prototype.readToken_mult_modulo = function readToken_mult_modulo(code) {
  718. // '%*'
  719. var type = code === 42 ? types.star : types.modulo;
  720. var width = 1;
  721. var next = this.input.charCodeAt(this.state.pos + 1);
  722. if (next === 42) {
  723. // '*'
  724. width++;
  725. next = this.input.charCodeAt(this.state.pos + 2);
  726. type = types.exponent;
  727. }
  728. if (next === 61) {
  729. width++;
  730. type = types.assign;
  731. }
  732. return this.finishOp(type, width);
  733. };
  734. Tokenizer.prototype.readToken_pipe_amp = function readToken_pipe_amp(code) {
  735. // '|&'
  736. var next = this.input.charCodeAt(this.state.pos + 1);
  737. if (next === code) return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  738. if (next === 61) return this.finishOp(types.assign, 2);
  739. if (code === 124 && next === 125 && this.hasPlugin("flow")) return this.finishOp(types.braceBarR, 2);
  740. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  741. };
  742. Tokenizer.prototype.readToken_caret = function readToken_caret() {
  743. // '^'
  744. var next = this.input.charCodeAt(this.state.pos + 1);
  745. if (next === 61) {
  746. return this.finishOp(types.assign, 2);
  747. } else {
  748. return this.finishOp(types.bitwiseXOR, 1);
  749. }
  750. };
  751. Tokenizer.prototype.readToken_plus_min = function readToken_plus_min(code) {
  752. // '+-'
  753. var next = this.input.charCodeAt(this.state.pos + 1);
  754. if (next === code) {
  755. if (next === 45 && this.input.charCodeAt(this.state.pos + 2) === 62 && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) {
  756. // A `-->` line comment
  757. this.skipLineComment(3);
  758. this.skipSpace();
  759. return this.nextToken();
  760. }
  761. return this.finishOp(types.incDec, 2);
  762. }
  763. if (next === 61) {
  764. return this.finishOp(types.assign, 2);
  765. } else {
  766. return this.finishOp(types.plusMin, 1);
  767. }
  768. };
  769. Tokenizer.prototype.readToken_lt_gt = function readToken_lt_gt(code) {
  770. // '<>'
  771. var next = this.input.charCodeAt(this.state.pos + 1);
  772. var size = 1;
  773. if (next === code) {
  774. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  775. if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(types.assign, size + 1);
  776. return this.finishOp(types.bitShift, size);
  777. }
  778. if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  779. if (this.inModule) this.unexpected();
  780. // `<!--`, an XML-style comment that should be interpreted as a line comment
  781. this.skipLineComment(4);
  782. this.skipSpace();
  783. return this.nextToken();
  784. }
  785. if (next === 61) {
  786. // <= | >=
  787. size = 2;
  788. }
  789. return this.finishOp(types.relational, size);
  790. };
  791. Tokenizer.prototype.readToken_eq_excl = function readToken_eq_excl(code) {
  792. // '=!'
  793. var next = this.input.charCodeAt(this.state.pos + 1);
  794. if (next === 61) return this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  795. if (code === 61 && next === 62) {
  796. // '=>'
  797. this.state.pos += 2;
  798. return this.finishToken(types.arrow);
  799. }
  800. return this.finishOp(code === 61 ? types.eq : types.prefix, 1);
  801. };
  802. Tokenizer.prototype.getTokenFromCode = function getTokenFromCode(code) {
  803. switch (code) {
  804. // The interpretation of a dot depends on whether it is followed
  805. // by a digit or another two dots.
  806. case 46:
  807. // '.'
  808. return this.readToken_dot();
  809. // Punctuation tokens.
  810. case 40:
  811. ++this.state.pos;return this.finishToken(types.parenL);
  812. case 41:
  813. ++this.state.pos;return this.finishToken(types.parenR);
  814. case 59:
  815. ++this.state.pos;return this.finishToken(types.semi);
  816. case 44:
  817. ++this.state.pos;return this.finishToken(types.comma);
  818. case 91:
  819. ++this.state.pos;return this.finishToken(types.bracketL);
  820. case 93:
  821. ++this.state.pos;return this.finishToken(types.bracketR);
  822. case 123:
  823. if (this.hasPlugin("flow") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  824. return this.finishOp(types.braceBarL, 2);
  825. } else {
  826. ++this.state.pos;
  827. return this.finishToken(types.braceL);
  828. }
  829. case 125:
  830. ++this.state.pos;return this.finishToken(types.braceR);
  831. case 58:
  832. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  833. return this.finishOp(types.doubleColon, 2);
  834. } else {
  835. ++this.state.pos;
  836. return this.finishToken(types.colon);
  837. }
  838. case 63:
  839. ++this.state.pos;return this.finishToken(types.question);
  840. case 64:
  841. ++this.state.pos;return this.finishToken(types.at);
  842. case 96:
  843. // '`'
  844. ++this.state.pos;
  845. return this.finishToken(types.backQuote);
  846. case 48:
  847. // '0'
  848. var next = this.input.charCodeAt(this.state.pos + 1);
  849. if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
  850. if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
  851. if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
  852. // Anything else beginning with a digit is an integer, octal
  853. // number, or float.
  854. case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:
  855. // 1-9
  856. return this.readNumber(false);
  857. // Quotes produce strings.
  858. case 34:case 39:
  859. // '"', "'"
  860. return this.readString(code);
  861. // Operators are parsed inline in tiny state machines. '=' (61) is
  862. // often referred to. `finishOp` simply skips the amount of
  863. // characters it is given as second argument, and returns a token
  864. // of the type given by its first argument.
  865. case 47:
  866. // '/'
  867. return this.readToken_slash();
  868. case 37:case 42:
  869. // '%*'
  870. return this.readToken_mult_modulo(code);
  871. case 124:case 38:
  872. // '|&'
  873. return this.readToken_pipe_amp(code);
  874. case 94:
  875. // '^'
  876. return this.readToken_caret();
  877. case 43:case 45:
  878. // '+-'
  879. return this.readToken_plus_min(code);
  880. case 60:case 62:
  881. // '<>'
  882. return this.readToken_lt_gt(code);
  883. case 61:case 33:
  884. // '=!'
  885. return this.readToken_eq_excl(code);
  886. case 126:
  887. // '~'
  888. return this.finishOp(types.prefix, 1);
  889. }
  890. this.raise(this.state.pos, "Unexpected character '" + codePointToString(code) + "'");
  891. };
  892. Tokenizer.prototype.finishOp = function finishOp(type, size) {
  893. var str = this.input.slice(this.state.pos, this.state.pos + size);
  894. this.state.pos += size;
  895. return this.finishToken(type, str);
  896. };
  897. Tokenizer.prototype.readRegexp = function readRegexp() {
  898. var start = this.state.pos;
  899. var escaped = void 0,
  900. inClass = void 0;
  901. for (;;) {
  902. if (this.state.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
  903. var ch = this.input.charAt(this.state.pos);
  904. if (lineBreak.test(ch)) {
  905. this.raise(start, "Unterminated regular expression");
  906. }
  907. if (escaped) {
  908. escaped = false;
  909. } else {
  910. if (ch === "[") {
  911. inClass = true;
  912. } else if (ch === "]" && inClass) {
  913. inClass = false;
  914. } else if (ch === "/" && !inClass) {
  915. break;
  916. }
  917. escaped = ch === "\\";
  918. }
  919. ++this.state.pos;
  920. }
  921. var content = this.input.slice(start, this.state.pos);
  922. ++this.state.pos;
  923. // Need to use `readWord1` because '\uXXXX' sequences are allowed
  924. // here (don't ask).
  925. var mods = this.readWord1();
  926. if (mods) {
  927. var validFlags = /^[gmsiyu]*$/;
  928. if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
  929. }
  930. return this.finishToken(types.regexp, {
  931. pattern: content,
  932. flags: mods
  933. });
  934. };
  935. // Read an integer in the given radix. Return null if zero digits
  936. // were read, the integer value otherwise. When `len` is given, this
  937. // will return `null` unless the integer has exactly `len` digits.
  938. Tokenizer.prototype.readInt = function readInt(radix, len) {
  939. var start = this.state.pos;
  940. var total = 0;
  941. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  942. var code = this.input.charCodeAt(this.state.pos);
  943. var val = void 0;
  944. if (code >= 97) {
  945. val = code - 97 + 10; // a
  946. } else if (code >= 65) {
  947. val = code - 65 + 10; // A
  948. } else if (code >= 48 && code <= 57) {
  949. val = code - 48; // 0-9
  950. } else {
  951. val = Infinity;
  952. }
  953. if (val >= radix) break;
  954. ++this.state.pos;
  955. total = total * radix + val;
  956. }
  957. if (this.state.pos === start || len != null && this.state.pos - start !== len) return null;
  958. return total;
  959. };
  960. Tokenizer.prototype.readRadixNumber = function readRadixNumber(radix) {
  961. this.state.pos += 2; // 0x
  962. var val = this.readInt(radix);
  963. if (val == null) this.raise(this.state.start + 2, "Expected number in radix " + radix);
  964. if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.state.pos, "Identifier directly after number");
  965. return this.finishToken(types.num, val);
  966. };
  967. // Read an integer, octal integer, or floating-point number.
  968. Tokenizer.prototype.readNumber = function readNumber(startsWithDot) {
  969. var start = this.state.pos;
  970. var octal = this.input.charCodeAt(start) === 48; // '0'
  971. var isFloat = false;
  972. if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
  973. if (octal && this.state.pos == start + 1) octal = false; // number === 0
  974. var next = this.input.charCodeAt(this.state.pos);
  975. if (next === 46 && !octal) {
  976. // '.'
  977. ++this.state.pos;
  978. this.readInt(10);
  979. isFloat = true;
  980. next = this.input.charCodeAt(this.state.pos);
  981. }
  982. if ((next === 69 || next === 101) && !octal) {
  983. // 'eE'
  984. next = this.input.charCodeAt(++this.state.pos);
  985. if (next === 43 || next === 45) ++this.state.pos; // '+-'
  986. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  987. isFloat = true;
  988. }
  989. if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.state.pos, "Identifier directly after number");
  990. var str = this.input.slice(start, this.state.pos);
  991. var val = void 0;
  992. if (isFloat) {
  993. val = parseFloat(str);
  994. } else if (!octal || str.length === 1) {
  995. val = parseInt(str, 10);
  996. } else if (this.state.strict) {
  997. this.raise(start, "Invalid number");
  998. } else if (/[89]/.test(str)) {
  999. val = parseInt(str, 10);
  1000. } else {
  1001. val = parseInt(str, 8);
  1002. }
  1003. return this.finishToken(types.num, val);
  1004. };
  1005. // Read a string value, interpreting backslash-escapes.
  1006. Tokenizer.prototype.readCodePoint = function readCodePoint(throwOnInvalid) {
  1007. var ch = this.input.charCodeAt(this.state.pos);
  1008. var code = void 0;
  1009. if (ch === 123) {
  1010. // '{'
  1011. var codePos = ++this.state.pos;
  1012. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, throwOnInvalid);
  1013. ++this.state.pos;
  1014. if (code === null) {
  1015. --this.state.invalidTemplateEscapePosition; // to point to the '\'' instead of the 'u'
  1016. } else if (code > 0x10FFFF) {
  1017. if (throwOnInvalid) {
  1018. this.raise(codePos, "Code point out of bounds");
  1019. } else {
  1020. this.state.invalidTemplateEscapePosition = codePos - 2;
  1021. return null;
  1022. }
  1023. }
  1024. } else {
  1025. code = this.readHexChar(4, throwOnInvalid);
  1026. }
  1027. return code;
  1028. };
  1029. Tokenizer.prototype.readString = function readString(quote) {
  1030. var out = "",
  1031. chunkStart = ++this.state.pos;
  1032. for (;;) {
  1033. if (this.state.pos >= this.input.length) this.raise(this.state.start, "Unterminated string constant");
  1034. var ch = this.input.charCodeAt(this.state.pos);
  1035. if (ch === quote) break;
  1036. if (ch === 92) {
  1037. // '\'
  1038. out += this.input.slice(chunkStart, this.state.pos);
  1039. out += this.readEscapedChar(false);
  1040. chunkStart = this.state.pos;
  1041. } else {
  1042. if (isNewLine(ch)) this.raise(this.state.start, "Unterminated string constant");
  1043. ++this.state.pos;
  1044. }
  1045. }
  1046. out += this.input.slice(chunkStart, this.state.pos++);
  1047. return this.finishToken(types.string, out);
  1048. };
  1049. // Reads template string tokens.
  1050. Tokenizer.prototype.readTmplToken = function readTmplToken() {
  1051. var out = "",
  1052. chunkStart = this.state.pos,
  1053. containsInvalid = false;
  1054. for (;;) {
  1055. if (this.state.pos >= this.input.length) this.raise(this.state.start, "Unterminated template");
  1056. var ch = this.input.charCodeAt(this.state.pos);
  1057. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  1058. // '`', '${'
  1059. if (this.state.pos === this.state.start && this.match(types.template)) {
  1060. if (ch === 36) {
  1061. this.state.pos += 2;
  1062. return this.finishToken(types.dollarBraceL);
  1063. } else {
  1064. ++this.state.pos;
  1065. return this.finishToken(types.backQuote);
  1066. }
  1067. }
  1068. out += this.input.slice(chunkStart, this.state.pos);
  1069. return this.finishToken(types.template, containsInvalid ? null : out);
  1070. }
  1071. if (ch === 92) {
  1072. // '\'
  1073. out += this.input.slice(chunkStart, this.state.pos);
  1074. var escaped = this.readEscapedChar(true);
  1075. if (escaped === null) {
  1076. containsInvalid = true;
  1077. } else {
  1078. out += escaped;
  1079. }
  1080. chunkStart = this.state.pos;
  1081. } else if (isNewLine(ch)) {
  1082. out += this.input.slice(chunkStart, this.state.pos);
  1083. ++this.state.pos;
  1084. switch (ch) {
  1085. case 13:
  1086. if (this.input.charCodeAt(this.state.pos) === 10) ++this.state.pos;
  1087. case 10:
  1088. out += "\n";
  1089. break;
  1090. default:
  1091. out += String.fromCharCode(ch);
  1092. break;
  1093. }
  1094. ++this.state.curLine;
  1095. this.state.lineStart = this.state.pos;
  1096. chunkStart = this.state.pos;
  1097. } else {
  1098. ++this.state.pos;
  1099. }
  1100. }
  1101. };
  1102. // Used to read escaped characters
  1103. Tokenizer.prototype.readEscapedChar = function readEscapedChar(inTemplate) {
  1104. var throwOnInvalid = !inTemplate;
  1105. var ch = this.input.charCodeAt(++this.state.pos);
  1106. ++this.state.pos;
  1107. switch (ch) {
  1108. case 110:
  1109. return "\n"; // 'n' -> '\n'
  1110. case 114:
  1111. return "\r"; // 'r' -> '\r'
  1112. case 120:
  1113. {
  1114. // 'x'
  1115. var code = this.readHexChar(2, throwOnInvalid);
  1116. return code === null ? null : String.fromCharCode(code);
  1117. }
  1118. case 117:
  1119. {
  1120. // 'u'
  1121. var _code = this.readCodePoint(throwOnInvalid);
  1122. return _code === null ? null : codePointToString(_code);
  1123. }
  1124. case 116:
  1125. return "\t"; // 't' -> '\t'
  1126. case 98:
  1127. return "\b"; // 'b' -> '\b'
  1128. case 118:
  1129. return "\x0B"; // 'v' -> '\u000b'
  1130. case 102:
  1131. return "\f"; // 'f' -> '\f'
  1132. case 13:
  1133. if (this.input.charCodeAt(this.state.pos) === 10) ++this.state.pos; // '\r\n'
  1134. case 10:
  1135. // ' \n'
  1136. this.state.lineStart = this.state.pos;
  1137. ++this.state.curLine;
  1138. return "";
  1139. default:
  1140. if (ch >= 48 && ch <= 55) {
  1141. var codePos = this.state.pos - 1;
  1142. var octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0];
  1143. var octal = parseInt(octalStr, 8);
  1144. if (octal > 255) {
  1145. octalStr = octalStr.slice(0, -1);
  1146. octal = parseInt(octalStr, 8);
  1147. }
  1148. if (octal > 0) {
  1149. if (inTemplate) {
  1150. this.state.invalidTemplateEscapePosition = codePos;
  1151. return null;
  1152. } else if (this.state.strict) {
  1153. this.raise(codePos, "Octal literal in strict mode");
  1154. } else if (!this.state.containsOctal) {
  1155. // These properties are only used to throw an error for an octal which occurs
  1156. // in a directive which occurs prior to a "use strict" directive.
  1157. this.state.containsOctal = true;
  1158. this.state.octalPosition = codePos;
  1159. }
  1160. }
  1161. this.state.pos += octalStr.length - 1;
  1162. return String.fromCharCode(octal);
  1163. }
  1164. return String.fromCharCode(ch);
  1165. }
  1166. };
  1167. // Used to read character escape sequences ('\x', '\u').
  1168. Tokenizer.prototype.readHexChar = function readHexChar(len, throwOnInvalid) {
  1169. var codePos = this.state.pos;
  1170. var n = this.readInt(16, len);
  1171. if (n === null) {
  1172. if (throwOnInvalid) {
  1173. this.raise(codePos, "Bad character escape sequence");
  1174. } else {
  1175. this.state.pos = codePos - 1;
  1176. this.state.invalidTemplateEscapePosition = codePos - 1;
  1177. }
  1178. }
  1179. return n;
  1180. };
  1181. // Read an identifier, and return it as a string. Sets `this.state.containsEsc`
  1182. // to whether the word contained a '\u' escape.
  1183. //
  1184. // Incrementally adds only escaped chars, adding other chunks as-is
  1185. // as a micro-optimization.
  1186. Tokenizer.prototype.readWord1 = function readWord1() {
  1187. this.state.containsEsc = false;
  1188. var word = "",
  1189. first = true,
  1190. chunkStart = this.state.pos;
  1191. while (this.state.pos < this.input.length) {
  1192. var ch = this.fullCharCodeAtPos();
  1193. if (isIdentifierChar(ch)) {
  1194. this.state.pos += ch <= 0xffff ? 1 : 2;
  1195. } else if (ch === 92) {
  1196. // "\"
  1197. this.state.containsEsc = true;
  1198. word += this.input.slice(chunkStart, this.state.pos);
  1199. var escStart = this.state.pos;
  1200. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  1201. // "u"
  1202. this.raise(this.state.pos, "Expecting Unicode escape sequence \\uXXXX");
  1203. }
  1204. ++this.state.pos;
  1205. var esc = this.readCodePoint(true);
  1206. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, true)) {
  1207. this.raise(escStart, "Invalid Unicode escape");
  1208. }
  1209. word += codePointToString(esc);
  1210. chunkStart = this.state.pos;
  1211. } else {
  1212. break;
  1213. }
  1214. first = false;
  1215. }
  1216. return word + this.input.slice(chunkStart, this.state.pos);
  1217. };
  1218. // Read an identifier or keyword token. Will check for reserved
  1219. // words when necessary.
  1220. Tokenizer.prototype.readWord = function readWord() {
  1221. var word = this.readWord1();
  1222. var type = types.name;
  1223. if (!this.state.containsEsc && this.isKeyword(word)) {
  1224. type = keywords[word];
  1225. }
  1226. return this.finishToken(type, word);
  1227. };
  1228. Tokenizer.prototype.braceIsBlock = function braceIsBlock(prevType) {
  1229. if (prevType === types.colon) {
  1230. var parent = this.curContext();
  1231. if (parent === types$1.braceStatement || parent === types$1.braceExpression) {
  1232. return !parent.isExpr;
  1233. }
  1234. }
  1235. if (prevType === types._return) {
  1236. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  1237. }
  1238. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR) {
  1239. return true;
  1240. }
  1241. if (prevType === types.braceL) {
  1242. return this.curContext() === types$1.braceStatement;
  1243. }
  1244. return !this.state.exprAllowed;
  1245. };
  1246. Tokenizer.prototype.updateContext = function updateContext(prevType) {
  1247. var type = this.state.type;
  1248. var update = void 0;
  1249. if (type.keyword && prevType === types.dot) {
  1250. this.state.exprAllowed = false;
  1251. } else if (update = type.updateContext) {
  1252. update.call(this, prevType);
  1253. } else {
  1254. this.state.exprAllowed = type.beforeExpr;
  1255. }
  1256. };
  1257. return Tokenizer;
  1258. }();
  1259. var plugins = {};
  1260. var frozenDeprecatedWildcardPluginList = ["jsx", "doExpressions", "objectRestSpread", "decorators", "classProperties", "exportExtensions", "asyncGenerators", "functionBind", "functionSent", "dynamicImport", "flow"];
  1261. var Parser = function (_Tokenizer) {
  1262. inherits(Parser, _Tokenizer);
  1263. function Parser(options, input) {
  1264. classCallCheck(this, Parser);
  1265. options = getOptions(options);
  1266. var _this = possibleConstructorReturn(this, _Tokenizer.call(this, options, input));
  1267. _this.options = options;
  1268. _this.inModule = _this.options.sourceType === "module";
  1269. _this.input = input;
  1270. _this.plugins = _this.loadPlugins(_this.options.plugins);
  1271. _this.filename = options.sourceFilename;
  1272. // If enabled, skip leading hashbang line.
  1273. if (_this.state.pos === 0 && _this.input[0] === "#" && _this.input[1] === "!") {
  1274. _this.skipLineComment(2);
  1275. }
  1276. return _this;
  1277. }
  1278. Parser.prototype.isReservedWord = function isReservedWord(word) {
  1279. if (word === "await") {
  1280. return this.inModule;
  1281. } else {
  1282. return reservedWords[6](word);
  1283. }
  1284. };
  1285. Parser.prototype.hasPlugin = function hasPlugin(name) {
  1286. if (this.plugins["*"] && frozenDeprecatedWildcardPluginList.indexOf(name) > -1) {
  1287. return true;
  1288. }
  1289. return !!this.plugins[name];
  1290. };
  1291. Parser.prototype.extend = function extend(name, f) {
  1292. this[name] = f(this[name]);
  1293. };
  1294. Parser.prototype.loadAllPlugins = function loadAllPlugins() {
  1295. var _this2 = this;
  1296. // ensure flow plugin loads last, also ensure estree is not loaded with *
  1297. var pluginNames = Object.keys(plugins).filter(function (name) {
  1298. return name !== "flow" && name !== "estree";
  1299. });
  1300. pluginNames.push("flow");
  1301. pluginNames.forEach(function (name) {
  1302. var plugin = plugins[name];
  1303. if (plugin) plugin(_this2);
  1304. });
  1305. };
  1306. Parser.prototype.loadPlugins = function loadPlugins(pluginList) {
  1307. // TODO: Deprecate "*" option in next major version of Babylon
  1308. if (pluginList.indexOf("*") >= 0) {
  1309. this.loadAllPlugins();
  1310. return { "*": true };
  1311. }
  1312. var pluginMap = {};
  1313. if (pluginList.indexOf("flow") >= 0) {
  1314. // ensure flow plugin loads last
  1315. pluginList = pluginList.filter(function (plugin) {
  1316. return plugin !== "flow";
  1317. });
  1318. pluginList.push("flow");
  1319. }
  1320. if (pluginList.indexOf("estree") >= 0) {
  1321. // ensure estree plugin loads first
  1322. pluginList = pluginList.filter(function (plugin) {
  1323. return plugin !== "estree";
  1324. });
  1325. pluginList.unshift("estree");
  1326. }
  1327. for (var _iterator = pluginList, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  1328. var _ref;
  1329. if (_isArray) {
  1330. if (_i >= _iterator.length) break;
  1331. _ref = _iterator[_i++];
  1332. } else {
  1333. _i = _iterator.next();
  1334. if (_i.done) break;
  1335. _ref = _i.value;
  1336. }
  1337. var name = _ref;
  1338. if (!pluginMap[name]) {
  1339. pluginMap[name] = true;
  1340. var plugin = plugins[name];
  1341. if (plugin) plugin(this);
  1342. }
  1343. }
  1344. return pluginMap;
  1345. };
  1346. Parser.prototype.parse = function parse() {
  1347. var file = this.startNode();
  1348. var program = this.startNode();
  1349. this.nextToken();
  1350. return this.parseTopLevel(file, program);
  1351. };
  1352. return Parser;
  1353. }(Tokenizer);
  1354. var pp = Parser.prototype;
  1355. // ## Parser utilities
  1356. // TODO
  1357. pp.addExtra = function (node, key, val) {
  1358. if (!node) return;
  1359. var extra = node.extra = node.extra || {};
  1360. extra[key] = val;
  1361. };
  1362. // TODO
  1363. pp.isRelational = function (op) {
  1364. return this.match(types.relational) && this.state.value === op;
  1365. };
  1366. // TODO
  1367. pp.expectRelational = function (op) {
  1368. if (this.isRelational(op)) {
  1369. this.next();
  1370. } else {
  1371. this.unexpected(null, types.relational);
  1372. }
  1373. };
  1374. // Tests whether parsed token is a contextual keyword.
  1375. pp.isContextual = function (name) {
  1376. return this.match(types.name) && this.state.value === name;
  1377. };
  1378. // Consumes contextual keyword if possible.
  1379. pp.eatContextual = function (name) {
  1380. return this.state.value === name && this.eat(types.name);
  1381. };
  1382. // Asserts that following token is given contextual keyword.
  1383. pp.expectContextual = function (name, message) {
  1384. if (!this.eatContextual(name)) this.unexpected(null, message);
  1385. };
  1386. // Test whether a semicolon can be inserted at the current position.
  1387. pp.canInsertSemicolon = function () {
  1388. return this.match(types.eof) || this.match(types.braceR) || lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  1389. };
  1390. // TODO
  1391. pp.isLineTerminator = function () {
  1392. return this.eat(types.semi) || this.canInsertSemicolon();
  1393. };
  1394. // Consume a semicolon, or, failing that, see if we are allowed to
  1395. // pretend that there is a semicolon at this position.
  1396. pp.semicolon = function () {
  1397. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  1398. };
  1399. // Expect a token of a given type. If found, consume it, otherwise,
  1400. // raise an unexpected token error at given pos.
  1401. pp.expect = function (type, pos) {
  1402. return this.eat(type) || this.unexpected(pos, type);
  1403. };
  1404. // Raise an unexpected token error. Can take the expected token type
  1405. // instead of a message string.
  1406. pp.unexpected = function (pos) {
  1407. var messageOrType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "Unexpected token";
  1408. if (messageOrType && (typeof messageOrType === "undefined" ? "undefined" : _typeof(messageOrType)) === "object" && messageOrType.label) {
  1409. messageOrType = "Unexpected token, expected " + messageOrType.label;
  1410. }
  1411. this.raise(pos != null ? pos : this.state.start, messageOrType);
  1412. };
  1413. /* eslint max-len: 0 */
  1414. var pp$1 = Parser.prototype;
  1415. // ### Statement parsing
  1416. // Parse a program. Initializes the parser, reads any number of
  1417. // statements, and wraps them in a Program node. Optionally takes a
  1418. // `program` argument. If present, the statements will be appended
  1419. // to its body instead of creating a new node.
  1420. pp$1.parseTopLevel = function (file, program) {
  1421. program.sourceType = this.options.sourceType;
  1422. this.parseBlockBody(program, true, true, types.eof);
  1423. file.program = this.finishNode(program, "Program");
  1424. file.comments = this.state.comments;
  1425. file.tokens = this.state.tokens;
  1426. return this.finishNode(file, "File");
  1427. };
  1428. var loopLabel = { kind: "loop" };
  1429. var switchLabel = { kind: "switch" };
  1430. // TODO
  1431. pp$1.stmtToDirective = function (stmt) {
  1432. var expr = stmt.expression;
  1433. var directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  1434. var directive = this.startNodeAt(stmt.start, stmt.loc.start);
  1435. var raw = this.input.slice(expr.start, expr.end);
  1436. var val = directiveLiteral.value = raw.slice(1, -1); // remove quotes
  1437. this.addExtra(directiveLiteral, "raw", raw);
  1438. this.addExtra(directiveLiteral, "rawValue", val);
  1439. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  1440. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  1441. };
  1442. // Parse a single statement.
  1443. //
  1444. // If expecting a statement and finding a slash operator, parse a
  1445. // regular expression literal. This is to handle cases like
  1446. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  1447. // does not help.
  1448. pp$1.parseStatement = function (declaration, topLevel) {
  1449. if (this.match(types.at)) {
  1450. this.parseDecorators(true);
  1451. }
  1452. var starttype = this.state.type;
  1453. var node = this.startNode();
  1454. // Most types of statements are recognized by the keyword they
  1455. // start with. Many are trivial to parse, some require a bit of
  1456. // complexity.
  1457. switch (starttype) {
  1458. case types._break:case types._continue:
  1459. return this.parseBreakContinueStatement(node, starttype.keyword);
  1460. case types._debugger:
  1461. return this.parseDebuggerStatement(node);
  1462. case types._do:
  1463. return this.parseDoStatement(node);
  1464. case types._for:
  1465. return this.parseForStatement(node);
  1466. case types._function:
  1467. if (!declaration) this.unexpected();
  1468. return this.parseFunctionStatement(node);
  1469. case types._class:
  1470. if (!declaration) this.unexpected();
  1471. return this.parseClass(node, true);
  1472. case types._if:
  1473. return this.parseIfStatement(node);
  1474. case types._return:
  1475. return this.parseReturnStatement(node);
  1476. case types._switch:
  1477. return this.parseSwitchStatement(node);
  1478. case types._throw:
  1479. return this.parseThrowStatement(node);
  1480. case types._try:
  1481. return this.parseTryStatement(node);
  1482. case types._let:
  1483. case types._const:
  1484. if (!declaration) this.unexpected(); // NOTE: falls through to _var
  1485. case types._var:
  1486. return this.parseVarStatement(node, starttype);
  1487. case types._while:
  1488. return this.parseWhileStatement(node);
  1489. case types._with:
  1490. return this.parseWithStatement(node);
  1491. case types.braceL:
  1492. return this.parseBlock();
  1493. case types.semi:
  1494. return this.parseEmptyStatement(node);
  1495. case types._export:
  1496. case types._import:
  1497. if (this.hasPlugin("dynamicImport") && this.lookahead().type === types.parenL) break;
  1498. if (!this.options.allowImportExportEverywhere) {
  1499. if (!topLevel) {
  1500. this.raise(this.state.start, "'import' and 'export' may only appear at the top level");
  1501. }
  1502. if (!this.inModule) {
  1503. this.raise(this.state.start, "'import' and 'export' may appear only with 'sourceType: \"module\"'");
  1504. }
  1505. }
  1506. return starttype === types._import ? this.parseImport(node) : this.parseExport(node);
  1507. case types.name:
  1508. if (this.state.value === "async") {
  1509. // peek ahead and see if next token is a function
  1510. var state = this.state.clone();
  1511. this.next();
  1512. if (this.match(types._function) && !this.canInsertSemicolon()) {
  1513. this.expect(types._function);
  1514. return this.parseFunction(node, true, false, true);
  1515. } else {
  1516. this.state = state;
  1517. }
  1518. }
  1519. }
  1520. // If the statement does not start with a statement keyword or a
  1521. // brace, it's an ExpressionStatement or LabeledStatement. We
  1522. // simply start parsing an expression, and afterwards, if the
  1523. // next token is a colon and the expression was a simple
  1524. // Identifier node, we switch to interpreting it as a label.
  1525. var maybeName = this.state.value;
  1526. var expr = this.parseExpression();
  1527. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  1528. return this.parseLabeledStatement(node, maybeName, expr);
  1529. } else {
  1530. return this.parseExpressionStatement(node, expr);
  1531. }
  1532. };
  1533. pp$1.takeDecorators = function (node) {
  1534. if (this.state.decorators.length) {
  1535. node.decorators = this.state.decorators;
  1536. this.state.decorators = [];
  1537. }
  1538. };
  1539. pp$1.parseDecorators = function (allowExport) {
  1540. while (this.match(types.at)) {
  1541. var decorator = this.parseDecorator();
  1542. this.state.decorators.push(decorator);
  1543. }
  1544. if (allowExport && this.match(types._export)) {
  1545. return;
  1546. }
  1547. if (!this.match(types._class)) {
  1548. this.raise(this.state.start, "Leading decorators must be attached to a class declaration");
  1549. }
  1550. };
  1551. pp$1.parseDecorator = function () {
  1552. if (!this.hasPlugin("decorators")) {
  1553. this.unexpected();
  1554. }
  1555. var node = this.startNode();
  1556. this.next();
  1557. node.expression = this.parseMaybeAssign();
  1558. return this.finishNode(node, "Decorator");
  1559. };
  1560. pp$1.parseBreakContinueStatement = function (node, keyword) {
  1561. var isBreak = keyword === "break";
  1562. this.next();
  1563. if (this.isLineTerminator()) {
  1564. node.label = null;
  1565. } else if (!this.match(types.name)) {
  1566. this.unexpected();
  1567. } else {
  1568. node.label = this.parseIdentifier();
  1569. this.semicolon();
  1570. }
  1571. // Verify that there is an actual destination to break or
  1572. // continue to.
  1573. var i = void 0;
  1574. for (i = 0; i < this.state.labels.length; ++i) {
  1575. var lab = this.state.labels[i];
  1576. if (node.label == null || lab.name === node.label.name) {
  1577. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  1578. if (node.label && isBreak) break;
  1579. }
  1580. }
  1581. if (i === this.state.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
  1582. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  1583. };
  1584. pp$1.parseDebuggerStatement = function (node) {
  1585. this.next();
  1586. this.semicolon();
  1587. return this.finishNode(node, "DebuggerStatement");
  1588. };
  1589. pp$1.parseDoStatement = function (node) {
  1590. this.next();
  1591. this.state.labels.push(loopLabel);
  1592. node.body = this.parseStatement(false);
  1593. this.state.labels.pop();
  1594. this.expect(types._while);
  1595. node.test = this.parseParenExpression();
  1596. this.eat(types.semi);
  1597. return this.finishNode(node, "DoWhileStatement");
  1598. };
  1599. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  1600. // loop is non-trivial. Basically, we have to parse the init `var`
  1601. // statement or expression, disallowing the `in` operator (see
  1602. // the second parameter to `parseExpression`), and then check
  1603. // whether the next token is `in` or `of`. When there is no init
  1604. // part (semicolon immediately after the opening parenthesis), it
  1605. // is a regular `for` loop.
  1606. pp$1.parseForStatement = function (node) {
  1607. this.next();
  1608. this.state.labels.push(loopLabel);
  1609. var forAwait = false;
  1610. if (this.hasPlugin("asyncGenerators") && this.state.inAsync && this.isContextual("await")) {
  1611. forAwait = true;
  1612. this.next();
  1613. }
  1614. this.expect(types.parenL);
  1615. if (this.match(types.semi)) {
  1616. if (forAwait) {
  1617. this.unexpected();
  1618. }
  1619. return this.parseFor(node, null);
  1620. }
  1621. if (this.match(types._var) || this.match(types._let) || this.match(types._const)) {
  1622. var _init = this.startNode();
  1623. var varKind = this.state.type;
  1624. this.next();
  1625. this.parseVar(_init, true, varKind);
  1626. this.finishNode(_init, "VariableDeclaration");
  1627. if (this.match(types._in) || this.isContextual("of")) {
  1628. if (_init.declarations.length === 1 && !_init.declarations[0].init) {
  1629. return this.parseForIn(node, _init, forAwait);
  1630. }
  1631. }
  1632. if (forAwait) {
  1633. this.unexpected();
  1634. }
  1635. return this.parseFor(node, _init);
  1636. }
  1637. var refShorthandDefaultPos = { start: 0 };
  1638. var init = this.parseExpression(true, refShorthandDefaultPos);
  1639. if (this.match(types._in) || this.isContextual("of")) {
  1640. var description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  1641. this.toAssignable(init, undefined, description);
  1642. this.checkLVal(init, undefined, undefined, description);
  1643. return this.parseForIn(node, init, forAwait);
  1644. } else if (refShorthandDefaultPos.start) {
  1645. this.unexpected(refShorthandDefaultPos.start);
  1646. }
  1647. if (forAwait) {
  1648. this.unexpected();
  1649. }
  1650. return this.parseFor(node, init);
  1651. };
  1652. pp$1.parseFunctionStatement = function (node) {
  1653. this.next();
  1654. return this.parseFunction(node, true);
  1655. };
  1656. pp$1.parseIfStatement = function (node) {
  1657. this.next();
  1658. node.test = this.parseParenExpression();
  1659. node.consequent = this.parseStatement(false);
  1660. node.alternate = this.eat(types._else) ? this.parseStatement(false) : null;
  1661. return this.finishNode(node, "IfStatement");
  1662. };
  1663. pp$1.parseReturnStatement = function (node) {
  1664. if (!this.state.inFunction && !this.options.allowReturnOutsideFunction) {
  1665. this.raise(this.state.start, "'return' outside of function");
  1666. }
  1667. this.next();
  1668. // In `return` (and `break`/`continue`), the keywords with
  1669. // optional arguments, we eagerly look for a semicolon or the
  1670. // possibility to insert one.
  1671. if (this.isLineTerminator()) {
  1672. node.argument = null;
  1673. } else {
  1674. node.argument = this.parseExpression();
  1675. this.semicolon();
  1676. }
  1677. return this.finishNode(node, "ReturnStatement");
  1678. };
  1679. pp$1.parseSwitchStatement = function (node) {
  1680. this.next();
  1681. node.discriminant = this.parseParenExpression();
  1682. node.cases = [];
  1683. this.expect(types.braceL);
  1684. this.state.labels.push(switchLabel);
  1685. // Statements under must be grouped (by label) in SwitchCase
  1686. // nodes. `cur` is used to keep the node that we are currently
  1687. // adding statements to.
  1688. var cur = void 0;
  1689. for (var sawDefault; !this.match(types.braceR);) {
  1690. if (this.match(types._case) || this.match(types._default)) {
  1691. var isCase = this.match(types._case);
  1692. if (cur) this.finishNode(cur, "SwitchCase");
  1693. node.cases.push(cur = this.startNode());
  1694. cur.consequent = [];
  1695. this.next();
  1696. if (isCase) {
  1697. cur.test = this.parseExpression();
  1698. } else {
  1699. if (sawDefault) this.raise(this.state.lastTokStart, "Multiple default clauses");
  1700. sawDefault = true;
  1701. cur.test = null;
  1702. }
  1703. this.expect(types.colon);
  1704. } else {
  1705. if (cur) {
  1706. cur.consequent.push(this.parseStatement(true));
  1707. } else {
  1708. this.unexpected();
  1709. }
  1710. }
  1711. }
  1712. if (cur) this.finishNode(cur, "SwitchCase");
  1713. this.next(); // Closing brace
  1714. this.state.labels.pop();
  1715. return this.finishNode(node, "SwitchStatement");
  1716. };
  1717. pp$1.parseThrowStatement = function (node) {
  1718. this.next();
  1719. if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) this.raise(this.state.lastTokEnd, "Illegal newline after throw");
  1720. node.argument = this.parseExpression();
  1721. this.semicolon();
  1722. return this.finishNode(node, "ThrowStatement");
  1723. };
  1724. // Reused empty array added for node fields that are always empty.
  1725. var empty = [];
  1726. pp$1.parseTryStatement = function (node) {
  1727. this.next();
  1728. node.block = this.parseBlock();
  1729. node.handler = null;
  1730. if (this.match(types._catch)) {
  1731. var clause = this.startNode();
  1732. this.next();
  1733. this.expect(types.parenL);
  1734. clause.param = this.parseBindingAtom();
  1735. this.checkLVal(clause.param, true, Object.create(null), "catch clause");
  1736. this.expect(types.parenR);
  1737. clause.body = this.parseBlock();
  1738. node.handler = this.finishNode(clause, "CatchClause");
  1739. }
  1740. node.guardedHandlers = empty;
  1741. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  1742. if (!node.handler && !node.finalizer) {
  1743. this.raise(node.start, "Missing catch or finally clause");
  1744. }
  1745. return this.finishNode(node, "TryStatement");
  1746. };
  1747. pp$1.parseVarStatement = function (node, kind) {
  1748. this.next();
  1749. this.parseVar(node, false, kind);
  1750. this.semicolon();
  1751. return this.finishNode(node, "VariableDeclaration");
  1752. };
  1753. pp$1.parseWhileStatement = function (node) {
  1754. this.next();
  1755. node.test = this.parseParenExpression();
  1756. this.state.labels.push(loopLabel);
  1757. node.body = this.parseStatement(false);
  1758. this.state.labels.pop();
  1759. return this.finishNode(node, "WhileStatement");
  1760. };
  1761. pp$1.parseWithStatement = function (node) {
  1762. if (this.state.strict) this.raise(this.state.start, "'with' in strict mode");
  1763. this.next();
  1764. node.object = this.parseParenExpression();
  1765. node.body = this.parseStatement(false);
  1766. return this.finishNode(node, "WithStatement");
  1767. };
  1768. pp$1.parseEmptyStatement = function (node) {
  1769. this.next();
  1770. return this.finishNode(node, "EmptyStatement");
  1771. };
  1772. pp$1.parseLabeledStatement = function (node, maybeName, expr) {
  1773. for (var _iterator = this.state.labels, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  1774. var _ref;
  1775. if (_isArray) {
  1776. if (_i >= _iterator.length) break;
  1777. _ref = _iterator[_i++];
  1778. } else {
  1779. _i = _iterator.next();
  1780. if (_i.done) break;
  1781. _ref = _i.value;
  1782. }
  1783. var _label = _ref;
  1784. if (_label.name === maybeName) {
  1785. this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  1786. }
  1787. }
  1788. var kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  1789. for (var i = this.state.labels.length - 1; i >= 0; i--) {
  1790. var label = this.state.labels[i];
  1791. if (label.statementStart === node.start) {
  1792. label.statementStart = this.state.start;
  1793. label.kind = kind;
  1794. } else {
  1795. break;
  1796. }
  1797. }
  1798. this.state.labels.push({ name: maybeName, kind: kind, statementStart: this.state.start });
  1799. node.body = this.parseStatement(true);
  1800. this.state.labels.pop();
  1801. node.label = expr;
  1802. return this.finishNode(node, "LabeledStatement");
  1803. };
  1804. pp$1.parseExpressionStatement = function (node, expr) {
  1805. node.expression = expr;
  1806. this.semicolon();
  1807. return this.finishNode(node, "ExpressionStatement");
  1808. };
  1809. // Parse a semicolon-enclosed block of statements, handling `"use
  1810. // strict"` declarations when `allowStrict` is true (used for
  1811. // function bodies).
  1812. pp$1.parseBlock = function (allowDirectives) {
  1813. var node = this.startNode();
  1814. this.expect(types.braceL);
  1815. this.parseBlockBody(node, allowDirectives, false, types.braceR);
  1816. return this.finishNode(node, "BlockStatement");
  1817. };
  1818. pp$1.isValidDirective = function (stmt) {
  1819. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  1820. };
  1821. pp$1.parseBlockBody = function (node, allowDirectives, topLevel, end) {
  1822. node.body = [];
  1823. node.directives = [];
  1824. var parsedNonDirective = false;
  1825. var oldStrict = void 0;
  1826. var octalPosition = void 0;
  1827. while (!this.eat(end)) {
  1828. if (!parsedNonDirective && this.state.containsOctal && !octalPosition) {
  1829. octalPosition = this.state.octalPosition;
  1830. }
  1831. var stmt = this.parseStatement(true, topLevel);
  1832. if (allowDirectives && !parsedNonDirective && this.isValidDirective(stmt)) {
  1833. var directive = this.stmtToDirective(stmt);
  1834. node.directives.push(directive);
  1835. if (oldStrict === undefined && directive.value.value === "use strict") {
  1836. oldStrict = this.state.strict;
  1837. this.setStrict(true);
  1838. if (octalPosition) {
  1839. this.raise(octalPosition, "Octal literal in strict mode");
  1840. }
  1841. }
  1842. continue;
  1843. }
  1844. parsedNonDirective = true;
  1845. node.body.push(stmt);
  1846. }
  1847. if (oldStrict === false) {
  1848. this.setStrict(false);
  1849. }
  1850. };
  1851. // Parse a regular `for` loop. The disambiguation code in
  1852. // `parseStatement` will already have parsed the init statement or
  1853. // expression.
  1854. pp$1.parseFor = function (node, init) {
  1855. node.init = init;
  1856. this.expect(types.semi);
  1857. node.test = this.match(types.semi) ? null : this.parseExpression();
  1858. this.expect(types.semi);
  1859. node.update = this.match(types.parenR) ? null : this.parseExpression();
  1860. this.expect(types.parenR);
  1861. node.body = this.parseStatement(false);
  1862. this.state.labels.pop();
  1863. return this.finishNode(node, "ForStatement");
  1864. };
  1865. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  1866. // same from parser's perspective.
  1867. pp$1.parseForIn = function (node, init, forAwait) {
  1868. var type = void 0;
  1869. if (forAwait) {
  1870. this.eatContextual("of");
  1871. type = "ForAwaitStatement";
  1872. } else {
  1873. type = this.match(types._in) ? "ForInStatement" : "ForOfStatement";
  1874. this.next();
  1875. }
  1876. node.left = init;
  1877. node.right = this.parseExpression();
  1878. this.expect(types.parenR);
  1879. node.body = this.parseStatement(false);
  1880. this.state.labels.pop();
  1881. return this.finishNode(node, type);
  1882. };
  1883. // Parse a list of variable declarations.
  1884. pp$1.parseVar = function (node, isFor, kind) {
  1885. node.declarations = [];
  1886. node.kind = kind.keyword;
  1887. for (;;) {
  1888. var decl = this.startNode();
  1889. this.parseVarHead(decl);
  1890. if (this.eat(types.eq)) {
  1891. decl.init = this.parseMaybeAssign(isFor);
  1892. } else if (kind === types._const && !(this.match(types._in) || this.isContextual("of"))) {
  1893. this.unexpected();
  1894. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  1895. this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value");
  1896. } else {
  1897. decl.init = null;
  1898. }
  1899. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  1900. if (!this.eat(types.comma)) break;
  1901. }
  1902. return node;
  1903. };
  1904. pp$1.parseVarHead = function (decl) {
  1905. decl.id = this.parseBindingAtom();
  1906. this.checkLVal(decl.id, true, undefined, "variable declaration");
  1907. };
  1908. // Parse a function declaration or literal (depending on the
  1909. // `isStatement` parameter).
  1910. pp$1.parseFunction = function (node, isStatement, allowExpressionBody, isAsync, optionalId) {
  1911. var oldInMethod = this.state.inMethod;
  1912. this.state.inMethod = false;
  1913. this.initFunction(node, isAsync);
  1914. if (this.match(types.star)) {
  1915. if (node.async && !this.hasPlugin("asyncGenerators")) {
  1916. this.unexpected();
  1917. } else {
  1918. node.generator = true;
  1919. this.next();
  1920. }
  1921. }
  1922. if (isStatement && !optionalId && !this.match(types.name) && !this.match(types._yield)) {
  1923. this.unexpected();
  1924. }
  1925. if (this.match(types.name) || this.match(types._yield)) {
  1926. node.id = this.parseBindingIdentifier();
  1927. }
  1928. this.parseFunctionParams(node);
  1929. this.parseFunctionBody(node, allowExpressionBody);
  1930. this.state.inMethod = oldInMethod;
  1931. return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  1932. };
  1933. pp$1.parseFunctionParams = function (node) {
  1934. this.expect(types.parenL);
  1935. node.params = this.parseBindingList(types.parenR);
  1936. };
  1937. // Parse a class declaration or literal (depending on the
  1938. // `isStatement` parameter).
  1939. pp$1.parseClass = function (node, isStatement, optionalId) {
  1940. this.next();
  1941. this.takeDecorators(node);
  1942. this.parseClassId(node, isStatement, optionalId);
  1943. this.parseClassSuper(node);
  1944. this.parseClassBody(node);
  1945. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  1946. };
  1947. pp$1.isClassProperty = function () {
  1948. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  1949. };
  1950. pp$1.isClassMethod = function () {
  1951. return this.match(types.parenL);
  1952. };
  1953. pp$1.isNonstaticConstructor = function (method) {
  1954. return !method.computed && !method.static && (method.key.name === "constructor" || // Identifier
  1955. method.key.value === "constructor" // Literal
  1956. );
  1957. };
  1958. pp$1.parseClassBody = function (node) {
  1959. // class bodies are implicitly strict
  1960. var oldStrict = this.state.strict;
  1961. this.state.strict = true;
  1962. var hadConstructorCall = false;
  1963. var hadConstructor = false;
  1964. var decorators = [];
  1965. var classBody = this.startNode();
  1966. classBody.body = [];
  1967. this.expect(types.braceL);
  1968. while (!this.eat(types.braceR)) {
  1969. if (this.eat(types.semi)) {
  1970. if (decorators.length > 0) {
  1971. this.raise(this.state.lastTokEnd, "Decorators must not be followed by a semicolon");
  1972. }
  1973. continue;
  1974. }
  1975. if (this.match(types.at)) {
  1976. decorators.push(this.parseDecorator());
  1977. continue;
  1978. }
  1979. var method = this.startNode();
  1980. // steal the decorators if there are any
  1981. if (decorators.length) {
  1982. method.decorators = decorators;
  1983. decorators = [];
  1984. }
  1985. method.static = false;
  1986. if (this.match(types.name) && this.state.value === "static") {
  1987. var key = this.parseIdentifier(true); // eats 'static'
  1988. if (this.isClassMethod()) {
  1989. // a method named 'static'
  1990. method.kind = "method";
  1991. method.computed = false;
  1992. method.key = key;
  1993. this.parseClassMethod(classBody, method, false, false);
  1994. continue;
  1995. } else if (this.isClassProperty()) {
  1996. // a property named 'static'
  1997. method.computed = false;
  1998. method.key = key;
  1999. classBody.body.push(this.parseClassProperty(method));
  2000. continue;
  2001. }
  2002. // otherwise something static
  2003. method.static = true;
  2004. }
  2005. if (this.eat(types.star)) {
  2006. // a generator
  2007. method.kind = "method";
  2008. this.parsePropertyName(method);
  2009. if (this.isNonstaticConstructor(method)) {
  2010. this.raise(method.key.start, "Constructor can't be a generator");
  2011. }
  2012. if (!method.computed && method.static && (method.key.name === "prototype" || method.key.value === "prototype")) {
  2013. this.raise(method.key.start, "Classes may not have static property named prototype");
  2014. }
  2015. this.parseClassMethod(classBody, method, true, false);
  2016. } else {
  2017. var isSimple = this.match(types.name);
  2018. var _key = this.parsePropertyName(method);
  2019. if (!method.computed && method.static && (method.key.name === "prototype" || method.key.value === "prototype")) {
  2020. this.raise(method.key.start, "Classes may not have static property named prototype");
  2021. }
  2022. if (this.isClassMethod()) {
  2023. // a normal method
  2024. if (this.isNonstaticConstructor(method)) {
  2025. if (hadConstructor) {
  2026. this.raise(_key.start, "Duplicate constructor in the same class");
  2027. } else if (method.decorators) {
  2028. this.raise(method.start, "You can't attach decorators to a class constructor");
  2029. }
  2030. hadConstructor = true;
  2031. method.kind = "constructor";
  2032. } else {
  2033. method.kind = "method";
  2034. }
  2035. this.parseClassMethod(classBody, method, false, false);
  2036. } else if (this.isClassProperty()) {
  2037. // a normal property
  2038. if (this.isNonstaticConstructor(method)) {
  2039. this.raise(method.key.start, "Classes may not have a non-static field named 'constructor'");
  2040. }
  2041. classBody.body.push(this.parseClassProperty(method));
  2042. } else if (isSimple && _key.name === "async" && !this.isLineTerminator()) {
  2043. // an async method
  2044. var isGenerator = this.hasPlugin("asyncGenerators") && this.eat(types.star);
  2045. method.kind = "method";
  2046. this.parsePropertyName(method);
  2047. if (this.isNonstaticConstructor(method)) {
  2048. this.raise(method.key.start, "Constructor can't be an async function");
  2049. }
  2050. this.parseClassMethod(classBody, method, isGenerator, true);
  2051. } else if (isSimple && (_key.name === "get" || _key.name === "set") && !(this.isLineTerminator() && this.match(types.star))) {
  2052. // `get\n*` is an uninitialized property named 'get' followed by a generator.
  2053. // a getter or setter
  2054. method.kind = _key.name;
  2055. this.parsePropertyName(method);
  2056. if (this.isNonstaticConstructor(method)) {
  2057. this.raise(method.key.start, "Constructor can't have get/set modifier");
  2058. }
  2059. this.parseClassMethod(classBody, method, false, false);
  2060. this.checkGetterSetterParamCount(method);
  2061. } else if (this.hasPlugin("classConstructorCall") && isSimple && _key.name === "call" && this.match(types.name) && this.state.value === "constructor") {
  2062. // a (deprecated) call constructor
  2063. if (hadConstructorCall) {
  2064. this.raise(method.start, "Duplicate constructor call in the same class");
  2065. } else if (method.decorators) {
  2066. this.raise(method.start, "You can't attach decorators to a class constructor");
  2067. }
  2068. hadConstructorCall = true;
  2069. method.kind = "constructorCall";
  2070. this.parsePropertyName(method); // consume "constructor" and make it the method's name
  2071. this.parseClassMethod(classBody, method, false, false);
  2072. } else if (this.isLineTerminator()) {
  2073. // an uninitialized class property (due to ASI, since we don't otherwise recognize the next token)
  2074. if (this.isNonstaticConstructor(method)) {
  2075. this.raise(method.key.start, "Classes may not have a non-static field named 'constructor'");
  2076. }
  2077. classBody.body.push(this.parseClassProperty(method));
  2078. } else {
  2079. this.unexpected();
  2080. }
  2081. }
  2082. }
  2083. if (decorators.length) {
  2084. this.raise(this.state.start, "You have trailing decorators with no method");
  2085. }
  2086. node.body = this.finishNode(classBody, "ClassBody");
  2087. this.state.strict = oldStrict;
  2088. };
  2089. pp$1.parseClassProperty = function (node) {
  2090. this.state.inClassProperty = true;
  2091. if (this.match(types.eq)) {
  2092. if (!this.hasPlugin("classProperties")) this.unexpected();
  2093. this.next();
  2094. node.value = this.parseMaybeAssign();
  2095. } else {
  2096. node.value = null;
  2097. }
  2098. this.semicolon();
  2099. this.state.inClassProperty = false;
  2100. return this.finishNode(node, "ClassProperty");
  2101. };
  2102. pp$1.parseClassMethod = function (classBody, method, isGenerator, isAsync) {
  2103. this.parseMethod(method, isGenerator, isAsync);
  2104. classBody.body.push(this.finishNode(method, "ClassMethod"));
  2105. };
  2106. pp$1.parseClassId = function (node, isStatement, optionalId) {
  2107. if (this.match(types.name)) {
  2108. node.id = this.parseIdentifier();
  2109. } else {
  2110. if (optionalId || !isStatement) {
  2111. node.id = null;
  2112. } else {
  2113. this.unexpected();
  2114. }
  2115. }
  2116. };
  2117. pp$1.parseClassSuper = function (node) {
  2118. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  2119. };
  2120. // Parses module export declaration.
  2121. pp$1.parseExport = function (node) {
  2122. this.next();
  2123. // export * from '...'
  2124. if (this.match(types.star)) {
  2125. var specifier = this.startNode();
  2126. this.next();
  2127. if (this.hasPlugin("exportExtensions") && this.eatContextual("as")) {
  2128. specifier.exported = this.parseIdentifier();
  2129. node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")];
  2130. this.parseExportSpecifiersMaybe(node);
  2131. this.parseExportFrom(node, true);
  2132. } else {
  2133. this.parseExportFrom(node, true);
  2134. return this.finishNode(node, "ExportAllDeclaration");
  2135. }
  2136. } else if (this.hasPlugin("exportExtensions") && this.isExportDefaultSpecifier()) {
  2137. var _specifier = this.startNode();
  2138. _specifier.exported = this.parseIdentifier(true);
  2139. node.specifiers = [this.finishNode(_specifier, "ExportDefaultSpecifier")];
  2140. if (this.match(types.comma) && this.lookahead().type === types.star) {
  2141. this.expect(types.comma);
  2142. var _specifier2 = this.startNode();
  2143. this.expect(types.star);
  2144. this.expectContextual("as");
  2145. _specifier2.exported = this.parseIdentifier();
  2146. node.specifiers.push(this.finishNode(_specifier2, "ExportNamespaceSpecifier"));
  2147. } else {
  2148. this.parseExportSpecifiersMaybe(node);
  2149. }
  2150. this.parseExportFrom(node, true);
  2151. } else if (this.eat(types._default)) {
  2152. // export default ...
  2153. var expr = this.startNode();
  2154. var needsSemi = false;
  2155. if (this.eat(types._function)) {
  2156. expr = this.parseFunction(expr, true, false, false, true);
  2157. } else if (this.match(types._class)) {
  2158. expr = this.parseClass(expr, true, true);
  2159. } else {
  2160. needsSemi = true;
  2161. expr = this.parseMaybeAssign();
  2162. }
  2163. node.declaration = expr;
  2164. if (needsSemi) this.semicolon();
  2165. this.checkExport(node, true, true);
  2166. return this.finishNode(node, "ExportDefaultDeclaration");
  2167. } else if (this.shouldParseExportDeclaration()) {
  2168. node.specifiers = [];
  2169. node.source = null;
  2170. node.declaration = this.parseExportDeclaration(node);
  2171. } else {
  2172. // export { x, y as z } [from '...']
  2173. node.declaration = null;
  2174. node.specifiers = this.parseExportSpecifiers();
  2175. this.parseExportFrom(node);
  2176. }
  2177. this.checkExport(node, true);
  2178. return this.finishNode(node, "ExportNamedDeclaration");
  2179. };
  2180. pp$1.parseExportDeclaration = function () {
  2181. return this.parseStatement(true);
  2182. };
  2183. pp$1.isExportDefaultSpecifier = function () {
  2184. if (this.match(types.name)) {
  2185. return this.state.value !== "async";
  2186. }
  2187. if (!this.match(types._default)) {
  2188. return false;
  2189. }
  2190. var lookahead = this.lookahead();
  2191. return lookahead.type === types.comma || lookahead.type === types.name && lookahead.value === "from";
  2192. };
  2193. pp$1.parseExportSpecifiersMaybe = function (node) {
  2194. if (this.eat(types.comma)) {
  2195. node.specifiers = node.specifiers.concat(this.parseExportSpecifiers());
  2196. }
  2197. };
  2198. pp$1.parseExportFrom = function (node, expect) {
  2199. if (this.eatContextual("from")) {
  2200. node.source = this.match(types.string) ? this.parseExprAtom() : this.unexpected();
  2201. this.checkExport(node);
  2202. } else {
  2203. if (expect) {
  2204. this.unexpected();
  2205. } else {
  2206. node.source = null;
  2207. }
  2208. }
  2209. this.semicolon();
  2210. };
  2211. pp$1.shouldParseExportDeclaration = function () {
  2212. return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "let" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isContextual("async");
  2213. };
  2214. pp$1.checkExport = function (node, checkNames, isDefault) {
  2215. if (checkNames) {
  2216. // Check for duplicate exports
  2217. if (isDefault) {
  2218. // Default exports
  2219. this.checkDuplicateExports(node, "default");
  2220. } else if (node.specifiers && node.specifiers.length) {
  2221. // Named exports
  2222. for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
  2223. var _ref2;
  2224. if (_isArray2) {
  2225. if (_i2 >= _iterator2.length) break;
  2226. _ref2 = _iterator2[_i2++];
  2227. } else {
  2228. _i2 = _iterator2.next();
  2229. if (_i2.done) break;
  2230. _ref2 = _i2.value;
  2231. }
  2232. var specifier = _ref2;
  2233. this.checkDuplicateExports(specifier, specifier.exported.name);
  2234. }
  2235. } else if (node.declaration) {
  2236. // Exported declarations
  2237. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  2238. this.checkDuplicateExports(node, node.declaration.id.name);
  2239. } else if (node.declaration.type === "VariableDeclaration") {
  2240. for (var _iterator3 = node.declaration.declarations, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
  2241. var _ref3;
  2242. if (_isArray3) {
  2243. if (_i3 >= _iterator3.length) break;
  2244. _ref3 = _iterator3[_i3++];
  2245. } else {
  2246. _i3 = _iterator3.next();
  2247. if (_i3.done) break;
  2248. _ref3 = _i3.value;
  2249. }
  2250. var declaration = _ref3;
  2251. this.checkDeclaration(declaration.id);
  2252. }
  2253. }
  2254. }
  2255. }
  2256. if (this.state.decorators.length) {
  2257. var isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
  2258. if (!node.declaration || !isClass) {
  2259. this.raise(node.start, "You can only use decorators on an export when exporting a class");
  2260. }
  2261. this.takeDecorators(node.declaration);
  2262. }
  2263. };
  2264. pp$1.checkDeclaration = function (node) {
  2265. if (node.type === "ObjectPattern") {
  2266. for (var _iterator4 = node.properties, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
  2267. var _ref4;
  2268. if (_isArray4) {
  2269. if (_i4 >= _iterator4.length) break;
  2270. _ref4 = _iterator4[_i4++];
  2271. } else {
  2272. _i4 = _iterator4.next();
  2273. if (_i4.done) break;
  2274. _ref4 = _i4.value;
  2275. }
  2276. var prop = _ref4;
  2277. this.checkDeclaration(prop);
  2278. }
  2279. } else if (node.type === "ArrayPattern") {
  2280. for (var _iterator5 = node.elements, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
  2281. var _ref5;
  2282. if (_isArray5) {
  2283. if (_i5 >= _iterator5.length) break;
  2284. _ref5 = _iterator5[_i5++];
  2285. } else {
  2286. _i5 = _iterator5.next();
  2287. if (_i5.done) break;
  2288. _ref5 = _i5.value;
  2289. }
  2290. var elem = _ref5;
  2291. if (elem) {
  2292. this.checkDeclaration(elem);
  2293. }
  2294. }
  2295. } else if (node.type === "ObjectProperty") {
  2296. this.checkDeclaration(node.value);
  2297. } else if (node.type === "RestElement" || node.type === "RestProperty") {
  2298. this.checkDeclaration(node.argument);
  2299. } else if (node.type === "Identifier") {
  2300. this.checkDuplicateExports(node, node.name);
  2301. }
  2302. };
  2303. pp$1.checkDuplicateExports = function (node, name) {
  2304. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  2305. this.raiseDuplicateExportError(node, name);
  2306. }
  2307. this.state.exportedIdentifiers.push(name);
  2308. };
  2309. pp$1.raiseDuplicateExportError = function (node, name) {
  2310. this.raise(node.start, name === "default" ? "Only one default export allowed per module." : "`" + name + "` has already been exported. Exported identifiers must be unique.");
  2311. };
  2312. // Parses a comma-separated list of module exports.
  2313. pp$1.parseExportSpecifiers = function () {
  2314. var nodes = [];
  2315. var first = true;
  2316. var needsFrom = void 0;
  2317. // export { x, y as z } [from '...']
  2318. this.expect(types.braceL);
  2319. while (!this.eat(types.braceR)) {
  2320. if (first) {
  2321. first = false;
  2322. } else {
  2323. this.expect(types.comma);
  2324. if (this.eat(types.braceR)) break;
  2325. }
  2326. var isDefault = this.match(types._default);
  2327. if (isDefault && !needsFrom) needsFrom = true;
  2328. var node = this.startNode();
  2329. node.local = this.parseIdentifier(isDefault);
  2330. node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
  2331. nodes.push(this.finishNode(node, "ExportSpecifier"));
  2332. }
  2333. // https://github.com/ember-cli/ember-cli/pull/3739
  2334. if (needsFrom && !this.isContextual("from")) {
  2335. this.unexpected();
  2336. }
  2337. return nodes;
  2338. };
  2339. // Parses import declaration.
  2340. pp$1.parseImport = function (node) {
  2341. this.eat(types._import);
  2342. // import '...'
  2343. if (this.match(types.string)) {
  2344. node.specifiers = [];
  2345. node.source = this.parseExprAtom();
  2346. } else {
  2347. node.specifiers = [];
  2348. this.parseImportSpecifiers(node);
  2349. this.expectContextual("from");
  2350. node.source = this.match(types.string) ? this.parseExprAtom() : this.unexpected();
  2351. }
  2352. this.semicolon();
  2353. return this.finishNode(node, "ImportDeclaration");
  2354. };
  2355. // Parses a comma-separated list of module imports.
  2356. pp$1.parseImportSpecifiers = function (node) {
  2357. var first = true;
  2358. if (this.match(types.name)) {
  2359. // import defaultObj, { x, y as z } from '...'
  2360. var startPos = this.state.start;
  2361. var startLoc = this.state.startLoc;
  2362. node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(), startPos, startLoc));
  2363. if (!this.eat(types.comma)) return;
  2364. }
  2365. if (this.match(types.star)) {
  2366. var specifier = this.startNode();
  2367. this.next();
  2368. this.expectContextual("as");
  2369. specifier.local = this.parseIdentifier();
  2370. this.checkLVal(specifier.local, true, undefined, "import namespace specifier");
  2371. node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier"));
  2372. return;
  2373. }
  2374. this.expect(types.braceL);
  2375. while (!this.eat(types.braceR)) {
  2376. if (first) {
  2377. first = false;
  2378. } else {
  2379. // Detect an attempt to deep destructure
  2380. if (this.eat(types.colon)) {
  2381. this.unexpected(null, "ES2015 named imports do not destructure. Use another statement for destructuring after the import.");
  2382. }
  2383. this.expect(types.comma);
  2384. if (this.eat(types.braceR)) break;
  2385. }
  2386. this.parseImportSpecifier(node);
  2387. }
  2388. };
  2389. pp$1.parseImportSpecifier = function (node) {
  2390. var specifier = this.startNode();
  2391. specifier.imported = this.parseIdentifier(true);
  2392. if (this.eatContextual("as")) {
  2393. specifier.local = this.parseIdentifier();
  2394. } else {
  2395. this.checkReservedWord(specifier.imported.name, specifier.start, true, true);
  2396. specifier.local = specifier.imported.__clone();
  2397. }
  2398. this.checkLVal(specifier.local, true, undefined, "import specifier");
  2399. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  2400. };
  2401. pp$1.parseImportSpecifierDefault = function (id, startPos, startLoc) {
  2402. var node = this.startNodeAt(startPos, startLoc);
  2403. node.local = id;
  2404. this.checkLVal(node.local, true, undefined, "default import specifier");
  2405. return this.finishNode(node, "ImportDefaultSpecifier");
  2406. };
  2407. var pp$2 = Parser.prototype;
  2408. // Convert existing expression atom to assignable pattern
  2409. // if possible.
  2410. pp$2.toAssignable = function (node, isBinding, contextDescription) {
  2411. if (node) {
  2412. switch (node.type) {
  2413. case "Identifier":
  2414. case "ObjectPattern":
  2415. case "ArrayPattern":
  2416. case "AssignmentPattern":
  2417. break;
  2418. case "ObjectExpression":
  2419. node.type = "ObjectPattern";
  2420. for (var _iterator = node.properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  2421. var _ref;
  2422. if (_isArray) {
  2423. if (_i >= _iterator.length) break;
  2424. _ref = _iterator[_i++];
  2425. } else {
  2426. _i = _iterator.next();
  2427. if (_i.done) break;
  2428. _ref = _i.value;
  2429. }
  2430. var prop = _ref;
  2431. if (prop.type === "ObjectMethod") {
  2432. if (prop.kind === "get" || prop.kind === "set") {
  2433. this.raise(prop.key.start, "Object pattern can't contain getter or setter");
  2434. } else {
  2435. this.raise(prop.key.start, "Object pattern can't contain methods");
  2436. }
  2437. } else {
  2438. this.toAssignable(prop, isBinding, "object destructuring pattern");
  2439. }
  2440. }
  2441. break;
  2442. case "ObjectProperty":
  2443. this.toAssignable(node.value, isBinding, contextDescription);
  2444. break;
  2445. case "SpreadProperty":
  2446. node.type = "RestProperty";
  2447. var arg = node.argument;
  2448. this.toAssignable(arg, isBinding, contextDescription);
  2449. break;
  2450. case "ArrayExpression":
  2451. node.type = "ArrayPattern";
  2452. this.toAssignableList(node.elements, isBinding, contextDescription);
  2453. break;
  2454. case "AssignmentExpression":
  2455. if (node.operator === "=") {
  2456. node.type = "AssignmentPattern";
  2457. delete node.operator;
  2458. } else {
  2459. this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
  2460. }
  2461. break;
  2462. case "MemberExpression":
  2463. if (!isBinding) break;
  2464. default:
  2465. {
  2466. var message = "Invalid left-hand side" + (contextDescription ? " in " + contextDescription : /* istanbul ignore next */"expression");
  2467. this.raise(node.start, message);
  2468. }
  2469. }
  2470. }
  2471. return node;
  2472. };
  2473. // Convert list of expression atoms to binding list.
  2474. pp$2.toAssignableList = function (exprList, isBinding, contextDescription) {
  2475. var end = exprList.length;
  2476. if (end) {
  2477. var last = exprList[end - 1];
  2478. if (last && last.type === "RestElement") {
  2479. --end;
  2480. } else if (last && last.type === "SpreadElement") {
  2481. last.type = "RestElement";
  2482. var arg = last.argument;
  2483. this.toAssignable(arg, isBinding, contextDescription);
  2484. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") {
  2485. this.unexpected(arg.start);
  2486. }
  2487. --end;
  2488. }
  2489. }
  2490. for (var i = 0; i < end; i++) {
  2491. var elt = exprList[i];
  2492. if (elt) this.toAssignable(elt, isBinding, contextDescription);
  2493. }
  2494. return exprList;
  2495. };
  2496. // Convert list of expression atoms to a list of
  2497. pp$2.toReferencedList = function (exprList) {
  2498. return exprList;
  2499. };
  2500. // Parses spread element.
  2501. pp$2.parseSpread = function (refShorthandDefaultPos) {
  2502. var node = this.startNode();
  2503. this.next();
  2504. node.argument = this.parseMaybeAssign(false, refShorthandDefaultPos);
  2505. return this.finishNode(node, "SpreadElement");
  2506. };
  2507. pp$2.parseRest = function () {
  2508. var node = this.startNode();
  2509. this.next();
  2510. node.argument = this.parseBindingIdentifier();
  2511. return this.finishNode(node, "RestElement");
  2512. };
  2513. pp$2.shouldAllowYieldIdentifier = function () {
  2514. return this.match(types._yield) && !this.state.strict && !this.state.inGenerator;
  2515. };
  2516. pp$2.parseBindingIdentifier = function () {
  2517. return this.parseIdentifier(this.shouldAllowYieldIdentifier());
  2518. };
  2519. // Parses lvalue (assignable) atom.
  2520. pp$2.parseBindingAtom = function () {
  2521. switch (this.state.type) {
  2522. case types._yield:
  2523. if (this.state.strict || this.state.inGenerator) this.unexpected();
  2524. // fall-through
  2525. case types.name:
  2526. return this.parseIdentifier(true);
  2527. case types.bracketL:
  2528. var node = this.startNode();
  2529. this.next();
  2530. node.elements = this.parseBindingList(types.bracketR, true);
  2531. return this.finishNode(node, "ArrayPattern");
  2532. case types.braceL:
  2533. return this.parseObj(true);
  2534. default:
  2535. this.unexpected();
  2536. }
  2537. };
  2538. pp$2.parseBindingList = function (close, allowEmpty) {
  2539. var elts = [];
  2540. var first = true;
  2541. while (!this.eat(close)) {
  2542. if (first) {
  2543. first = false;
  2544. } else {
  2545. this.expect(types.comma);
  2546. }
  2547. if (allowEmpty && this.match(types.comma)) {
  2548. elts.push(null);
  2549. } else if (this.eat(close)) {
  2550. break;
  2551. } else if (this.match(types.ellipsis)) {
  2552. elts.push(this.parseAssignableListItemTypes(this.parseRest()));
  2553. this.expect(close);
  2554. break;
  2555. } else {
  2556. var decorators = [];
  2557. while (this.match(types.at)) {
  2558. decorators.push(this.parseDecorator());
  2559. }
  2560. var left = this.parseMaybeDefault();
  2561. if (decorators.length) {
  2562. left.decorators = decorators;
  2563. }
  2564. this.parseAssignableListItemTypes(left);
  2565. elts.push(this.parseMaybeDefault(left.start, left.loc.start, left));
  2566. }
  2567. }
  2568. return elts;
  2569. };
  2570. pp$2.parseAssignableListItemTypes = function (param) {
  2571. return param;
  2572. };
  2573. // Parses assignment pattern around given atom if possible.
  2574. pp$2.parseMaybeDefault = function (startPos, startLoc, left) {
  2575. startLoc = startLoc || this.state.startLoc;
  2576. startPos = startPos || this.state.start;
  2577. left = left || this.parseBindingAtom();
  2578. if (!this.eat(types.eq)) return left;
  2579. var node = this.startNodeAt(startPos, startLoc);
  2580. node.left = left;
  2581. node.right = this.parseMaybeAssign();
  2582. return this.finishNode(node, "AssignmentPattern");
  2583. };
  2584. // Verify that a node is an lval — something that can be assigned
  2585. // to.
  2586. pp$2.checkLVal = function (expr, isBinding, checkClashes, contextDescription) {
  2587. switch (expr.type) {
  2588. case "Identifier":
  2589. this.checkReservedWord(expr.name, expr.start, false, true);
  2590. if (checkClashes) {
  2591. // we need to prefix this with an underscore for the cases where we have a key of
  2592. // `__proto__`. there's a bug in old V8 where the following wouldn't work:
  2593. //
  2594. // > var obj = Object.create(null);
  2595. // undefined
  2596. // > obj.__proto__
  2597. // null
  2598. // > obj.__proto__ = true;
  2599. // true
  2600. // > obj.__proto__
  2601. // null
  2602. var key = "_" + expr.name;
  2603. if (checkClashes[key]) {
  2604. this.raise(expr.start, "Argument name clash in strict mode");
  2605. } else {
  2606. checkClashes[key] = true;
  2607. }
  2608. }
  2609. break;
  2610. case "MemberExpression":
  2611. if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
  2612. break;
  2613. case "ObjectPattern":
  2614. for (var _iterator2 = expr.properties, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
  2615. var _ref2;
  2616. if (_isArray2) {
  2617. if (_i2 >= _iterator2.length) break;
  2618. _ref2 = _iterator2[_i2++];
  2619. } else {
  2620. _i2 = _iterator2.next();
  2621. if (_i2.done) break;
  2622. _ref2 = _i2.value;
  2623. }
  2624. var prop = _ref2;
  2625. if (prop.type === "ObjectProperty") prop = prop.value;
  2626. this.checkLVal(prop, isBinding, checkClashes, "object destructuring pattern");
  2627. }
  2628. break;
  2629. case "ArrayPattern":
  2630. for (var _iterator3 = expr.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
  2631. var _ref3;
  2632. if (_isArray3) {
  2633. if (_i3 >= _iterator3.length) break;
  2634. _ref3 = _iterator3[_i3++];
  2635. } else {
  2636. _i3 = _iterator3.next();
  2637. if (_i3.done) break;
  2638. _ref3 = _i3.value;
  2639. }
  2640. var elem = _ref3;
  2641. if (elem) this.checkLVal(elem, isBinding, checkClashes, "array destructuring pattern");
  2642. }
  2643. break;
  2644. case "AssignmentPattern":
  2645. this.checkLVal(expr.left, isBinding, checkClashes, "assignment pattern");
  2646. break;
  2647. case "RestProperty":
  2648. this.checkLVal(expr.argument, isBinding, checkClashes, "rest property");
  2649. break;
  2650. case "RestElement":
  2651. this.checkLVal(expr.argument, isBinding, checkClashes, "rest element");
  2652. break;
  2653. default:
  2654. {
  2655. var message = (isBinding ? /* istanbul ignore next */"Binding invalid" : "Invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : /* istanbul ignore next */"expression");
  2656. this.raise(expr.start, message);
  2657. }
  2658. }
  2659. };
  2660. /* eslint max-len: 0 */
  2661. // A recursive descent parser operates by defining functions for all
  2662. // syntactic elements, and recursively calling those, each function
  2663. // advancing the input stream and returning an AST node. Precedence
  2664. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  2665. // instead of `(!x)[1]` is handled by the fact that the parser
  2666. // function that parses unary prefix operators is called first, and
  2667. // in turn calls the function that parses `[]` subscripts — that
  2668. // way, it'll receive the node for `x[1]` already parsed, and wraps
  2669. // *that* in the unary operator node.
  2670. //
  2671. // Acorn uses an [operator precedence parser][opp] to handle binary
  2672. // operator precedence, because it is much more compact than using
  2673. // the technique outlined above, which uses different, nesting
  2674. // functions to specify precedence, for all of the ten binary
  2675. // precedence levels that JavaScript defines.
  2676. //
  2677. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  2678. var pp$3 = Parser.prototype;
  2679. // Check if property name clashes with already added.
  2680. // Object/class getters and setters are not allowed to clash —
  2681. // either with each other or with an init property — and in
  2682. // strict mode, init properties are also not allowed to be repeated.
  2683. pp$3.checkPropClash = function (prop, propHash) {
  2684. if (prop.computed || prop.kind) return;
  2685. var key = prop.key;
  2686. // It is either an Identifier or a String/NumericLiteral
  2687. var name = key.type === "Identifier" ? key.name : String(key.value);
  2688. if (name === "__proto__") {
  2689. if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
  2690. propHash.proto = true;
  2691. }
  2692. };
  2693. // Convenience method to parse an Expression only
  2694. pp$3.getExpression = function () {
  2695. this.nextToken();
  2696. var expr = this.parseExpression();
  2697. if (!this.match(types.eof)) {
  2698. this.unexpected();
  2699. }
  2700. return expr;
  2701. };
  2702. // ### Expression parsing
  2703. // These nest, from the most general expression type at the top to
  2704. // 'atomic', nondivisible expression types at the bottom. Most of
  2705. // the functions will simply let the function (s) below them parse,
  2706. // and, *if* the syntactic construct they handle is present, wrap
  2707. // the AST node that the inner parser gave them in another node.
  2708. // Parse a full expression. The optional arguments are used to
  2709. // forbid the `in` operator (in for loops initialization expressions)
  2710. // and provide reference for storing '=' operator inside shorthand
  2711. // property assignment in contexts where both object expression
  2712. // and object pattern might appear (so it's possible to raise
  2713. // delayed syntax error at correct position).
  2714. pp$3.parseExpression = function (noIn, refShorthandDefaultPos) {
  2715. var startPos = this.state.start;
  2716. var startLoc = this.state.startLoc;
  2717. var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
  2718. if (this.match(types.comma)) {
  2719. var node = this.startNodeAt(startPos, startLoc);
  2720. node.expressions = [expr];
  2721. while (this.eat(types.comma)) {
  2722. node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
  2723. }
  2724. this.toReferencedList(node.expressions);
  2725. return this.finishNode(node, "SequenceExpression");
  2726. }
  2727. return expr;
  2728. };
  2729. // Parse an assignment expression. This includes applications of
  2730. // operators like `+=`.
  2731. pp$3.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) {
  2732. var startPos = this.state.start;
  2733. var startLoc = this.state.startLoc;
  2734. if (this.match(types._yield) && this.state.inGenerator) {
  2735. var _left = this.parseYield();
  2736. if (afterLeftParse) _left = afterLeftParse.call(this, _left, startPos, startLoc);
  2737. return _left;
  2738. }
  2739. var failOnShorthandAssign = void 0;
  2740. if (refShorthandDefaultPos) {
  2741. failOnShorthandAssign = false;
  2742. } else {
  2743. refShorthandDefaultPos = { start: 0 };
  2744. failOnShorthandAssign = true;
  2745. }
  2746. if (this.match(types.parenL) || this.match(types.name)) {
  2747. this.state.potentialArrowAt = this.state.start;
  2748. }
  2749. var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos);
  2750. if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
  2751. if (this.state.type.isAssign) {
  2752. var node = this.startNodeAt(startPos, startLoc);
  2753. node.operator = this.state.value;
  2754. node.left = this.match(types.eq) ? this.toAssignable(left, undefined, "assignment expression") : left;
  2755. refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly
  2756. this.checkLVal(left, undefined, undefined, "assignment expression");
  2757. if (left.extra && left.extra.parenthesized) {
  2758. var errorMsg = void 0;
  2759. if (left.type === "ObjectPattern") {
  2760. errorMsg = "`({a}) = 0` use `({a} = 0)`";
  2761. } else if (left.type === "ArrayPattern") {
  2762. errorMsg = "`([a]) = 0` use `([a] = 0)`";
  2763. }
  2764. if (errorMsg) {
  2765. this.raise(left.start, "You're trying to assign to a parenthesized expression, eg. instead of " + errorMsg);
  2766. }
  2767. }
  2768. this.next();
  2769. node.right = this.parseMaybeAssign(noIn);
  2770. return this.finishNode(node, "AssignmentExpression");
  2771. } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
  2772. this.unexpected(refShorthandDefaultPos.start);
  2773. }
  2774. return left;
  2775. };
  2776. // Parse a ternary conditional (`?:`) operator.
  2777. pp$3.parseMaybeConditional = function (noIn, refShorthandDefaultPos, refNeedsArrowPos) {
  2778. var startPos = this.state.start;
  2779. var startLoc = this.state.startLoc;
  2780. var expr = this.parseExprOps(noIn, refShorthandDefaultPos);
  2781. if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
  2782. return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
  2783. };
  2784. pp$3.parseConditional = function (expr, noIn, startPos, startLoc) {
  2785. if (this.eat(types.question)) {
  2786. var node = this.startNodeAt(startPos, startLoc);
  2787. node.test = expr;
  2788. node.consequent = this.parseMaybeAssign();
  2789. this.expect(types.colon);
  2790. node.alternate = this.parseMaybeAssign(noIn);
  2791. return this.finishNode(node, "ConditionalExpression");
  2792. }
  2793. return expr;
  2794. };
  2795. // Start the precedence parser.
  2796. pp$3.parseExprOps = function (noIn, refShorthandDefaultPos) {
  2797. var startPos = this.state.start;
  2798. var startLoc = this.state.startLoc;
  2799. var expr = this.parseMaybeUnary(refShorthandDefaultPos);
  2800. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  2801. return expr;
  2802. } else {
  2803. return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  2804. }
  2805. };
  2806. // Parse binary operators with the operator precedence parsing
  2807. // algorithm. `left` is the left-hand side of the operator.
  2808. // `minPrec` provides context that allows the function to stop and
  2809. // defer further parser to one of its callers when it encounters an
  2810. // operator that has a lower precedence than the set it is parsing.
  2811. pp$3.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
  2812. var prec = this.state.type.binop;
  2813. if (prec != null && (!noIn || !this.match(types._in))) {
  2814. if (prec > minPrec) {
  2815. var node = this.startNodeAt(leftStartPos, leftStartLoc);
  2816. node.left = left;
  2817. node.operator = this.state.value;
  2818. if (node.operator === "**" && left.type === "UnaryExpression" && left.extra && !left.extra.parenthesizedArgument && !left.extra.parenthesized) {
  2819. this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");
  2820. }
  2821. var op = this.state.type;
  2822. this.next();
  2823. var startPos = this.state.start;
  2824. var startLoc = this.state.startLoc;
  2825. node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
  2826. this.finishNode(node, op === types.logicalOR || op === types.logicalAND ? "LogicalExpression" : "BinaryExpression");
  2827. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
  2828. }
  2829. }
  2830. return left;
  2831. };
  2832. // Parse unary operators, both prefix and postfix.
  2833. pp$3.parseMaybeUnary = function (refShorthandDefaultPos) {
  2834. if (this.state.type.prefix) {
  2835. var node = this.startNode();
  2836. var update = this.match(types.incDec);
  2837. node.operator = this.state.value;
  2838. node.prefix = true;
  2839. this.next();
  2840. var argType = this.state.type;
  2841. node.argument = this.parseMaybeUnary();
  2842. this.addExtra(node, "parenthesizedArgument", argType === types.parenL && (!node.argument.extra || !node.argument.extra.parenthesized));
  2843. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  2844. this.unexpected(refShorthandDefaultPos.start);
  2845. }
  2846. if (update) {
  2847. this.checkLVal(node.argument, undefined, undefined, "prefix operation");
  2848. } else if (this.state.strict && node.operator === "delete" && node.argument.type === "Identifier") {
  2849. this.raise(node.start, "Deleting local variable in strict mode");
  2850. }
  2851. return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  2852. }
  2853. var startPos = this.state.start;
  2854. var startLoc = this.state.startLoc;
  2855. var expr = this.parseExprSubscripts(refShorthandDefaultPos);
  2856. if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
  2857. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  2858. var _node = this.startNodeAt(startPos, startLoc);
  2859. _node.operator = this.state.value;
  2860. _node.prefix = false;
  2861. _node.argument = expr;
  2862. this.checkLVal(expr, undefined, undefined, "postfix operation");
  2863. this.next();
  2864. expr = this.finishNode(_node, "UpdateExpression");
  2865. }
  2866. return expr;
  2867. };
  2868. // Parse call, dot, and `[]`-subscript expressions.
  2869. pp$3.parseExprSubscripts = function (refShorthandDefaultPos) {
  2870. var startPos = this.state.start;
  2871. var startLoc = this.state.startLoc;
  2872. var potentialArrowAt = this.state.potentialArrowAt;
  2873. var expr = this.parseExprAtom(refShorthandDefaultPos);
  2874. if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
  2875. return expr;
  2876. }
  2877. if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
  2878. return expr;
  2879. }
  2880. return this.parseSubscripts(expr, startPos, startLoc);
  2881. };
  2882. pp$3.parseSubscripts = function (base, startPos, startLoc, noCalls) {
  2883. for (;;) {
  2884. if (!noCalls && this.eat(types.doubleColon)) {
  2885. var node = this.startNodeAt(startPos, startLoc);
  2886. node.object = base;
  2887. node.callee = this.parseNoCallExpr();
  2888. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  2889. } else if (this.eat(types.dot)) {
  2890. var _node2 = this.startNodeAt(startPos, startLoc);
  2891. _node2.object = base;
  2892. _node2.property = this.parseIdentifier(true);
  2893. _node2.computed = false;
  2894. base = this.finishNode(_node2, "MemberExpression");
  2895. } else if (this.eat(types.bracketL)) {
  2896. var _node3 = this.startNodeAt(startPos, startLoc);
  2897. _node3.object = base;
  2898. _node3.property = this.parseExpression();
  2899. _node3.computed = true;
  2900. this.expect(types.bracketR);
  2901. base = this.finishNode(_node3, "MemberExpression");
  2902. } else if (!noCalls && this.match(types.parenL)) {
  2903. var possibleAsync = this.state.potentialArrowAt === base.start && base.type === "Identifier" && base.name === "async" && !this.canInsertSemicolon();
  2904. this.next();
  2905. var _node4 = this.startNodeAt(startPos, startLoc);
  2906. _node4.callee = base;
  2907. _node4.arguments = this.parseCallExpressionArguments(types.parenR, possibleAsync);
  2908. if (_node4.callee.type === "Import" && _node4.arguments.length !== 1) {
  2909. this.raise(_node4.start, "import() requires exactly one argument");
  2910. }
  2911. base = this.finishNode(_node4, "CallExpression");
  2912. if (possibleAsync && this.shouldParseAsyncArrow()) {
  2913. return this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), _node4);
  2914. } else {
  2915. this.toReferencedList(_node4.arguments);
  2916. }
  2917. } else if (this.match(types.backQuote)) {
  2918. var _node5 = this.startNodeAt(startPos, startLoc);
  2919. _node5.tag = base;
  2920. _node5.quasi = this.parseTemplate(true);
  2921. base = this.finishNode(_node5, "TaggedTemplateExpression");
  2922. } else {
  2923. return base;
  2924. }
  2925. }
  2926. };
  2927. pp$3.parseCallExpressionArguments = function (close, possibleAsyncArrow) {
  2928. var elts = [];
  2929. var innerParenStart = void 0;
  2930. var first = true;
  2931. while (!this.eat(close)) {
  2932. if (first) {
  2933. first = false;
  2934. } else {
  2935. this.expect(types.comma);
  2936. if (this.eat(close)) break;
  2937. }
  2938. // we need to make sure that if this is an async arrow functions, that we don't allow inner parens inside the params
  2939. if (this.match(types.parenL) && !innerParenStart) {
  2940. innerParenStart = this.state.start;
  2941. }
  2942. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? { start: 0 } : undefined, possibleAsyncArrow ? { start: 0 } : undefined));
  2943. }
  2944. // we found an async arrow function so let's not allow any inner parens
  2945. if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
  2946. this.unexpected();
  2947. }
  2948. return elts;
  2949. };
  2950. pp$3.shouldParseAsyncArrow = function () {
  2951. return this.match(types.arrow);
  2952. };
  2953. pp$3.parseAsyncArrowFromCallExpression = function (node, call) {
  2954. this.expect(types.arrow);
  2955. return this.parseArrowExpression(node, call.arguments, true);
  2956. };
  2957. // Parse a no-call expression (like argument of `new` or `::` operators).
  2958. pp$3.parseNoCallExpr = function () {
  2959. var startPos = this.state.start;
  2960. var startLoc = this.state.startLoc;
  2961. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  2962. };
  2963. // Parse an atomic expression — either a single token that is an
  2964. // expression, an expression started by a keyword like `function` or
  2965. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  2966. // or `{}`.
  2967. pp$3.parseExprAtom = function (refShorthandDefaultPos) {
  2968. var canBeArrow = this.state.potentialArrowAt === this.state.start;
  2969. var node = void 0;
  2970. switch (this.state.type) {
  2971. case types._super:
  2972. if (!this.state.inMethod && !this.state.inClassProperty && !this.options.allowSuperOutsideMethod) {
  2973. this.raise(this.state.start, "'super' outside of function or class");
  2974. }
  2975. node = this.startNode();
  2976. this.next();
  2977. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  2978. this.unexpected();
  2979. }
  2980. if (this.match(types.parenL) && this.state.inMethod !== "constructor" && !this.options.allowSuperOutsideMethod) {
  2981. this.raise(node.start, "super() outside of class constructor");
  2982. }
  2983. return this.finishNode(node, "Super");
  2984. case types._import:
  2985. if (!this.hasPlugin("dynamicImport")) this.unexpected();
  2986. node = this.startNode();
  2987. this.next();
  2988. if (!this.match(types.parenL)) {
  2989. this.unexpected(null, types.parenL);
  2990. }
  2991. return this.finishNode(node, "Import");
  2992. case types._this:
  2993. node = this.startNode();
  2994. this.next();
  2995. return this.finishNode(node, "ThisExpression");
  2996. case types._yield:
  2997. if (this.state.inGenerator) this.unexpected();
  2998. case types.name:
  2999. node = this.startNode();
  3000. var allowAwait = this.state.value === "await" && this.state.inAsync;
  3001. var allowYield = this.shouldAllowYieldIdentifier();
  3002. var id = this.parseIdentifier(allowAwait || allowYield);
  3003. if (id.name === "await") {
  3004. if (this.state.inAsync || this.inModule) {
  3005. return this.parseAwait(node);
  3006. }
  3007. } else if (id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) {
  3008. this.next();
  3009. return this.parseFunction(node, false, false, true);
  3010. } else if (canBeArrow && id.name === "async" && this.match(types.name)) {
  3011. var params = [this.parseIdentifier()];
  3012. this.expect(types.arrow);
  3013. // let foo = bar => {};
  3014. return this.parseArrowExpression(node, params, true);
  3015. }
  3016. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  3017. return this.parseArrowExpression(node, [id]);
  3018. }
  3019. return id;
  3020. case types._do:
  3021. if (this.hasPlugin("doExpressions")) {
  3022. var _node6 = this.startNode();
  3023. this.next();
  3024. var oldInFunction = this.state.inFunction;
  3025. var oldLabels = this.state.labels;
  3026. this.state.labels = [];
  3027. this.state.inFunction = false;
  3028. _node6.body = this.parseBlock(false, true);
  3029. this.state.inFunction = oldInFunction;
  3030. this.state.labels = oldLabels;
  3031. return this.finishNode(_node6, "DoExpression");
  3032. }
  3033. case types.regexp:
  3034. var value = this.state.value;
  3035. node = this.parseLiteral(value.value, "RegExpLiteral");
  3036. node.pattern = value.pattern;
  3037. node.flags = value.flags;
  3038. return node;
  3039. case types.num:
  3040. return this.parseLiteral(this.state.value, "NumericLiteral");
  3041. case types.string:
  3042. return this.parseLiteral(this.state.value, "StringLiteral");
  3043. case types._null:
  3044. node = this.startNode();
  3045. this.next();
  3046. return this.finishNode(node, "NullLiteral");
  3047. case types._true:case types._false:
  3048. node = this.startNode();
  3049. node.value = this.match(types._true);
  3050. this.next();
  3051. return this.finishNode(node, "BooleanLiteral");
  3052. case types.parenL:
  3053. return this.parseParenAndDistinguishExpression(null, null, canBeArrow);
  3054. case types.bracketL:
  3055. node = this.startNode();
  3056. this.next();
  3057. node.elements = this.parseExprList(types.bracketR, true, refShorthandDefaultPos);
  3058. this.toReferencedList(node.elements);
  3059. return this.finishNode(node, "ArrayExpression");
  3060. case types.braceL:
  3061. return this.parseObj(false, refShorthandDefaultPos);
  3062. case types._function:
  3063. return this.parseFunctionExpression();
  3064. case types.at:
  3065. this.parseDecorators();
  3066. case types._class:
  3067. node = this.startNode();
  3068. this.takeDecorators(node);
  3069. return this.parseClass(node, false);
  3070. case types._new:
  3071. return this.parseNew();
  3072. case types.backQuote:
  3073. return this.parseTemplate(false);
  3074. case types.doubleColon:
  3075. node = this.startNode();
  3076. this.next();
  3077. node.object = null;
  3078. var callee = node.callee = this.parseNoCallExpr();
  3079. if (callee.type === "MemberExpression") {
  3080. return this.finishNode(node, "BindExpression");
  3081. } else {
  3082. this.raise(callee.start, "Binding should be performed on object property.");
  3083. }
  3084. default:
  3085. this.unexpected();
  3086. }
  3087. };
  3088. pp$3.parseFunctionExpression = function () {
  3089. var node = this.startNode();
  3090. var meta = this.parseIdentifier(true);
  3091. if (this.state.inGenerator && this.eat(types.dot) && this.hasPlugin("functionSent")) {
  3092. return this.parseMetaProperty(node, meta, "sent");
  3093. } else {
  3094. return this.parseFunction(node, false);
  3095. }
  3096. };
  3097. pp$3.parseMetaProperty = function (node, meta, propertyName) {
  3098. node.meta = meta;
  3099. node.property = this.parseIdentifier(true);
  3100. if (node.property.name !== propertyName) {
  3101. this.raise(node.property.start, "The only valid meta property for new is " + meta.name + "." + propertyName);
  3102. }
  3103. return this.finishNode(node, "MetaProperty");
  3104. };
  3105. pp$3.parseLiteral = function (value, type, startPos, startLoc) {
  3106. startPos = startPos || this.state.start;
  3107. startLoc = startLoc || this.state.startLoc;
  3108. var node = this.startNodeAt(startPos, startLoc);
  3109. this.addExtra(node, "rawValue", value);
  3110. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  3111. node.value = value;
  3112. this.next();
  3113. return this.finishNode(node, type);
  3114. };
  3115. pp$3.parseParenExpression = function () {
  3116. this.expect(types.parenL);
  3117. var val = this.parseExpression();
  3118. this.expect(types.parenR);
  3119. return val;
  3120. };
  3121. pp$3.parseParenAndDistinguishExpression = function (startPos, startLoc, canBeArrow) {
  3122. startPos = startPos || this.state.start;
  3123. startLoc = startLoc || this.state.startLoc;
  3124. var val = void 0;
  3125. this.expect(types.parenL);
  3126. var innerStartPos = this.state.start;
  3127. var innerStartLoc = this.state.startLoc;
  3128. var exprList = [];
  3129. var refShorthandDefaultPos = { start: 0 };
  3130. var refNeedsArrowPos = { start: 0 };
  3131. var first = true;
  3132. var spreadStart = void 0;
  3133. var optionalCommaStart = void 0;
  3134. while (!this.match(types.parenR)) {
  3135. if (first) {
  3136. first = false;
  3137. } else {
  3138. this.expect(types.comma, refNeedsArrowPos.start || null);
  3139. if (this.match(types.parenR)) {
  3140. optionalCommaStart = this.state.start;
  3141. break;
  3142. }
  3143. }
  3144. if (this.match(types.ellipsis)) {
  3145. var spreadNodeStartPos = this.state.start;
  3146. var spreadNodeStartLoc = this.state.startLoc;
  3147. spreadStart = this.state.start;
  3148. exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStartPos, spreadNodeStartLoc));
  3149. break;
  3150. } else {
  3151. exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos));
  3152. }
  3153. }
  3154. var innerEndPos = this.state.start;
  3155. var innerEndLoc = this.state.startLoc;
  3156. this.expect(types.parenR);
  3157. var arrowNode = this.startNodeAt(startPos, startLoc);
  3158. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  3159. for (var _iterator = exprList, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  3160. var _ref;
  3161. if (_isArray) {
  3162. if (_i >= _iterator.length) break;
  3163. _ref = _iterator[_i++];
  3164. } else {
  3165. _i = _iterator.next();
  3166. if (_i.done) break;
  3167. _ref = _i.value;
  3168. }
  3169. var param = _ref;
  3170. if (param.extra && param.extra.parenthesized) this.unexpected(param.extra.parenStart);
  3171. }
  3172. return this.parseArrowExpression(arrowNode, exprList);
  3173. }
  3174. if (!exprList.length) {
  3175. this.unexpected(this.state.lastTokStart);
  3176. }
  3177. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  3178. if (spreadStart) this.unexpected(spreadStart);
  3179. if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
  3180. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  3181. if (exprList.length > 1) {
  3182. val = this.startNodeAt(innerStartPos, innerStartLoc);
  3183. val.expressions = exprList;
  3184. this.toReferencedList(val.expressions);
  3185. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  3186. } else {
  3187. val = exprList[0];
  3188. }
  3189. this.addExtra(val, "parenthesized", true);
  3190. this.addExtra(val, "parenStart", startPos);
  3191. return val;
  3192. };
  3193. pp$3.shouldParseArrow = function () {
  3194. return !this.canInsertSemicolon();
  3195. };
  3196. pp$3.parseArrow = function (node) {
  3197. if (this.eat(types.arrow)) {
  3198. return node;
  3199. }
  3200. };
  3201. pp$3.parseParenItem = function (node) {
  3202. return node;
  3203. };
  3204. // New's precedence is slightly tricky. It must allow its argument
  3205. // to be a `[]` or dot subscript expression, but not a call — at
  3206. // least, not without wrapping it in parentheses. Thus, it uses the
  3207. pp$3.parseNew = function () {
  3208. var node = this.startNode();
  3209. var meta = this.parseIdentifier(true);
  3210. if (this.eat(types.dot)) {
  3211. var metaProp = this.parseMetaProperty(node, meta, "target");
  3212. if (!this.state.inFunction) {
  3213. this.raise(metaProp.property.start, "new.target can only be used in functions");
  3214. }
  3215. return metaProp;
  3216. }
  3217. node.callee = this.parseNoCallExpr();
  3218. if (this.eat(types.parenL)) {
  3219. node.arguments = this.parseExprList(types.parenR);
  3220. this.toReferencedList(node.arguments);
  3221. } else {
  3222. node.arguments = [];
  3223. }
  3224. return this.finishNode(node, "NewExpression");
  3225. };
  3226. // Parse template expression.
  3227. pp$3.parseTemplateElement = function (isTagged) {
  3228. var elem = this.startNode();
  3229. if (this.state.value === null) {
  3230. if (!isTagged || !this.hasPlugin("templateInvalidEscapes")) {
  3231. this.raise(this.state.invalidTemplateEscapePosition, "Invalid escape sequence in template");
  3232. } else {
  3233. this.state.invalidTemplateEscapePosition = null;
  3234. }
  3235. }
  3236. elem.value = {
  3237. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  3238. cooked: this.state.value
  3239. };
  3240. this.next();
  3241. elem.tail = this.match(types.backQuote);
  3242. return this.finishNode(elem, "TemplateElement");
  3243. };
  3244. pp$3.parseTemplate = function (isTagged) {
  3245. var node = this.startNode();
  3246. this.next();
  3247. node.expressions = [];
  3248. var curElt = this.parseTemplateElement(isTagged);
  3249. node.quasis = [curElt];
  3250. while (!curElt.tail) {
  3251. this.expect(types.dollarBraceL);
  3252. node.expressions.push(this.parseExpression());
  3253. this.expect(types.braceR);
  3254. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  3255. }
  3256. this.next();
  3257. return this.finishNode(node, "TemplateLiteral");
  3258. };
  3259. // Parse an object literal or binding pattern.
  3260. pp$3.parseObj = function (isPattern, refShorthandDefaultPos) {
  3261. var decorators = [];
  3262. var propHash = Object.create(null);
  3263. var first = true;
  3264. var node = this.startNode();
  3265. node.properties = [];
  3266. this.next();
  3267. var firstRestLocation = null;
  3268. while (!this.eat(types.braceR)) {
  3269. if (first) {
  3270. first = false;
  3271. } else {
  3272. this.expect(types.comma);
  3273. if (this.eat(types.braceR)) break;
  3274. }
  3275. while (this.match(types.at)) {
  3276. decorators.push(this.parseDecorator());
  3277. }
  3278. var prop = this.startNode(),
  3279. isGenerator = false,
  3280. isAsync = false,
  3281. startPos = void 0,
  3282. startLoc = void 0;
  3283. if (decorators.length) {
  3284. prop.decorators = decorators;
  3285. decorators = [];
  3286. }
  3287. if (this.hasPlugin("objectRestSpread") && this.match(types.ellipsis)) {
  3288. prop = this.parseSpread(isPattern ? { start: 0 } : undefined);
  3289. prop.type = isPattern ? "RestProperty" : "SpreadProperty";
  3290. if (isPattern) this.toAssignable(prop.argument, true, "object pattern");
  3291. node.properties.push(prop);
  3292. if (isPattern) {
  3293. var position = this.state.start;
  3294. if (firstRestLocation !== null) {
  3295. this.unexpected(firstRestLocation, "Cannot have multiple rest elements when destructuring");
  3296. } else if (this.eat(types.braceR)) {
  3297. break;
  3298. } else if (this.match(types.comma) && this.lookahead().type === types.braceR) {
  3299. // TODO: temporary rollback
  3300. // this.unexpected(position, "A trailing comma is not permitted after the rest element");
  3301. continue;
  3302. } else {
  3303. firstRestLocation = position;
  3304. continue;
  3305. }
  3306. } else {
  3307. continue;
  3308. }
  3309. }
  3310. prop.method = false;
  3311. prop.shorthand = false;
  3312. if (isPattern || refShorthandDefaultPos) {
  3313. startPos = this.state.start;
  3314. startLoc = this.state.startLoc;
  3315. }
  3316. if (!isPattern) {
  3317. isGenerator = this.eat(types.star);
  3318. }
  3319. if (!isPattern && this.isContextual("async")) {
  3320. if (isGenerator) this.unexpected();
  3321. var asyncId = this.parseIdentifier();
  3322. if (this.match(types.colon) || this.match(types.parenL) || this.match(types.braceR) || this.match(types.eq) || this.match(types.comma)) {
  3323. prop.key = asyncId;
  3324. prop.computed = false;
  3325. } else {
  3326. isAsync = true;
  3327. if (this.hasPlugin("asyncGenerators")) isGenerator = this.eat(types.star);
  3328. this.parsePropertyName(prop);
  3329. }
  3330. } else {
  3331. this.parsePropertyName(prop);
  3332. }
  3333. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos);
  3334. this.checkPropClash(prop, propHash);
  3335. if (prop.shorthand) {
  3336. this.addExtra(prop, "shorthand", true);
  3337. }
  3338. node.properties.push(prop);
  3339. }
  3340. if (firstRestLocation !== null) {
  3341. this.unexpected(firstRestLocation, "The rest element has to be the last element when destructuring");
  3342. }
  3343. if (decorators.length) {
  3344. this.raise(this.state.start, "You have trailing decorators with no property");
  3345. }
  3346. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
  3347. };
  3348. pp$3.isGetterOrSetterMethod = function (prop, isPattern) {
  3349. return !isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.match(types.string) || // get "string"() {}
  3350. this.match(types.num) || // get 1() {}
  3351. this.match(types.bracketL) || // get ["string"]() {}
  3352. this.match(types.name) || // get foo() {}
  3353. this.state.type.keyword // get debugger() {}
  3354. );
  3355. };
  3356. // get methods aren't allowed to have any parameters
  3357. // set methods must have exactly 1 parameter
  3358. pp$3.checkGetterSetterParamCount = function (method) {
  3359. var paramCount = method.kind === "get" ? 0 : 1;
  3360. if (method.params.length !== paramCount) {
  3361. var start = method.start;
  3362. if (method.kind === "get") {
  3363. this.raise(start, "getter should have no params");
  3364. } else {
  3365. this.raise(start, "setter should have exactly one param");
  3366. }
  3367. }
  3368. };
  3369. pp$3.parseObjectMethod = function (prop, isGenerator, isAsync, isPattern) {
  3370. if (isAsync || isGenerator || this.match(types.parenL)) {
  3371. if (isPattern) this.unexpected();
  3372. prop.kind = "method";
  3373. prop.method = true;
  3374. this.parseMethod(prop, isGenerator, isAsync);
  3375. return this.finishNode(prop, "ObjectMethod");
  3376. }
  3377. if (this.isGetterOrSetterMethod(prop, isPattern)) {
  3378. if (isGenerator || isAsync) this.unexpected();
  3379. prop.kind = prop.key.name;
  3380. this.parsePropertyName(prop);
  3381. this.parseMethod(prop);
  3382. this.checkGetterSetterParamCount(prop);
  3383. return this.finishNode(prop, "ObjectMethod");
  3384. }
  3385. };
  3386. pp$3.parseObjectProperty = function (prop, startPos, startLoc, isPattern, refShorthandDefaultPos) {
  3387. if (this.eat(types.colon)) {
  3388. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
  3389. return this.finishNode(prop, "ObjectProperty");
  3390. }
  3391. if (!prop.computed && prop.key.type === "Identifier") {
  3392. this.checkReservedWord(prop.key.name, prop.key.start, true, true);
  3393. if (isPattern) {
  3394. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  3395. } else if (this.match(types.eq) && refShorthandDefaultPos) {
  3396. if (!refShorthandDefaultPos.start) {
  3397. refShorthandDefaultPos.start = this.state.start;
  3398. }
  3399. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  3400. } else {
  3401. prop.value = prop.key.__clone();
  3402. }
  3403. prop.shorthand = true;
  3404. return this.finishNode(prop, "ObjectProperty");
  3405. }
  3406. };
  3407. pp$3.parseObjPropValue = function (prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos) {
  3408. var node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos);
  3409. if (!node) this.unexpected();
  3410. return node;
  3411. };
  3412. pp$3.parsePropertyName = function (prop) {
  3413. if (this.eat(types.bracketL)) {
  3414. prop.computed = true;
  3415. prop.key = this.parseMaybeAssign();
  3416. this.expect(types.bracketR);
  3417. } else {
  3418. prop.computed = false;
  3419. var oldInPropertyName = this.state.inPropertyName;
  3420. this.state.inPropertyName = true;
  3421. prop.key = this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  3422. this.state.inPropertyName = oldInPropertyName;
  3423. }
  3424. return prop.key;
  3425. };
  3426. // Initialize empty function node.
  3427. pp$3.initFunction = function (node, isAsync) {
  3428. node.id = null;
  3429. node.generator = false;
  3430. node.expression = false;
  3431. node.async = !!isAsync;
  3432. };
  3433. // Parse object or class method.
  3434. pp$3.parseMethod = function (node, isGenerator, isAsync) {
  3435. var oldInMethod = this.state.inMethod;
  3436. this.state.inMethod = node.kind || true;
  3437. this.initFunction(node, isAsync);
  3438. this.expect(types.parenL);
  3439. node.params = this.parseBindingList(types.parenR);
  3440. node.generator = !!isGenerator;
  3441. this.parseFunctionBody(node);
  3442. this.state.inMethod = oldInMethod;
  3443. return node;
  3444. };
  3445. // Parse arrow function expression with given parameters.
  3446. pp$3.parseArrowExpression = function (node, params, isAsync) {
  3447. this.initFunction(node, isAsync);
  3448. node.params = this.toAssignableList(params, true, "arrow function parameters");
  3449. this.parseFunctionBody(node, true);
  3450. return this.finishNode(node, "ArrowFunctionExpression");
  3451. };
  3452. pp$3.isStrictBody = function (node, isExpression) {
  3453. if (!isExpression && node.body.directives.length) {
  3454. for (var _iterator2 = node.body.directives, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
  3455. var _ref2;
  3456. if (_isArray2) {
  3457. if (_i2 >= _iterator2.length) break;
  3458. _ref2 = _iterator2[_i2++];
  3459. } else {
  3460. _i2 = _iterator2.next();
  3461. if (_i2.done) break;
  3462. _ref2 = _i2.value;
  3463. }
  3464. var directive = _ref2;
  3465. if (directive.value.value === "use strict") {
  3466. return true;
  3467. }
  3468. }
  3469. }
  3470. return false;
  3471. };
  3472. // Parse function body and check parameters.
  3473. pp$3.parseFunctionBody = function (node, allowExpression) {
  3474. var isExpression = allowExpression && !this.match(types.braceL);
  3475. var oldInAsync = this.state.inAsync;
  3476. this.state.inAsync = node.async;
  3477. if (isExpression) {
  3478. node.body = this.parseMaybeAssign();
  3479. node.expression = true;
  3480. } else {
  3481. // Start a new scope with regard to labels and the `inFunction`
  3482. // flag (restore them to their old value afterwards).
  3483. var oldInFunc = this.state.inFunction;
  3484. var oldInGen = this.state.inGenerator;
  3485. var oldLabels = this.state.labels;
  3486. this.state.inFunction = true;this.state.inGenerator = node.generator;this.state.labels = [];
  3487. node.body = this.parseBlock(true);
  3488. node.expression = false;
  3489. this.state.inFunction = oldInFunc;this.state.inGenerator = oldInGen;this.state.labels = oldLabels;
  3490. }
  3491. this.state.inAsync = oldInAsync;
  3492. // If this is a strict mode function, verify that argument names
  3493. // are not repeated, and it does not try to bind the words `eval`
  3494. // or `arguments`.
  3495. var isStrict = this.isStrictBody(node, isExpression);
  3496. // Also check when allowExpression === true for arrow functions
  3497. var checkLVal = this.state.strict || allowExpression || isStrict;
  3498. if (isStrict && node.id && node.id.type === "Identifier" && node.id.name === "yield") {
  3499. this.raise(node.id.start, "Binding yield in strict mode");
  3500. }
  3501. if (checkLVal) {
  3502. var nameHash = Object.create(null);
  3503. var oldStrict = this.state.strict;
  3504. if (isStrict) this.state.strict = true;
  3505. if (node.id) {
  3506. this.checkLVal(node.id, true, undefined, "function name");
  3507. }
  3508. for (var _iterator3 = node.params, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
  3509. var _ref3;
  3510. if (_isArray3) {
  3511. if (_i3 >= _iterator3.length) break;
  3512. _ref3 = _iterator3[_i3++];
  3513. } else {
  3514. _i3 = _iterator3.next();
  3515. if (_i3.done) break;
  3516. _ref3 = _i3.value;
  3517. }
  3518. var param = _ref3;
  3519. if (isStrict && param.type !== "Identifier") {
  3520. this.raise(param.start, "Non-simple parameter in strict mode");
  3521. }
  3522. this.checkLVal(param, true, nameHash, "function parameter list");
  3523. }
  3524. this.state.strict = oldStrict;
  3525. }
  3526. };
  3527. // Parses a comma-separated list of expressions, and returns them as
  3528. // an array. `close` is the token type that ends the list, and
  3529. // `allowEmpty` can be turned on to allow subsequent commas with
  3530. // nothing in between them to be parsed as `null` (which is needed
  3531. // for array literals).
  3532. pp$3.parseExprList = function (close, allowEmpty, refShorthandDefaultPos) {
  3533. var elts = [];
  3534. var first = true;
  3535. while (!this.eat(close)) {
  3536. if (first) {
  3537. first = false;
  3538. } else {
  3539. this.expect(types.comma);
  3540. if (this.eat(close)) break;
  3541. }
  3542. elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos));
  3543. }
  3544. return elts;
  3545. };
  3546. pp$3.parseExprListItem = function (allowEmpty, refShorthandDefaultPos, refNeedsArrowPos) {
  3547. var elt = void 0;
  3548. if (allowEmpty && this.match(types.comma)) {
  3549. elt = null;
  3550. } else if (this.match(types.ellipsis)) {
  3551. elt = this.parseSpread(refShorthandDefaultPos);
  3552. } else {
  3553. elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos);
  3554. }
  3555. return elt;
  3556. };
  3557. // Parse the next token as an identifier. If `liberal` is true (used
  3558. // when parsing properties), it will also convert keywords into
  3559. // identifiers.
  3560. pp$3.parseIdentifier = function (liberal) {
  3561. var node = this.startNode();
  3562. if (!liberal) {
  3563. this.checkReservedWord(this.state.value, this.state.start, !!this.state.type.keyword, false);
  3564. }
  3565. if (this.match(types.name)) {
  3566. node.name = this.state.value;
  3567. } else if (this.state.type.keyword) {
  3568. node.name = this.state.type.keyword;
  3569. } else {
  3570. this.unexpected();
  3571. }
  3572. if (!liberal && node.name === "await" && this.state.inAsync) {
  3573. this.raise(node.start, "invalid use of await inside of an async function");
  3574. }
  3575. node.loc.identifierName = node.name;
  3576. this.next();
  3577. return this.finishNode(node, "Identifier");
  3578. };
  3579. pp$3.checkReservedWord = function (word, startLoc, checkKeywords, isBinding) {
  3580. if (this.isReservedWord(word) || checkKeywords && this.isKeyword(word)) {
  3581. this.raise(startLoc, word + " is a reserved word");
  3582. }
  3583. if (this.state.strict && (reservedWords.strict(word) || isBinding && reservedWords.strictBind(word))) {
  3584. this.raise(startLoc, word + " is a reserved word in strict mode");
  3585. }
  3586. };
  3587. // Parses await expression inside async function.
  3588. pp$3.parseAwait = function (node) {
  3589. // istanbul ignore next: this condition is checked at the call site so won't be hit here
  3590. if (!this.state.inAsync) {
  3591. this.unexpected();
  3592. }
  3593. if (this.match(types.star)) {
  3594. this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead.");
  3595. }
  3596. node.argument = this.parseMaybeUnary();
  3597. return this.finishNode(node, "AwaitExpression");
  3598. };
  3599. // Parses yield expression inside generator.
  3600. pp$3.parseYield = function () {
  3601. var node = this.startNode();
  3602. this.next();
  3603. if (this.match(types.semi) || this.canInsertSemicolon() || !this.match(types.star) && !this.state.type.startsExpr) {
  3604. node.delegate = false;
  3605. node.argument = null;
  3606. } else {
  3607. node.delegate = this.eat(types.star);
  3608. node.argument = this.parseMaybeAssign();
  3609. }
  3610. return this.finishNode(node, "YieldExpression");
  3611. };
  3612. // Start an AST node, attaching a start offset.
  3613. var pp$4 = Parser.prototype;
  3614. var commentKeys = ["leadingComments", "trailingComments", "innerComments"];
  3615. var Node = function () {
  3616. function Node(pos, loc, filename) {
  3617. classCallCheck(this, Node);
  3618. this.type = "";
  3619. this.start = pos;
  3620. this.end = 0;
  3621. this.loc = new SourceLocation(loc);
  3622. if (filename) this.loc.filename = filename;
  3623. }
  3624. Node.prototype.__clone = function __clone() {
  3625. var node2 = new Node();
  3626. for (var key in this) {
  3627. // Do not clone comments that are already attached to the node
  3628. if (commentKeys.indexOf(key) < 0) {
  3629. node2[key] = this[key];
  3630. }
  3631. }
  3632. return node2;
  3633. };
  3634. return Node;
  3635. }();
  3636. pp$4.startNode = function () {
  3637. return new Node(this.state.start, this.state.startLoc, this.filename);
  3638. };
  3639. pp$4.startNodeAt = function (pos, loc) {
  3640. return new Node(pos, loc, this.filename);
  3641. };
  3642. function finishNodeAt(node, type, pos, loc) {
  3643. node.type = type;
  3644. node.end = pos;
  3645. node.loc.end = loc;
  3646. this.processComment(node);
  3647. return node;
  3648. }
  3649. // Finish an AST node, adding `type` and `end` properties.
  3650. pp$4.finishNode = function (node, type) {
  3651. return finishNodeAt.call(this, node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  3652. };
  3653. // Finish node at given position
  3654. pp$4.finishNodeAt = function (node, type, pos, loc) {
  3655. return finishNodeAt.call(this, node, type, pos, loc);
  3656. };
  3657. var pp$5 = Parser.prototype;
  3658. // This function is used to raise exceptions on parse errors. It
  3659. // takes an offset integer (into the current `input`) to indicate
  3660. // the location of the error, attaches the position to the end
  3661. // of the error message, and then raises a `SyntaxError` with that
  3662. // message.
  3663. pp$5.raise = function (pos, message) {
  3664. var loc = getLineInfo(this.input, pos);
  3665. message += " (" + loc.line + ":" + loc.column + ")";
  3666. var err = new SyntaxError(message);
  3667. err.pos = pos;
  3668. err.loc = loc;
  3669. throw err;
  3670. };
  3671. /* eslint max-len: 0 */
  3672. /**
  3673. * Based on the comment attachment algorithm used in espree and estraverse.
  3674. *
  3675. * Redistribution and use in source and binary forms, with or without
  3676. * modification, are permitted provided that the following conditions are met:
  3677. *
  3678. * * Redistributions of source code must retain the above copyright
  3679. * notice, this list of conditions and the following disclaimer.
  3680. * * Redistributions in binary form must reproduce the above copyright
  3681. * notice, this list of conditions and the following disclaimer in the
  3682. * documentation and/or other materials provided with the distribution.
  3683. *
  3684. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3685. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3686. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3687. * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  3688. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  3689. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  3690. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  3691. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3692. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  3693. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3694. */
  3695. function last(stack) {
  3696. return stack[stack.length - 1];
  3697. }
  3698. var pp$6 = Parser.prototype;
  3699. pp$6.addComment = function (comment) {
  3700. if (this.filename) comment.loc.filename = this.filename;
  3701. this.state.trailingComments.push(comment);
  3702. this.state.leadingComments.push(comment);
  3703. };
  3704. pp$6.processComment = function (node) {
  3705. if (node.type === "Program" && node.body.length > 0) return;
  3706. var stack = this.state.commentStack;
  3707. var firstChild = void 0,
  3708. lastChild = void 0,
  3709. trailingComments = void 0,
  3710. i = void 0,
  3711. j = void 0;
  3712. if (this.state.trailingComments.length > 0) {
  3713. // If the first comment in trailingComments comes after the
  3714. // current node, then we're good - all comments in the array will
  3715. // come after the node and so it's safe to add them as official
  3716. // trailingComments.
  3717. if (this.state.trailingComments[0].start >= node.end) {
  3718. trailingComments = this.state.trailingComments;
  3719. this.state.trailingComments = [];
  3720. } else {
  3721. // Otherwise, if the first comment doesn't come after the
  3722. // current node, that means we have a mix of leading and trailing
  3723. // comments in the array and that leadingComments contains the
  3724. // same items as trailingComments. Reset trailingComments to
  3725. // zero items and we'll handle this by evaluating leadingComments
  3726. // later.
  3727. this.state.trailingComments.length = 0;
  3728. }
  3729. } else {
  3730. var lastInStack = last(stack);
  3731. if (stack.length > 0 && lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  3732. trailingComments = lastInStack.trailingComments;
  3733. lastInStack.trailingComments = null;
  3734. }
  3735. }
  3736. // Eating the stack.
  3737. if (stack.length > 0 && last(stack).start >= node.start) {
  3738. firstChild = stack.pop();
  3739. }
  3740. while (stack.length > 0 && last(stack).start >= node.start) {
  3741. lastChild = stack.pop();
  3742. }
  3743. if (!lastChild && firstChild) lastChild = firstChild;
  3744. // Attach comments that follow a trailing comma on the last
  3745. // property in an object literal or a trailing comma in function arguments
  3746. // as trailing comments
  3747. if (firstChild && this.state.leadingComments.length > 0) {
  3748. var lastComment = last(this.state.leadingComments);
  3749. if (firstChild.type === "ObjectProperty") {
  3750. if (lastComment.start >= node.start) {
  3751. if (this.state.commentPreviousNode) {
  3752. for (j = 0; j < this.state.leadingComments.length; j++) {
  3753. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  3754. this.state.leadingComments.splice(j, 1);
  3755. j--;
  3756. }
  3757. }
  3758. if (this.state.leadingComments.length > 0) {
  3759. firstChild.trailingComments = this.state.leadingComments;
  3760. this.state.leadingComments = [];
  3761. }
  3762. }
  3763. }
  3764. } else if (node.type === "CallExpression" && node.arguments && node.arguments.length) {
  3765. var lastArg = last(node.arguments);
  3766. if (lastArg && lastComment.start >= lastArg.start && lastComment.end <= node.end) {
  3767. if (this.state.commentPreviousNode) {
  3768. if (this.state.leadingComments.length > 0) {
  3769. lastArg.trailingComments = this.state.leadingComments;
  3770. this.state.leadingComments = [];
  3771. }
  3772. }
  3773. }
  3774. }
  3775. }
  3776. if (lastChild) {
  3777. if (lastChild.leadingComments) {
  3778. if (lastChild !== node && last(lastChild.leadingComments).end <= node.start) {
  3779. node.leadingComments = lastChild.leadingComments;
  3780. lastChild.leadingComments = null;
  3781. } else {
  3782. // A leading comment for an anonymous class had been stolen by its first ClassMethod,
  3783. // so this takes back the leading comment.
  3784. // See also: https://github.com/eslint/espree/issues/158
  3785. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  3786. if (lastChild.leadingComments[i].end <= node.start) {
  3787. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  3788. break;
  3789. }
  3790. }
  3791. }
  3792. }
  3793. } else if (this.state.leadingComments.length > 0) {
  3794. if (last(this.state.leadingComments).end <= node.start) {
  3795. if (this.state.commentPreviousNode) {
  3796. for (j = 0; j < this.state.leadingComments.length; j++) {
  3797. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  3798. this.state.leadingComments.splice(j, 1);
  3799. j--;
  3800. }
  3801. }
  3802. }
  3803. if (this.state.leadingComments.length > 0) {
  3804. node.leadingComments = this.state.leadingComments;
  3805. this.state.leadingComments = [];
  3806. }
  3807. } else {
  3808. // https://github.com/eslint/espree/issues/2
  3809. //
  3810. // In special cases, such as return (without a value) and
  3811. // debugger, all comments will end up as leadingComments and
  3812. // will otherwise be eliminated. This step runs when the
  3813. // commentStack is empty and there are comments left
  3814. // in leadingComments.
  3815. //
  3816. // This loop figures out the stopping point between the actual
  3817. // leading and trailing comments by finding the location of the
  3818. // first comment that comes after the given node.
  3819. for (i = 0; i < this.state.leadingComments.length; i++) {
  3820. if (this.state.leadingComments[i].end > node.start) {
  3821. break;
  3822. }
  3823. }
  3824. // Split the array based on the location of the first comment
  3825. // that comes after the node. Keep in mind that this could
  3826. // result in an empty array, and if so, the array must be
  3827. // deleted.
  3828. node.leadingComments = this.state.leadingComments.slice(0, i);
  3829. if (node.leadingComments.length === 0) {
  3830. node.leadingComments = null;
  3831. }
  3832. // Similarly, trailing comments are attached later. The variable
  3833. // must be reset to null if there are no trailing comments.
  3834. trailingComments = this.state.leadingComments.slice(i);
  3835. if (trailingComments.length === 0) {
  3836. trailingComments = null;
  3837. }
  3838. }
  3839. }
  3840. this.state.commentPreviousNode = node;
  3841. if (trailingComments) {
  3842. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  3843. node.innerComments = trailingComments;
  3844. } else {
  3845. node.trailingComments = trailingComments;
  3846. }
  3847. }
  3848. stack.push(node);
  3849. };
  3850. var pp$7 = Parser.prototype;
  3851. pp$7.estreeParseRegExpLiteral = function (_ref) {
  3852. var pattern = _ref.pattern,
  3853. flags = _ref.flags;
  3854. var regex = null;
  3855. try {
  3856. regex = new RegExp(pattern, flags);
  3857. } catch (e) {
  3858. // In environments that don't support these flags value will
  3859. // be null as the regex can't be represented natively.
  3860. }
  3861. var node = this.estreeParseLiteral(regex);
  3862. node.regex = { pattern: pattern, flags: flags };
  3863. return node;
  3864. };
  3865. pp$7.estreeParseLiteral = function (value) {
  3866. return this.parseLiteral(value, "Literal");
  3867. };
  3868. pp$7.directiveToStmt = function (directive) {
  3869. var directiveLiteral = directive.value;
  3870. var stmt = this.startNodeAt(directive.start, directive.loc.start);
  3871. var expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  3872. expression.value = directiveLiteral.value;
  3873. expression.raw = directiveLiteral.extra.raw;
  3874. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  3875. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  3876. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  3877. };
  3878. function isSimpleProperty(node) {
  3879. return node && node.type === "Property" && node.kind === "init" && node.method === false;
  3880. }
  3881. var estreePlugin = function (instance) {
  3882. instance.extend("checkDeclaration", function (inner) {
  3883. return function (node) {
  3884. if (isSimpleProperty(node)) {
  3885. this.checkDeclaration(node.value);
  3886. } else {
  3887. inner.call(this, node);
  3888. }
  3889. };
  3890. });
  3891. instance.extend("checkGetterSetterParamCount", function () {
  3892. return function (prop) {
  3893. var paramCount = prop.kind === "get" ? 0 : 1;
  3894. if (prop.value.params.length !== paramCount) {
  3895. var start = prop.start;
  3896. if (prop.kind === "get") {
  3897. this.raise(start, "getter should have no params");
  3898. } else {
  3899. this.raise(start, "setter should have exactly one param");
  3900. }
  3901. }
  3902. };
  3903. });
  3904. instance.extend("checkLVal", function (inner) {
  3905. return function (expr, isBinding, checkClashes) {
  3906. var _this = this;
  3907. switch (expr.type) {
  3908. case "ObjectPattern":
  3909. expr.properties.forEach(function (prop) {
  3910. _this.checkLVal(prop.type === "Property" ? prop.value : prop, isBinding, checkClashes, "object destructuring pattern");
  3911. });
  3912. break;
  3913. default:
  3914. for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  3915. args[_key - 3] = arguments[_key];
  3916. }
  3917. inner.call.apply(inner, [this, expr, isBinding, checkClashes].concat(args));
  3918. }
  3919. };
  3920. });
  3921. instance.extend("checkPropClash", function () {
  3922. return function (prop, propHash) {
  3923. if (prop.computed || !isSimpleProperty(prop)) return;
  3924. var key = prop.key;
  3925. // It is either an Identifier or a String/NumericLiteral
  3926. var name = key.type === "Identifier" ? key.name : String(key.value);
  3927. if (name === "__proto__") {
  3928. if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
  3929. propHash.proto = true;
  3930. }
  3931. };
  3932. });
  3933. instance.extend("isStrictBody", function () {
  3934. return function (node, isExpression) {
  3935. if (!isExpression && node.body.body.length > 0) {
  3936. for (var _iterator = node.body.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  3937. var _ref2;
  3938. if (_isArray) {
  3939. if (_i >= _iterator.length) break;
  3940. _ref2 = _iterator[_i++];
  3941. } else {
  3942. _i = _iterator.next();
  3943. if (_i.done) break;
  3944. _ref2 = _i.value;
  3945. }
  3946. var directive = _ref2;
  3947. if (directive.type === "ExpressionStatement" && directive.expression.type === "Literal") {
  3948. if (directive.expression.value === "use strict") return true;
  3949. } else {
  3950. // Break for the first non literal expression
  3951. break;
  3952. }
  3953. }
  3954. }
  3955. return false;
  3956. };
  3957. });
  3958. instance.extend("isValidDirective", function () {
  3959. return function (stmt) {
  3960. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized);
  3961. };
  3962. });
  3963. instance.extend("stmtToDirective", function (inner) {
  3964. return function (stmt) {
  3965. var directive = inner.call(this, stmt);
  3966. var value = stmt.expression.value;
  3967. // Reset value to the actual value as in estree mode we want
  3968. // the stmt to have the real value and not the raw value
  3969. directive.value.value = value;
  3970. return directive;
  3971. };
  3972. });
  3973. instance.extend("parseBlockBody", function (inner) {
  3974. return function (node) {
  3975. var _this2 = this;
  3976. for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  3977. args[_key2 - 1] = arguments[_key2];
  3978. }
  3979. inner.call.apply(inner, [this, node].concat(args));
  3980. node.directives.reverse().forEach(function (directive) {
  3981. node.body.unshift(_this2.directiveToStmt(directive));
  3982. });
  3983. delete node.directives;
  3984. };
  3985. });
  3986. instance.extend("parseClassMethod", function () {
  3987. return function (classBody, method, isGenerator, isAsync) {
  3988. this.parseMethod(method, isGenerator, isAsync);
  3989. if (method.typeParameters) {
  3990. method.value.typeParameters = method.typeParameters;
  3991. delete method.typeParameters;
  3992. }
  3993. classBody.body.push(this.finishNode(method, "MethodDefinition"));
  3994. };
  3995. });
  3996. instance.extend("parseExprAtom", function (inner) {
  3997. return function () {
  3998. switch (this.state.type) {
  3999. case types.regexp:
  4000. return this.estreeParseRegExpLiteral(this.state.value);
  4001. case types.num:
  4002. case types.string:
  4003. return this.estreeParseLiteral(this.state.value);
  4004. case types._null:
  4005. return this.estreeParseLiteral(null);
  4006. case types._true:
  4007. return this.estreeParseLiteral(true);
  4008. case types._false:
  4009. return this.estreeParseLiteral(false);
  4010. default:
  4011. for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  4012. args[_key3] = arguments[_key3];
  4013. }
  4014. return inner.call.apply(inner, [this].concat(args));
  4015. }
  4016. };
  4017. });
  4018. instance.extend("parseLiteral", function (inner) {
  4019. return function () {
  4020. for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  4021. args[_key4] = arguments[_key4];
  4022. }
  4023. var node = inner.call.apply(inner, [this].concat(args));
  4024. node.raw = node.extra.raw;
  4025. delete node.extra;
  4026. return node;
  4027. };
  4028. });
  4029. instance.extend("parseMethod", function (inner) {
  4030. return function (node) {
  4031. var funcNode = this.startNode();
  4032. funcNode.kind = node.kind; // provide kind, so inner method correctly sets state
  4033. for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  4034. args[_key5 - 1] = arguments[_key5];
  4035. }
  4036. funcNode = inner.call.apply(inner, [this, funcNode].concat(args));
  4037. delete funcNode.kind;
  4038. node.value = this.finishNode(funcNode, "FunctionExpression");
  4039. return node;
  4040. };
  4041. });
  4042. instance.extend("parseObjectMethod", function (inner) {
  4043. return function () {
  4044. for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
  4045. args[_key6] = arguments[_key6];
  4046. }
  4047. var node = inner.call.apply(inner, [this].concat(args));
  4048. if (node) {
  4049. if (node.kind === "method") node.kind = "init";
  4050. node.type = "Property";
  4051. }
  4052. return node;
  4053. };
  4054. });
  4055. instance.extend("parseObjectProperty", function (inner) {
  4056. return function () {
  4057. for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
  4058. args[_key7] = arguments[_key7];
  4059. }
  4060. var node = inner.call.apply(inner, [this].concat(args));
  4061. if (node) {
  4062. node.kind = "init";
  4063. node.type = "Property";
  4064. }
  4065. return node;
  4066. };
  4067. });
  4068. instance.extend("toAssignable", function (inner) {
  4069. return function (node, isBinding) {
  4070. for (var _len8 = arguments.length, args = Array(_len8 > 2 ? _len8 - 2 : 0), _key8 = 2; _key8 < _len8; _key8++) {
  4071. args[_key8 - 2] = arguments[_key8];
  4072. }
  4073. if (isSimpleProperty(node)) {
  4074. this.toAssignable.apply(this, [node.value, isBinding].concat(args));
  4075. return node;
  4076. } else if (node.type === "ObjectExpression") {
  4077. node.type = "ObjectPattern";
  4078. for (var _iterator2 = node.properties, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
  4079. var _ref3;
  4080. if (_isArray2) {
  4081. if (_i2 >= _iterator2.length) break;
  4082. _ref3 = _iterator2[_i2++];
  4083. } else {
  4084. _i2 = _iterator2.next();
  4085. if (_i2.done) break;
  4086. _ref3 = _i2.value;
  4087. }
  4088. var prop = _ref3;
  4089. if (prop.kind === "get" || prop.kind === "set") {
  4090. this.raise(prop.key.start, "Object pattern can't contain getter or setter");
  4091. } else if (prop.method) {
  4092. this.raise(prop.key.start, "Object pattern can't contain methods");
  4093. } else {
  4094. this.toAssignable(prop, isBinding, "object destructuring pattern");
  4095. }
  4096. }
  4097. return node;
  4098. }
  4099. return inner.call.apply(inner, [this, node, isBinding].concat(args));
  4100. };
  4101. });
  4102. };
  4103. /* eslint max-len: 0 */
  4104. var primitiveTypes = ["any", "mixed", "empty", "bool", "boolean", "number", "string", "void", "null"];
  4105. var pp$8 = Parser.prototype;
  4106. pp$8.flowParseTypeInitialiser = function (tok) {
  4107. var oldInType = this.state.inType;
  4108. this.state.inType = true;
  4109. this.expect(tok || types.colon);
  4110. var type = this.flowParseType();
  4111. this.state.inType = oldInType;
  4112. return type;
  4113. };
  4114. pp$8.flowParsePredicate = function () {
  4115. var node = this.startNode();
  4116. var moduloLoc = this.state.startLoc;
  4117. var moduloPos = this.state.start;
  4118. this.expect(types.modulo);
  4119. var checksLoc = this.state.startLoc;
  4120. this.expectContextual("checks");
  4121. // Force '%' and 'checks' to be adjacent
  4122. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  4123. this.raise(moduloPos, "Spaces between ´%´ and ´checks´ are not allowed here.");
  4124. }
  4125. if (this.eat(types.parenL)) {
  4126. node.expression = this.parseExpression();
  4127. this.expect(types.parenR);
  4128. return this.finishNode(node, "DeclaredPredicate");
  4129. } else {
  4130. return this.finishNode(node, "InferredPredicate");
  4131. }
  4132. };
  4133. pp$8.flowParseTypeAndPredicateInitialiser = function () {
  4134. var oldInType = this.state.inType;
  4135. this.state.inType = true;
  4136. this.expect(types.colon);
  4137. var type = null;
  4138. var predicate = null;
  4139. if (this.match(types.modulo)) {
  4140. this.state.inType = oldInType;
  4141. predicate = this.flowParsePredicate();
  4142. } else {
  4143. type = this.flowParseType();
  4144. this.state.inType = oldInType;
  4145. if (this.match(types.modulo)) {
  4146. predicate = this.flowParsePredicate();
  4147. }
  4148. }
  4149. return [type, predicate];
  4150. };
  4151. pp$8.flowParseDeclareClass = function (node) {
  4152. this.next();
  4153. this.flowParseInterfaceish(node, true);
  4154. return this.finishNode(node, "DeclareClass");
  4155. };
  4156. pp$8.flowParseDeclareFunction = function (node) {
  4157. this.next();
  4158. var id = node.id = this.parseIdentifier();
  4159. var typeNode = this.startNode();
  4160. var typeContainer = this.startNode();
  4161. if (this.isRelational("<")) {
  4162. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4163. } else {
  4164. typeNode.typeParameters = null;
  4165. }
  4166. this.expect(types.parenL);
  4167. var tmp = this.flowParseFunctionTypeParams();
  4168. typeNode.params = tmp.params;
  4169. typeNode.rest = tmp.rest;
  4170. this.expect(types.parenR);
  4171. var predicate = null;
  4172. var _flowParseTypeAndPred = this.flowParseTypeAndPredicateInitialiser();
  4173. typeNode.returnType = _flowParseTypeAndPred[0];
  4174. predicate = _flowParseTypeAndPred[1];
  4175. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4176. typeContainer.predicate = predicate;
  4177. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4178. this.finishNode(id, id.type);
  4179. this.semicolon();
  4180. return this.finishNode(node, "DeclareFunction");
  4181. };
  4182. pp$8.flowParseDeclare = function (node) {
  4183. if (this.match(types._class)) {
  4184. return this.flowParseDeclareClass(node);
  4185. } else if (this.match(types._function)) {
  4186. return this.flowParseDeclareFunction(node);
  4187. } else if (this.match(types._var)) {
  4188. return this.flowParseDeclareVariable(node);
  4189. } else if (this.isContextual("module")) {
  4190. if (this.lookahead().type === types.dot) {
  4191. return this.flowParseDeclareModuleExports(node);
  4192. } else {
  4193. return this.flowParseDeclareModule(node);
  4194. }
  4195. } else if (this.isContextual("type")) {
  4196. return this.flowParseDeclareTypeAlias(node);
  4197. } else if (this.isContextual("opaque")) {
  4198. return this.flowParseDeclareOpaqueType(node);
  4199. } else if (this.isContextual("interface")) {
  4200. return this.flowParseDeclareInterface(node);
  4201. } else if (this.match(types._export)) {
  4202. return this.flowParseDeclareExportDeclaration(node);
  4203. } else {
  4204. this.unexpected();
  4205. }
  4206. };
  4207. pp$8.flowParseDeclareExportDeclaration = function (node) {
  4208. this.expect(types._export);
  4209. if (this.isContextual("opaque") // declare export opaque ...
  4210. ) {
  4211. node.declaration = this.flowParseDeclare(this.startNode());
  4212. node.default = false;
  4213. return this.finishNode(node, "DeclareExportDeclaration");
  4214. }
  4215. throw this.unexpected();
  4216. };
  4217. pp$8.flowParseDeclareVariable = function (node) {
  4218. this.next();
  4219. node.id = this.flowParseTypeAnnotatableIdentifier();
  4220. this.semicolon();
  4221. return this.finishNode(node, "DeclareVariable");
  4222. };
  4223. pp$8.flowParseDeclareModule = function (node) {
  4224. this.next();
  4225. if (this.match(types.string)) {
  4226. node.id = this.parseExprAtom();
  4227. } else {
  4228. node.id = this.parseIdentifier();
  4229. }
  4230. var bodyNode = node.body = this.startNode();
  4231. var body = bodyNode.body = [];
  4232. this.expect(types.braceL);
  4233. while (!this.match(types.braceR)) {
  4234. var _bodyNode = this.startNode();
  4235. if (this.match(types._import)) {
  4236. var lookahead = this.lookahead();
  4237. if (lookahead.value !== "type" && lookahead.value !== "typeof") {
  4238. this.unexpected(null, "Imports within a `declare module` body must always be `import type` or `import typeof`");
  4239. }
  4240. this.parseImport(_bodyNode);
  4241. } else {
  4242. this.expectContextual("declare", "Only declares and type imports are allowed inside declare module");
  4243. _bodyNode = this.flowParseDeclare(_bodyNode, true);
  4244. }
  4245. body.push(_bodyNode);
  4246. }
  4247. this.expect(types.braceR);
  4248. this.finishNode(bodyNode, "BlockStatement");
  4249. return this.finishNode(node, "DeclareModule");
  4250. };
  4251. pp$8.flowParseDeclareModuleExports = function (node) {
  4252. this.expectContextual("module");
  4253. this.expect(types.dot);
  4254. this.expectContextual("exports");
  4255. node.typeAnnotation = this.flowParseTypeAnnotation();
  4256. this.semicolon();
  4257. return this.finishNode(node, "DeclareModuleExports");
  4258. };
  4259. pp$8.flowParseDeclareTypeAlias = function (node) {
  4260. this.next();
  4261. this.flowParseTypeAlias(node);
  4262. return this.finishNode(node, "DeclareTypeAlias");
  4263. };
  4264. pp$8.flowParseDeclareOpaqueType = function (node) {
  4265. this.next();
  4266. this.flowParseOpaqueType(node, true);
  4267. return this.finishNode(node, "DeclareOpaqueType");
  4268. };
  4269. pp$8.flowParseDeclareInterface = function (node) {
  4270. this.next();
  4271. this.flowParseInterfaceish(node);
  4272. return this.finishNode(node, "DeclareInterface");
  4273. };
  4274. // Interfaces
  4275. pp$8.flowParseInterfaceish = function (node) {
  4276. node.id = this.parseIdentifier();
  4277. if (this.isRelational("<")) {
  4278. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4279. } else {
  4280. node.typeParameters = null;
  4281. }
  4282. node.extends = [];
  4283. node.mixins = [];
  4284. if (this.eat(types._extends)) {
  4285. do {
  4286. node.extends.push(this.flowParseInterfaceExtends());
  4287. } while (this.eat(types.comma));
  4288. }
  4289. if (this.isContextual("mixins")) {
  4290. this.next();
  4291. do {
  4292. node.mixins.push(this.flowParseInterfaceExtends());
  4293. } while (this.eat(types.comma));
  4294. }
  4295. node.body = this.flowParseObjectType(true, false, false);
  4296. };
  4297. pp$8.flowParseInterfaceExtends = function () {
  4298. var node = this.startNode();
  4299. node.id = this.flowParseQualifiedTypeIdentifier();
  4300. if (this.isRelational("<")) {
  4301. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4302. } else {
  4303. node.typeParameters = null;
  4304. }
  4305. return this.finishNode(node, "InterfaceExtends");
  4306. };
  4307. pp$8.flowParseInterface = function (node) {
  4308. this.flowParseInterfaceish(node, false);
  4309. return this.finishNode(node, "InterfaceDeclaration");
  4310. };
  4311. pp$8.flowParseRestrictedIdentifier = function (liberal) {
  4312. if (primitiveTypes.indexOf(this.state.value) > -1) {
  4313. this.raise(this.state.start, "Cannot overwrite primitive type " + this.state.value);
  4314. }
  4315. return this.parseIdentifier(liberal);
  4316. };
  4317. // Type aliases
  4318. pp$8.flowParseTypeAlias = function (node) {
  4319. node.id = this.flowParseRestrictedIdentifier();
  4320. if (this.isRelational("<")) {
  4321. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4322. } else {
  4323. node.typeParameters = null;
  4324. }
  4325. node.right = this.flowParseTypeInitialiser(types.eq);
  4326. this.semicolon();
  4327. return this.finishNode(node, "TypeAlias");
  4328. };
  4329. // Opaque type aliases
  4330. pp$8.flowParseOpaqueType = function (node, declare) {
  4331. this.expectContextual("type");
  4332. node.id = this.flowParseRestrictedIdentifier();
  4333. if (this.isRelational("<")) {
  4334. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4335. } else {
  4336. node.typeParameters = null;
  4337. }
  4338. // Parse the supertype
  4339. node.supertype = null;
  4340. if (this.match(types.colon)) {
  4341. node.supertype = this.flowParseTypeInitialiser(types.colon);
  4342. }
  4343. node.impltype = null;
  4344. if (!declare) {
  4345. node.impltype = this.flowParseTypeInitialiser(types.eq);
  4346. }
  4347. this.semicolon();
  4348. return this.finishNode(node, "OpaqueType");
  4349. };
  4350. // Type annotations
  4351. pp$8.flowParseTypeParameter = function () {
  4352. var node = this.startNode();
  4353. var variance = this.flowParseVariance();
  4354. var ident = this.flowParseTypeAnnotatableIdentifier();
  4355. node.name = ident.name;
  4356. node.variance = variance;
  4357. node.bound = ident.typeAnnotation;
  4358. if (this.match(types.eq)) {
  4359. this.eat(types.eq);
  4360. node.default = this.flowParseType();
  4361. }
  4362. return this.finishNode(node, "TypeParameter");
  4363. };
  4364. pp$8.flowParseTypeParameterDeclaration = function () {
  4365. var oldInType = this.state.inType;
  4366. var node = this.startNode();
  4367. node.params = [];
  4368. this.state.inType = true;
  4369. // istanbul ignore else: this condition is already checked at all call sites
  4370. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4371. this.next();
  4372. } else {
  4373. this.unexpected();
  4374. }
  4375. do {
  4376. node.params.push(this.flowParseTypeParameter());
  4377. if (!this.isRelational(">")) {
  4378. this.expect(types.comma);
  4379. }
  4380. } while (!this.isRelational(">"));
  4381. this.expectRelational(">");
  4382. this.state.inType = oldInType;
  4383. return this.finishNode(node, "TypeParameterDeclaration");
  4384. };
  4385. pp$8.flowParseTypeParameterInstantiation = function () {
  4386. var node = this.startNode();
  4387. var oldInType = this.state.inType;
  4388. node.params = [];
  4389. this.state.inType = true;
  4390. this.expectRelational("<");
  4391. while (!this.isRelational(">")) {
  4392. node.params.push(this.flowParseType());
  4393. if (!this.isRelational(">")) {
  4394. this.expect(types.comma);
  4395. }
  4396. }
  4397. this.expectRelational(">");
  4398. this.state.inType = oldInType;
  4399. return this.finishNode(node, "TypeParameterInstantiation");
  4400. };
  4401. pp$8.flowParseObjectPropertyKey = function () {
  4402. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  4403. };
  4404. pp$8.flowParseObjectTypeIndexer = function (node, isStatic, variance) {
  4405. node.static = isStatic;
  4406. this.expect(types.bracketL);
  4407. if (this.lookahead().type === types.colon) {
  4408. node.id = this.flowParseObjectPropertyKey();
  4409. node.key = this.flowParseTypeInitialiser();
  4410. } else {
  4411. node.id = null;
  4412. node.key = this.flowParseType();
  4413. }
  4414. this.expect(types.bracketR);
  4415. node.value = this.flowParseTypeInitialiser();
  4416. node.variance = variance;
  4417. this.flowObjectTypeSemicolon();
  4418. return this.finishNode(node, "ObjectTypeIndexer");
  4419. };
  4420. pp$8.flowParseObjectTypeMethodish = function (node) {
  4421. node.params = [];
  4422. node.rest = null;
  4423. node.typeParameters = null;
  4424. if (this.isRelational("<")) {
  4425. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4426. }
  4427. this.expect(types.parenL);
  4428. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  4429. node.params.push(this.flowParseFunctionTypeParam());
  4430. if (!this.match(types.parenR)) {
  4431. this.expect(types.comma);
  4432. }
  4433. }
  4434. if (this.eat(types.ellipsis)) {
  4435. node.rest = this.flowParseFunctionTypeParam();
  4436. }
  4437. this.expect(types.parenR);
  4438. node.returnType = this.flowParseTypeInitialiser();
  4439. return this.finishNode(node, "FunctionTypeAnnotation");
  4440. };
  4441. pp$8.flowParseObjectTypeMethod = function (startPos, startLoc, isStatic, key) {
  4442. var node = this.startNodeAt(startPos, startLoc);
  4443. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(startPos, startLoc));
  4444. node.static = isStatic;
  4445. node.key = key;
  4446. node.optional = false;
  4447. this.flowObjectTypeSemicolon();
  4448. return this.finishNode(node, "ObjectTypeProperty");
  4449. };
  4450. pp$8.flowParseObjectTypeCallProperty = function (node, isStatic) {
  4451. var valueNode = this.startNode();
  4452. node.static = isStatic;
  4453. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4454. this.flowObjectTypeSemicolon();
  4455. return this.finishNode(node, "ObjectTypeCallProperty");
  4456. };
  4457. pp$8.flowParseObjectType = function (allowStatic, allowExact, allowSpread) {
  4458. var oldInType = this.state.inType;
  4459. this.state.inType = true;
  4460. var nodeStart = this.startNode();
  4461. var node = void 0;
  4462. var propertyKey = void 0;
  4463. var isStatic = false;
  4464. nodeStart.callProperties = [];
  4465. nodeStart.properties = [];
  4466. nodeStart.indexers = [];
  4467. var endDelim = void 0;
  4468. var exact = void 0;
  4469. if (allowExact && this.match(types.braceBarL)) {
  4470. this.expect(types.braceBarL);
  4471. endDelim = types.braceBarR;
  4472. exact = true;
  4473. } else {
  4474. this.expect(types.braceL);
  4475. endDelim = types.braceR;
  4476. exact = false;
  4477. }
  4478. nodeStart.exact = exact;
  4479. while (!this.match(endDelim)) {
  4480. var optional = false;
  4481. var startPos = this.state.start;
  4482. var startLoc = this.state.startLoc;
  4483. node = this.startNode();
  4484. if (allowStatic && this.isContextual("static") && this.lookahead().type !== types.colon) {
  4485. this.next();
  4486. isStatic = true;
  4487. }
  4488. var variancePos = this.state.start;
  4489. var variance = this.flowParseVariance();
  4490. if (this.match(types.bracketL)) {
  4491. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4492. } else if (this.match(types.parenL) || this.isRelational("<")) {
  4493. if (variance) {
  4494. this.unexpected(variancePos);
  4495. }
  4496. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4497. } else {
  4498. if (this.match(types.ellipsis)) {
  4499. if (!allowSpread) {
  4500. this.unexpected(null, "Spread operator cannot appear in class or interface definitions");
  4501. }
  4502. if (variance) {
  4503. this.unexpected(variance.start, "Spread properties cannot have variance");
  4504. }
  4505. this.expect(types.ellipsis);
  4506. node.argument = this.flowParseType();
  4507. this.flowObjectTypeSemicolon();
  4508. nodeStart.properties.push(this.finishNode(node, "ObjectTypeSpreadProperty"));
  4509. } else {
  4510. propertyKey = this.flowParseObjectPropertyKey();
  4511. if (this.isRelational("<") || this.match(types.parenL)) {
  4512. // This is a method property
  4513. if (variance) {
  4514. this.unexpected(variance.start);
  4515. }
  4516. nodeStart.properties.push(this.flowParseObjectTypeMethod(startPos, startLoc, isStatic, propertyKey));
  4517. } else {
  4518. if (this.eat(types.question)) {
  4519. optional = true;
  4520. }
  4521. node.key = propertyKey;
  4522. node.value = this.flowParseTypeInitialiser();
  4523. node.optional = optional;
  4524. node.static = isStatic;
  4525. node.variance = variance;
  4526. this.flowObjectTypeSemicolon();
  4527. nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty"));
  4528. }
  4529. }
  4530. }
  4531. isStatic = false;
  4532. }
  4533. this.expect(endDelim);
  4534. var out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4535. this.state.inType = oldInType;
  4536. return out;
  4537. };
  4538. pp$8.flowObjectTypeSemicolon = function () {
  4539. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  4540. this.unexpected();
  4541. }
  4542. };
  4543. pp$8.flowParseQualifiedTypeIdentifier = function (startPos, startLoc, id) {
  4544. startPos = startPos || this.state.start;
  4545. startLoc = startLoc || this.state.startLoc;
  4546. var node = id || this.parseIdentifier();
  4547. while (this.eat(types.dot)) {
  4548. var node2 = this.startNodeAt(startPos, startLoc);
  4549. node2.qualification = node;
  4550. node2.id = this.parseIdentifier();
  4551. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4552. }
  4553. return node;
  4554. };
  4555. pp$8.flowParseGenericType = function (startPos, startLoc, id) {
  4556. var node = this.startNodeAt(startPos, startLoc);
  4557. node.typeParameters = null;
  4558. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  4559. if (this.isRelational("<")) {
  4560. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4561. }
  4562. return this.finishNode(node, "GenericTypeAnnotation");
  4563. };
  4564. pp$8.flowParseTypeofType = function () {
  4565. var node = this.startNode();
  4566. this.expect(types._typeof);
  4567. node.argument = this.flowParsePrimaryType();
  4568. return this.finishNode(node, "TypeofTypeAnnotation");
  4569. };
  4570. pp$8.flowParseTupleType = function () {
  4571. var node = this.startNode();
  4572. node.types = [];
  4573. this.expect(types.bracketL);
  4574. // We allow trailing commas
  4575. while (this.state.pos < this.input.length && !this.match(types.bracketR)) {
  4576. node.types.push(this.flowParseType());
  4577. if (this.match(types.bracketR)) break;
  4578. this.expect(types.comma);
  4579. }
  4580. this.expect(types.bracketR);
  4581. return this.finishNode(node, "TupleTypeAnnotation");
  4582. };
  4583. pp$8.flowParseFunctionTypeParam = function () {
  4584. var name = null;
  4585. var optional = false;
  4586. var typeAnnotation = null;
  4587. var node = this.startNode();
  4588. var lh = this.lookahead();
  4589. if (lh.type === types.colon || lh.type === types.question) {
  4590. name = this.parseIdentifier();
  4591. if (this.eat(types.question)) {
  4592. optional = true;
  4593. }
  4594. typeAnnotation = this.flowParseTypeInitialiser();
  4595. } else {
  4596. typeAnnotation = this.flowParseType();
  4597. }
  4598. node.name = name;
  4599. node.optional = optional;
  4600. node.typeAnnotation = typeAnnotation;
  4601. return this.finishNode(node, "FunctionTypeParam");
  4602. };
  4603. pp$8.reinterpretTypeAsFunctionTypeParam = function (type) {
  4604. var node = this.startNodeAt(type.start, type.loc.start);
  4605. node.name = null;
  4606. node.optional = false;
  4607. node.typeAnnotation = type;
  4608. return this.finishNode(node, "FunctionTypeParam");
  4609. };
  4610. pp$8.flowParseFunctionTypeParams = function () {
  4611. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  4612. var ret = { params: params, rest: null };
  4613. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  4614. ret.params.push(this.flowParseFunctionTypeParam());
  4615. if (!this.match(types.parenR)) {
  4616. this.expect(types.comma);
  4617. }
  4618. }
  4619. if (this.eat(types.ellipsis)) {
  4620. ret.rest = this.flowParseFunctionTypeParam();
  4621. }
  4622. return ret;
  4623. };
  4624. pp$8.flowIdentToTypeAnnotation = function (startPos, startLoc, node, id) {
  4625. switch (id.name) {
  4626. case "any":
  4627. return this.finishNode(node, "AnyTypeAnnotation");
  4628. case "void":
  4629. return this.finishNode(node, "VoidTypeAnnotation");
  4630. case "bool":
  4631. case "boolean":
  4632. return this.finishNode(node, "BooleanTypeAnnotation");
  4633. case "mixed":
  4634. return this.finishNode(node, "MixedTypeAnnotation");
  4635. case "empty":
  4636. return this.finishNode(node, "EmptyTypeAnnotation");
  4637. case "number":
  4638. return this.finishNode(node, "NumberTypeAnnotation");
  4639. case "string":
  4640. return this.finishNode(node, "StringTypeAnnotation");
  4641. default:
  4642. return this.flowParseGenericType(startPos, startLoc, id);
  4643. }
  4644. };
  4645. // The parsing of types roughly parallels the parsing of expressions, and
  4646. // primary types are kind of like primary expressions...they're the
  4647. // primitives with which other types are constructed.
  4648. pp$8.flowParsePrimaryType = function () {
  4649. var startPos = this.state.start;
  4650. var startLoc = this.state.startLoc;
  4651. var node = this.startNode();
  4652. var tmp = void 0;
  4653. var type = void 0;
  4654. var isGroupedType = false;
  4655. var oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4656. switch (this.state.type) {
  4657. case types.name:
  4658. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  4659. case types.braceL:
  4660. return this.flowParseObjectType(false, false, true);
  4661. case types.braceBarL:
  4662. return this.flowParseObjectType(false, true, true);
  4663. case types.bracketL:
  4664. return this.flowParseTupleType();
  4665. case types.relational:
  4666. if (this.state.value === "<") {
  4667. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4668. this.expect(types.parenL);
  4669. tmp = this.flowParseFunctionTypeParams();
  4670. node.params = tmp.params;
  4671. node.rest = tmp.rest;
  4672. this.expect(types.parenR);
  4673. this.expect(types.arrow);
  4674. node.returnType = this.flowParseType();
  4675. return this.finishNode(node, "FunctionTypeAnnotation");
  4676. }
  4677. break;
  4678. case types.parenL:
  4679. this.next();
  4680. // Check to see if this is actually a grouped type
  4681. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  4682. if (this.match(types.name)) {
  4683. var token = this.lookahead().type;
  4684. isGroupedType = token !== types.question && token !== types.colon;
  4685. } else {
  4686. isGroupedType = true;
  4687. }
  4688. }
  4689. if (isGroupedType) {
  4690. this.state.noAnonFunctionType = false;
  4691. type = this.flowParseType();
  4692. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4693. // A `,` or a `) =>` means this is an anonymous function type
  4694. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  4695. this.expect(types.parenR);
  4696. return type;
  4697. } else {
  4698. // Eat a comma if there is one
  4699. this.eat(types.comma);
  4700. }
  4701. }
  4702. if (type) {
  4703. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  4704. } else {
  4705. tmp = this.flowParseFunctionTypeParams();
  4706. }
  4707. node.params = tmp.params;
  4708. node.rest = tmp.rest;
  4709. this.expect(types.parenR);
  4710. this.expect(types.arrow);
  4711. node.returnType = this.flowParseType();
  4712. node.typeParameters = null;
  4713. return this.finishNode(node, "FunctionTypeAnnotation");
  4714. case types.string:
  4715. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  4716. case types._true:case types._false:
  4717. node.value = this.match(types._true);
  4718. this.next();
  4719. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  4720. case types.plusMin:
  4721. if (this.state.value === "-") {
  4722. this.next();
  4723. if (!this.match(types.num)) this.unexpected(null, "Unexpected token, expected number");
  4724. return this.parseLiteral(-this.state.value, "NumericLiteralTypeAnnotation", node.start, node.loc.start);
  4725. }
  4726. this.unexpected();
  4727. case types.num:
  4728. return this.parseLiteral(this.state.value, "NumericLiteralTypeAnnotation");
  4729. case types._null:
  4730. node.value = this.match(types._null);
  4731. this.next();
  4732. return this.finishNode(node, "NullLiteralTypeAnnotation");
  4733. case types._this:
  4734. node.value = this.match(types._this);
  4735. this.next();
  4736. return this.finishNode(node, "ThisTypeAnnotation");
  4737. case types.star:
  4738. this.next();
  4739. return this.finishNode(node, "ExistentialTypeParam");
  4740. default:
  4741. if (this.state.type.keyword === "typeof") {
  4742. return this.flowParseTypeofType();
  4743. }
  4744. }
  4745. this.unexpected();
  4746. };
  4747. pp$8.flowParsePostfixType = function () {
  4748. var startPos = this.state.start,
  4749. startLoc = this.state.startLoc;
  4750. var type = this.flowParsePrimaryType();
  4751. while (!this.canInsertSemicolon() && this.match(types.bracketL)) {
  4752. var node = this.startNodeAt(startPos, startLoc);
  4753. node.elementType = type;
  4754. this.expect(types.bracketL);
  4755. this.expect(types.bracketR);
  4756. type = this.finishNode(node, "ArrayTypeAnnotation");
  4757. }
  4758. return type;
  4759. };
  4760. pp$8.flowParsePrefixType = function () {
  4761. var node = this.startNode();
  4762. if (this.eat(types.question)) {
  4763. node.typeAnnotation = this.flowParsePrefixType();
  4764. return this.finishNode(node, "NullableTypeAnnotation");
  4765. } else {
  4766. return this.flowParsePostfixType();
  4767. }
  4768. };
  4769. pp$8.flowParseAnonFunctionWithoutParens = function () {
  4770. var param = this.flowParsePrefixType();
  4771. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  4772. var node = this.startNodeAt(param.start, param.loc.start);
  4773. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  4774. node.rest = null;
  4775. node.returnType = this.flowParseType();
  4776. node.typeParameters = null;
  4777. return this.finishNode(node, "FunctionTypeAnnotation");
  4778. }
  4779. return param;
  4780. };
  4781. pp$8.flowParseIntersectionType = function () {
  4782. var node = this.startNode();
  4783. this.eat(types.bitwiseAND);
  4784. var type = this.flowParseAnonFunctionWithoutParens();
  4785. node.types = [type];
  4786. while (this.eat(types.bitwiseAND)) {
  4787. node.types.push(this.flowParseAnonFunctionWithoutParens());
  4788. }
  4789. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  4790. };
  4791. pp$8.flowParseUnionType = function () {
  4792. var node = this.startNode();
  4793. this.eat(types.bitwiseOR);
  4794. var type = this.flowParseIntersectionType();
  4795. node.types = [type];
  4796. while (this.eat(types.bitwiseOR)) {
  4797. node.types.push(this.flowParseIntersectionType());
  4798. }
  4799. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  4800. };
  4801. pp$8.flowParseType = function () {
  4802. var oldInType = this.state.inType;
  4803. this.state.inType = true;
  4804. var type = this.flowParseUnionType();
  4805. this.state.inType = oldInType;
  4806. return type;
  4807. };
  4808. pp$8.flowParseTypeAnnotation = function () {
  4809. var node = this.startNode();
  4810. node.typeAnnotation = this.flowParseTypeInitialiser();
  4811. return this.finishNode(node, "TypeAnnotation");
  4812. };
  4813. pp$8.flowParseTypeAndPredicateAnnotation = function () {
  4814. var node = this.startNode();
  4815. var _flowParseTypeAndPred2 = this.flowParseTypeAndPredicateInitialiser();
  4816. node.typeAnnotation = _flowParseTypeAndPred2[0];
  4817. node.predicate = _flowParseTypeAndPred2[1];
  4818. return this.finishNode(node, "TypeAnnotation");
  4819. };
  4820. pp$8.flowParseTypeAnnotatableIdentifier = function () {
  4821. var ident = this.flowParseRestrictedIdentifier();
  4822. if (this.match(types.colon)) {
  4823. ident.typeAnnotation = this.flowParseTypeAnnotation();
  4824. this.finishNode(ident, ident.type);
  4825. }
  4826. return ident;
  4827. };
  4828. pp$8.typeCastToParameter = function (node) {
  4829. node.expression.typeAnnotation = node.typeAnnotation;
  4830. return this.finishNodeAt(node.expression, node.expression.type, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  4831. };
  4832. pp$8.flowParseVariance = function () {
  4833. var variance = null;
  4834. if (this.match(types.plusMin)) {
  4835. if (this.state.value === "+") {
  4836. variance = "plus";
  4837. } else if (this.state.value === "-") {
  4838. variance = "minus";
  4839. }
  4840. this.next();
  4841. }
  4842. return variance;
  4843. };
  4844. var flowPlugin = function (instance) {
  4845. // plain function return types: function name(): string {}
  4846. instance.extend("parseFunctionBody", function (inner) {
  4847. return function (node, allowExpression) {
  4848. if (this.match(types.colon) && !allowExpression) {
  4849. // if allowExpression is true then we're parsing an arrow function and if
  4850. // there's a return type then it's been handled elsewhere
  4851. node.returnType = this.flowParseTypeAndPredicateAnnotation();
  4852. }
  4853. return inner.call(this, node, allowExpression);
  4854. };
  4855. });
  4856. // interfaces
  4857. instance.extend("parseStatement", function (inner) {
  4858. return function (declaration, topLevel) {
  4859. // strict mode handling of `interface` since it's a reserved word
  4860. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  4861. var node = this.startNode();
  4862. this.next();
  4863. return this.flowParseInterface(node);
  4864. } else {
  4865. return inner.call(this, declaration, topLevel);
  4866. }
  4867. };
  4868. });
  4869. // declares, interfaces and type aliases
  4870. instance.extend("parseExpressionStatement", function (inner) {
  4871. return function (node, expr) {
  4872. if (expr.type === "Identifier") {
  4873. if (expr.name === "declare") {
  4874. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  4875. return this.flowParseDeclare(node);
  4876. }
  4877. } else if (this.match(types.name)) {
  4878. if (expr.name === "interface") {
  4879. return this.flowParseInterface(node);
  4880. } else if (expr.name === "type") {
  4881. return this.flowParseTypeAlias(node);
  4882. } else if (expr.name === "opaque") {
  4883. return this.flowParseOpaqueType(node, false);
  4884. }
  4885. }
  4886. }
  4887. return inner.call(this, node, expr);
  4888. };
  4889. });
  4890. // export type
  4891. instance.extend("shouldParseExportDeclaration", function (inner) {
  4892. return function () {
  4893. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || inner.call(this);
  4894. };
  4895. });
  4896. instance.extend("isExportDefaultSpecifier", function (inner) {
  4897. return function () {
  4898. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque")) {
  4899. return false;
  4900. }
  4901. return inner.call(this);
  4902. };
  4903. });
  4904. instance.extend("parseConditional", function (inner) {
  4905. return function (expr, noIn, startPos, startLoc, refNeedsArrowPos) {
  4906. // only do the expensive clone if there is a question mark
  4907. // and if we come from inside parens
  4908. if (refNeedsArrowPos && this.match(types.question)) {
  4909. var state = this.state.clone();
  4910. try {
  4911. return inner.call(this, expr, noIn, startPos, startLoc);
  4912. } catch (err) {
  4913. if (err instanceof SyntaxError) {
  4914. this.state = state;
  4915. refNeedsArrowPos.start = err.pos || this.state.start;
  4916. return expr;
  4917. } else {
  4918. // istanbul ignore next: no such error is expected
  4919. throw err;
  4920. }
  4921. }
  4922. }
  4923. return inner.call(this, expr, noIn, startPos, startLoc);
  4924. };
  4925. });
  4926. instance.extend("parseParenItem", function (inner) {
  4927. return function (node, startPos, startLoc) {
  4928. node = inner.call(this, node, startPos, startLoc);
  4929. if (this.eat(types.question)) {
  4930. node.optional = true;
  4931. }
  4932. if (this.match(types.colon)) {
  4933. var typeCastNode = this.startNodeAt(startPos, startLoc);
  4934. typeCastNode.expression = node;
  4935. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  4936. return this.finishNode(typeCastNode, "TypeCastExpression");
  4937. }
  4938. return node;
  4939. };
  4940. });
  4941. instance.extend("parseExport", function (inner) {
  4942. return function (node) {
  4943. node = inner.call(this, node);
  4944. if (node.type === "ExportNamedDeclaration") {
  4945. node.exportKind = node.exportKind || "value";
  4946. }
  4947. return node;
  4948. };
  4949. });
  4950. instance.extend("parseExportDeclaration", function (inner) {
  4951. return function (node) {
  4952. if (this.isContextual("type")) {
  4953. node.exportKind = "type";
  4954. var declarationNode = this.startNode();
  4955. this.next();
  4956. if (this.match(types.braceL)) {
  4957. // export type { foo, bar };
  4958. node.specifiers = this.parseExportSpecifiers();
  4959. this.parseExportFrom(node);
  4960. return null;
  4961. } else {
  4962. // export type Foo = Bar;
  4963. return this.flowParseTypeAlias(declarationNode);
  4964. }
  4965. } else if (this.isContextual("opaque")) {
  4966. node.exportKind = "type";
  4967. var _declarationNode = this.startNode();
  4968. this.next();
  4969. // export opaque type Foo = Bar;
  4970. return this.flowParseOpaqueType(_declarationNode, false);
  4971. } else if (this.isContextual("interface")) {
  4972. node.exportKind = "type";
  4973. var _declarationNode2 = this.startNode();
  4974. this.next();
  4975. return this.flowParseInterface(_declarationNode2);
  4976. } else {
  4977. return inner.call(this, node);
  4978. }
  4979. };
  4980. });
  4981. instance.extend("parseClassId", function (inner) {
  4982. return function (node) {
  4983. inner.apply(this, arguments);
  4984. if (this.isRelational("<")) {
  4985. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4986. }
  4987. };
  4988. });
  4989. // don't consider `void` to be a keyword as then it'll use the void token type
  4990. // and set startExpr
  4991. instance.extend("isKeyword", function (inner) {
  4992. return function (name) {
  4993. if (this.state.inType && name === "void") {
  4994. return false;
  4995. } else {
  4996. return inner.call(this, name);
  4997. }
  4998. };
  4999. });
  5000. // ensure that inside flow types, we bypass the jsx parser plugin
  5001. instance.extend("readToken", function (inner) {
  5002. return function (code) {
  5003. if (this.state.inType && (code === 62 || code === 60)) {
  5004. return this.finishOp(types.relational, 1);
  5005. } else {
  5006. return inner.call(this, code);
  5007. }
  5008. };
  5009. });
  5010. // don't lex any token as a jsx one inside a flow type
  5011. instance.extend("jsx_readToken", function (inner) {
  5012. return function () {
  5013. if (!this.state.inType) return inner.call(this);
  5014. };
  5015. });
  5016. instance.extend("toAssignable", function (inner) {
  5017. return function (node, isBinding, contextDescription) {
  5018. if (node.type === "TypeCastExpression") {
  5019. return inner.call(this, this.typeCastToParameter(node), isBinding, contextDescription);
  5020. } else {
  5021. return inner.call(this, node, isBinding, contextDescription);
  5022. }
  5023. };
  5024. });
  5025. // turn type casts that we found in function parameter head into type annotated params
  5026. instance.extend("toAssignableList", function (inner) {
  5027. return function (exprList, isBinding, contextDescription) {
  5028. for (var i = 0; i < exprList.length; i++) {
  5029. var expr = exprList[i];
  5030. if (expr && expr.type === "TypeCastExpression") {
  5031. exprList[i] = this.typeCastToParameter(expr);
  5032. }
  5033. }
  5034. return inner.call(this, exprList, isBinding, contextDescription);
  5035. };
  5036. });
  5037. // this is a list of nodes, from something like a call expression, we need to filter the
  5038. // type casts that we've found that are illegal in this context
  5039. instance.extend("toReferencedList", function () {
  5040. return function (exprList) {
  5041. for (var i = 0; i < exprList.length; i++) {
  5042. var expr = exprList[i];
  5043. if (expr && expr._exprListItem && expr.type === "TypeCastExpression") {
  5044. this.raise(expr.start, "Unexpected type cast");
  5045. }
  5046. }
  5047. return exprList;
  5048. };
  5049. });
  5050. // parse an item inside a expression list eg. `(NODE, NODE)` where NODE represents
  5051. // the position where this function is called
  5052. instance.extend("parseExprListItem", function (inner) {
  5053. return function () {
  5054. var container = this.startNode();
  5055. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  5056. args[_key] = arguments[_key];
  5057. }
  5058. var node = inner.call.apply(inner, [this].concat(args));
  5059. if (this.match(types.colon)) {
  5060. container._exprListItem = true;
  5061. container.expression = node;
  5062. container.typeAnnotation = this.flowParseTypeAnnotation();
  5063. return this.finishNode(container, "TypeCastExpression");
  5064. } else {
  5065. return node;
  5066. }
  5067. };
  5068. });
  5069. instance.extend("checkLVal", function (inner) {
  5070. return function (node) {
  5071. if (node.type !== "TypeCastExpression") {
  5072. return inner.apply(this, arguments);
  5073. }
  5074. };
  5075. });
  5076. // parse class property type annotations
  5077. instance.extend("parseClassProperty", function (inner) {
  5078. return function (node) {
  5079. delete node.variancePos;
  5080. if (this.match(types.colon)) {
  5081. node.typeAnnotation = this.flowParseTypeAnnotation();
  5082. }
  5083. return inner.call(this, node);
  5084. };
  5085. });
  5086. // determine whether or not we're currently in the position where a class method would appear
  5087. instance.extend("isClassMethod", function (inner) {
  5088. return function () {
  5089. return this.isRelational("<") || inner.call(this);
  5090. };
  5091. });
  5092. // determine whether or not we're currently in the position where a class property would appear
  5093. instance.extend("isClassProperty", function (inner) {
  5094. return function () {
  5095. return this.match(types.colon) || inner.call(this);
  5096. };
  5097. });
  5098. instance.extend("isNonstaticConstructor", function (inner) {
  5099. return function (method) {
  5100. return !this.match(types.colon) && inner.call(this, method);
  5101. };
  5102. });
  5103. // parse type parameters for class methods
  5104. instance.extend("parseClassMethod", function (inner) {
  5105. return function (classBody, method) {
  5106. if (method.variance) {
  5107. this.unexpected(method.variancePos);
  5108. }
  5109. delete method.variance;
  5110. delete method.variancePos;
  5111. if (this.isRelational("<")) {
  5112. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5113. }
  5114. for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
  5115. args[_key2 - 2] = arguments[_key2];
  5116. }
  5117. inner.call.apply(inner, [this, classBody, method].concat(args));
  5118. };
  5119. });
  5120. // parse a the super class type parameters and implements
  5121. instance.extend("parseClassSuper", function (inner) {
  5122. return function (node, isStatement) {
  5123. inner.call(this, node, isStatement);
  5124. if (node.superClass && this.isRelational("<")) {
  5125. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  5126. }
  5127. if (this.isContextual("implements")) {
  5128. this.next();
  5129. var implemented = node.implements = [];
  5130. do {
  5131. var _node = this.startNode();
  5132. _node.id = this.parseIdentifier();
  5133. if (this.isRelational("<")) {
  5134. _node.typeParameters = this.flowParseTypeParameterInstantiation();
  5135. } else {
  5136. _node.typeParameters = null;
  5137. }
  5138. implemented.push(this.finishNode(_node, "ClassImplements"));
  5139. } while (this.eat(types.comma));
  5140. }
  5141. };
  5142. });
  5143. instance.extend("parsePropertyName", function (inner) {
  5144. return function (node) {
  5145. var variancePos = this.state.start;
  5146. var variance = this.flowParseVariance();
  5147. var key = inner.call(this, node);
  5148. node.variance = variance;
  5149. node.variancePos = variancePos;
  5150. return key;
  5151. };
  5152. });
  5153. // parse type parameters for object method shorthand
  5154. instance.extend("parseObjPropValue", function (inner) {
  5155. return function (prop) {
  5156. if (prop.variance) {
  5157. this.unexpected(prop.variancePos);
  5158. }
  5159. delete prop.variance;
  5160. delete prop.variancePos;
  5161. var typeParameters = void 0;
  5162. // method shorthand
  5163. if (this.isRelational("<")) {
  5164. typeParameters = this.flowParseTypeParameterDeclaration();
  5165. if (!this.match(types.parenL)) this.unexpected();
  5166. }
  5167. inner.apply(this, arguments);
  5168. // add typeParameters if we found them
  5169. if (typeParameters) {
  5170. (prop.value || prop).typeParameters = typeParameters;
  5171. }
  5172. };
  5173. });
  5174. instance.extend("parseAssignableListItemTypes", function () {
  5175. return function (param) {
  5176. if (this.eat(types.question)) {
  5177. param.optional = true;
  5178. }
  5179. if (this.match(types.colon)) {
  5180. param.typeAnnotation = this.flowParseTypeAnnotation();
  5181. }
  5182. this.finishNode(param, param.type);
  5183. return param;
  5184. };
  5185. });
  5186. instance.extend("parseMaybeDefault", function (inner) {
  5187. return function () {
  5188. for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  5189. args[_key3] = arguments[_key3];
  5190. }
  5191. var node = inner.apply(this, args);
  5192. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5193. this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`");
  5194. }
  5195. return node;
  5196. };
  5197. });
  5198. // parse typeof and type imports
  5199. instance.extend("parseImportSpecifiers", function (inner) {
  5200. return function (node) {
  5201. node.importKind = "value";
  5202. var kind = null;
  5203. if (this.match(types._typeof)) {
  5204. kind = "typeof";
  5205. } else if (this.isContextual("type")) {
  5206. kind = "type";
  5207. }
  5208. if (kind) {
  5209. var lh = this.lookahead();
  5210. if (lh.type === types.name && lh.value !== "from" || lh.type === types.braceL || lh.type === types.star) {
  5211. this.next();
  5212. node.importKind = kind;
  5213. }
  5214. }
  5215. inner.call(this, node);
  5216. };
  5217. });
  5218. // parse import-type/typeof shorthand
  5219. instance.extend("parseImportSpecifier", function () {
  5220. return function (node) {
  5221. var specifier = this.startNode();
  5222. var firstIdentLoc = this.state.start;
  5223. var firstIdent = this.parseIdentifier(true);
  5224. var specifierTypeKind = null;
  5225. if (firstIdent.name === "type") {
  5226. specifierTypeKind = "type";
  5227. } else if (firstIdent.name === "typeof") {
  5228. specifierTypeKind = "typeof";
  5229. }
  5230. var isBinding = false;
  5231. if (this.isContextual("as")) {
  5232. var as_ident = this.parseIdentifier(true);
  5233. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  5234. // `import {type as ,` or `import {type as }`
  5235. specifier.imported = as_ident;
  5236. specifier.importKind = specifierTypeKind;
  5237. specifier.local = as_ident.__clone();
  5238. } else {
  5239. // `import {type as foo`
  5240. specifier.imported = firstIdent;
  5241. specifier.importKind = null;
  5242. specifier.local = this.parseIdentifier();
  5243. }
  5244. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  5245. // `import {type foo`
  5246. specifier.imported = this.parseIdentifier(true);
  5247. specifier.importKind = specifierTypeKind;
  5248. if (this.eatContextual("as")) {
  5249. specifier.local = this.parseIdentifier();
  5250. } else {
  5251. isBinding = true;
  5252. specifier.local = specifier.imported.__clone();
  5253. }
  5254. } else {
  5255. isBinding = true;
  5256. specifier.imported = firstIdent;
  5257. specifier.importKind = null;
  5258. specifier.local = specifier.imported.__clone();
  5259. }
  5260. if ((node.importKind === "type" || node.importKind === "typeof") && (specifier.importKind === "type" || specifier.importKind === "typeof")) {
  5261. this.raise(firstIdentLoc, "`The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements`");
  5262. }
  5263. if (isBinding) this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  5264. this.checkLVal(specifier.local, true, undefined, "import specifier");
  5265. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  5266. };
  5267. });
  5268. // parse function type parameters - function foo<T>() {}
  5269. instance.extend("parseFunctionParams", function (inner) {
  5270. return function (node) {
  5271. if (this.isRelational("<")) {
  5272. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5273. }
  5274. inner.call(this, node);
  5275. };
  5276. });
  5277. // parse flow type annotations on variable declarator heads - let foo: string = bar
  5278. instance.extend("parseVarHead", function (inner) {
  5279. return function (decl) {
  5280. inner.call(this, decl);
  5281. if (this.match(types.colon)) {
  5282. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5283. this.finishNode(decl.id, decl.id.type);
  5284. }
  5285. };
  5286. });
  5287. // parse the return type of an async arrow function - let foo = (async (): number => {});
  5288. instance.extend("parseAsyncArrowFromCallExpression", function (inner) {
  5289. return function (node, call) {
  5290. if (this.match(types.colon)) {
  5291. var oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5292. this.state.noAnonFunctionType = true;
  5293. node.returnType = this.flowParseTypeAnnotation();
  5294. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5295. }
  5296. return inner.call(this, node, call);
  5297. };
  5298. });
  5299. // todo description
  5300. instance.extend("shouldParseAsyncArrow", function (inner) {
  5301. return function () {
  5302. return this.match(types.colon) || inner.call(this);
  5303. };
  5304. });
  5305. // We need to support type parameter declarations for arrow functions. This
  5306. // is tricky. There are three situations we need to handle
  5307. //
  5308. // 1. This is either JSX or an arrow function. We'll try JSX first. If that
  5309. // fails, we'll try an arrow function. If that fails, we'll throw the JSX
  5310. // error.
  5311. // 2. This is an arrow function. We'll parse the type parameter declaration,
  5312. // parse the rest, make sure the rest is an arrow function, and go from
  5313. // there
  5314. // 3. This is neither. Just call the inner function
  5315. instance.extend("parseMaybeAssign", function (inner) {
  5316. return function () {
  5317. var jsxError = null;
  5318. for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  5319. args[_key4] = arguments[_key4];
  5320. }
  5321. if (types.jsxTagStart && this.match(types.jsxTagStart)) {
  5322. var state = this.state.clone();
  5323. try {
  5324. return inner.apply(this, args);
  5325. } catch (err) {
  5326. if (err instanceof SyntaxError) {
  5327. this.state = state;
  5328. // Remove `tc.j_expr` and `tc.j_oTag` from context added
  5329. // by parsing `jsxTagStart` to stop the JSX plugin from
  5330. // messing with the tokens
  5331. this.state.context.length -= 2;
  5332. jsxError = err;
  5333. } else {
  5334. // istanbul ignore next: no such error is expected
  5335. throw err;
  5336. }
  5337. }
  5338. }
  5339. if (jsxError != null || this.isRelational("<")) {
  5340. var arrowExpression = void 0;
  5341. var typeParameters = void 0;
  5342. try {
  5343. typeParameters = this.flowParseTypeParameterDeclaration();
  5344. arrowExpression = inner.apply(this, args);
  5345. arrowExpression.typeParameters = typeParameters;
  5346. arrowExpression.start = typeParameters.start;
  5347. arrowExpression.loc.start = typeParameters.loc.start;
  5348. } catch (err) {
  5349. throw jsxError || err;
  5350. }
  5351. if (arrowExpression.type === "ArrowFunctionExpression") {
  5352. return arrowExpression;
  5353. } else if (jsxError != null) {
  5354. throw jsxError;
  5355. } else {
  5356. this.raise(typeParameters.start, "Expected an arrow function after this type parameter declaration");
  5357. }
  5358. }
  5359. return inner.apply(this, args);
  5360. };
  5361. });
  5362. // handle return types for arrow functions
  5363. instance.extend("parseArrow", function (inner) {
  5364. return function (node) {
  5365. if (this.match(types.colon)) {
  5366. var state = this.state.clone();
  5367. try {
  5368. var oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5369. this.state.noAnonFunctionType = true;
  5370. var returnType = this.flowParseTypeAndPredicateAnnotation();
  5371. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5372. if (this.canInsertSemicolon()) this.unexpected();
  5373. if (!this.match(types.arrow)) this.unexpected();
  5374. // assign after it is clear it is an arrow
  5375. node.returnType = returnType;
  5376. } catch (err) {
  5377. if (err instanceof SyntaxError) {
  5378. this.state = state;
  5379. } else {
  5380. // istanbul ignore next: no such error is expected
  5381. throw err;
  5382. }
  5383. }
  5384. }
  5385. return inner.call(this, node);
  5386. };
  5387. });
  5388. instance.extend("shouldParseArrow", function (inner) {
  5389. return function () {
  5390. return this.match(types.colon) || inner.call(this);
  5391. };
  5392. });
  5393. };
  5394. // Adapted from String.fromcodepoint to export the function without modifying String
  5395. /*! https://mths.be/fromcodepoint v0.2.1 by @mathias */
  5396. // The MIT License (MIT)
  5397. // Copyright (c) Mathias Bynens
  5398. //
  5399. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  5400. // associated documentation files (the "Software"), to deal in the Software without restriction,
  5401. // including without limitation the rights to use, copy, modify, merge, publish, distribute,
  5402. // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  5403. // furnished to do so, subject to the following conditions:
  5404. //
  5405. // The above copyright notice and this permission notice shall be included in all copies or
  5406. // substantial portions of the Software.
  5407. //
  5408. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
  5409. // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  5410. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5411. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5412. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  5413. var fromCodePoint = String.fromCodePoint;
  5414. if (!fromCodePoint) {
  5415. var stringFromCharCode = String.fromCharCode;
  5416. var floor = Math.floor;
  5417. fromCodePoint = function fromCodePoint() {
  5418. var MAX_SIZE = 0x4000;
  5419. var codeUnits = [];
  5420. var highSurrogate = void 0;
  5421. var lowSurrogate = void 0;
  5422. var index = -1;
  5423. var length = arguments.length;
  5424. if (!length) {
  5425. return "";
  5426. }
  5427. var result = "";
  5428. while (++index < length) {
  5429. var codePoint = Number(arguments[index]);
  5430. if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  5431. codePoint < 0 || // not a valid Unicode code point
  5432. codePoint > 0x10FFFF || // not a valid Unicode code point
  5433. floor(codePoint) != codePoint // not an integer
  5434. ) {
  5435. throw RangeError("Invalid code point: " + codePoint);
  5436. }
  5437. if (codePoint <= 0xFFFF) {
  5438. // BMP code point
  5439. codeUnits.push(codePoint);
  5440. } else {
  5441. // Astral code point; split in surrogate halves
  5442. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  5443. codePoint -= 0x10000;
  5444. highSurrogate = (codePoint >> 10) + 0xD800;
  5445. lowSurrogate = codePoint % 0x400 + 0xDC00;
  5446. codeUnits.push(highSurrogate, lowSurrogate);
  5447. }
  5448. if (index + 1 == length || codeUnits.length > MAX_SIZE) {
  5449. result += stringFromCharCode.apply(null, codeUnits);
  5450. codeUnits.length = 0;
  5451. }
  5452. }
  5453. return result;
  5454. };
  5455. }
  5456. var fromCodePoint$1 = fromCodePoint;
  5457. var XHTMLEntities = {
  5458. quot: "\"",
  5459. amp: "&",
  5460. apos: "'",
  5461. lt: "<",
  5462. gt: ">",
  5463. nbsp: "\xA0",
  5464. iexcl: "\xA1",
  5465. cent: "\xA2",
  5466. pound: "\xA3",
  5467. curren: "\xA4",
  5468. yen: "\xA5",
  5469. brvbar: "\xA6",
  5470. sect: "\xA7",
  5471. uml: "\xA8",
  5472. copy: "\xA9",
  5473. ordf: "\xAA",
  5474. laquo: "\xAB",
  5475. not: "\xAC",
  5476. shy: "\xAD",
  5477. reg: "\xAE",
  5478. macr: "\xAF",
  5479. deg: "\xB0",
  5480. plusmn: "\xB1",
  5481. sup2: "\xB2",
  5482. sup3: "\xB3",
  5483. acute: "\xB4",
  5484. micro: "\xB5",
  5485. para: "\xB6",
  5486. middot: "\xB7",
  5487. cedil: "\xB8",
  5488. sup1: "\xB9",
  5489. ordm: "\xBA",
  5490. raquo: "\xBB",
  5491. frac14: "\xBC",
  5492. frac12: "\xBD",
  5493. frac34: "\xBE",
  5494. iquest: "\xBF",
  5495. Agrave: "\xC0",
  5496. Aacute: "\xC1",
  5497. Acirc: "\xC2",
  5498. Atilde: "\xC3",
  5499. Auml: "\xC4",
  5500. Aring: "\xC5",
  5501. AElig: "\xC6",
  5502. Ccedil: "\xC7",
  5503. Egrave: "\xC8",
  5504. Eacute: "\xC9",
  5505. Ecirc: "\xCA",
  5506. Euml: "\xCB",
  5507. Igrave: "\xCC",
  5508. Iacute: "\xCD",
  5509. Icirc: "\xCE",
  5510. Iuml: "\xCF",
  5511. ETH: "\xD0",
  5512. Ntilde: "\xD1",
  5513. Ograve: "\xD2",
  5514. Oacute: "\xD3",
  5515. Ocirc: "\xD4",
  5516. Otilde: "\xD5",
  5517. Ouml: "\xD6",
  5518. times: "\xD7",
  5519. Oslash: "\xD8",
  5520. Ugrave: "\xD9",
  5521. Uacute: "\xDA",
  5522. Ucirc: "\xDB",
  5523. Uuml: "\xDC",
  5524. Yacute: "\xDD",
  5525. THORN: "\xDE",
  5526. szlig: "\xDF",
  5527. agrave: "\xE0",
  5528. aacute: "\xE1",
  5529. acirc: "\xE2",
  5530. atilde: "\xE3",
  5531. auml: "\xE4",
  5532. aring: "\xE5",
  5533. aelig: "\xE6",
  5534. ccedil: "\xE7",
  5535. egrave: "\xE8",
  5536. eacute: "\xE9",
  5537. ecirc: "\xEA",
  5538. euml: "\xEB",
  5539. igrave: "\xEC",
  5540. iacute: "\xED",
  5541. icirc: "\xEE",
  5542. iuml: "\xEF",
  5543. eth: "\xF0",
  5544. ntilde: "\xF1",
  5545. ograve: "\xF2",
  5546. oacute: "\xF3",
  5547. ocirc: "\xF4",
  5548. otilde: "\xF5",
  5549. ouml: "\xF6",
  5550. divide: "\xF7",
  5551. oslash: "\xF8",
  5552. ugrave: "\xF9",
  5553. uacute: "\xFA",
  5554. ucirc: "\xFB",
  5555. uuml: "\xFC",
  5556. yacute: "\xFD",
  5557. thorn: "\xFE",
  5558. yuml: "\xFF",
  5559. OElig: "\u0152",
  5560. oelig: "\u0153",
  5561. Scaron: "\u0160",
  5562. scaron: "\u0161",
  5563. Yuml: "\u0178",
  5564. fnof: "\u0192",
  5565. circ: "\u02C6",
  5566. tilde: "\u02DC",
  5567. Alpha: "\u0391",
  5568. Beta: "\u0392",
  5569. Gamma: "\u0393",
  5570. Delta: "\u0394",
  5571. Epsilon: "\u0395",
  5572. Zeta: "\u0396",
  5573. Eta: "\u0397",
  5574. Theta: "\u0398",
  5575. Iota: "\u0399",
  5576. Kappa: "\u039A",
  5577. Lambda: "\u039B",
  5578. Mu: "\u039C",
  5579. Nu: "\u039D",
  5580. Xi: "\u039E",
  5581. Omicron: "\u039F",
  5582. Pi: "\u03A0",
  5583. Rho: "\u03A1",
  5584. Sigma: "\u03A3",
  5585. Tau: "\u03A4",
  5586. Upsilon: "\u03A5",
  5587. Phi: "\u03A6",
  5588. Chi: "\u03A7",
  5589. Psi: "\u03A8",
  5590. Omega: "\u03A9",
  5591. alpha: "\u03B1",
  5592. beta: "\u03B2",
  5593. gamma: "\u03B3",
  5594. delta: "\u03B4",
  5595. epsilon: "\u03B5",
  5596. zeta: "\u03B6",
  5597. eta: "\u03B7",
  5598. theta: "\u03B8",
  5599. iota: "\u03B9",
  5600. kappa: "\u03BA",
  5601. lambda: "\u03BB",
  5602. mu: "\u03BC",
  5603. nu: "\u03BD",
  5604. xi: "\u03BE",
  5605. omicron: "\u03BF",
  5606. pi: "\u03C0",
  5607. rho: "\u03C1",
  5608. sigmaf: "\u03C2",
  5609. sigma: "\u03C3",
  5610. tau: "\u03C4",
  5611. upsilon: "\u03C5",
  5612. phi: "\u03C6",
  5613. chi: "\u03C7",
  5614. psi: "\u03C8",
  5615. omega: "\u03C9",
  5616. thetasym: "\u03D1",
  5617. upsih: "\u03D2",
  5618. piv: "\u03D6",
  5619. ensp: "\u2002",
  5620. emsp: "\u2003",
  5621. thinsp: "\u2009",
  5622. zwnj: "\u200C",
  5623. zwj: "\u200D",
  5624. lrm: "\u200E",
  5625. rlm: "\u200F",
  5626. ndash: "\u2013",
  5627. mdash: "\u2014",
  5628. lsquo: "\u2018",
  5629. rsquo: "\u2019",
  5630. sbquo: "\u201A",
  5631. ldquo: "\u201C",
  5632. rdquo: "\u201D",
  5633. bdquo: "\u201E",
  5634. dagger: "\u2020",
  5635. Dagger: "\u2021",
  5636. bull: "\u2022",
  5637. hellip: "\u2026",
  5638. permil: "\u2030",
  5639. prime: "\u2032",
  5640. Prime: "\u2033",
  5641. lsaquo: "\u2039",
  5642. rsaquo: "\u203A",
  5643. oline: "\u203E",
  5644. frasl: "\u2044",
  5645. euro: "\u20AC",
  5646. image: "\u2111",
  5647. weierp: "\u2118",
  5648. real: "\u211C",
  5649. trade: "\u2122",
  5650. alefsym: "\u2135",
  5651. larr: "\u2190",
  5652. uarr: "\u2191",
  5653. rarr: "\u2192",
  5654. darr: "\u2193",
  5655. harr: "\u2194",
  5656. crarr: "\u21B5",
  5657. lArr: "\u21D0",
  5658. uArr: "\u21D1",
  5659. rArr: "\u21D2",
  5660. dArr: "\u21D3",
  5661. hArr: "\u21D4",
  5662. forall: "\u2200",
  5663. part: "\u2202",
  5664. exist: "\u2203",
  5665. empty: "\u2205",
  5666. nabla: "\u2207",
  5667. isin: "\u2208",
  5668. notin: "\u2209",
  5669. ni: "\u220B",
  5670. prod: "\u220F",
  5671. sum: "\u2211",
  5672. minus: "\u2212",
  5673. lowast: "\u2217",
  5674. radic: "\u221A",
  5675. prop: "\u221D",
  5676. infin: "\u221E",
  5677. ang: "\u2220",
  5678. and: "\u2227",
  5679. or: "\u2228",
  5680. cap: "\u2229",
  5681. cup: "\u222A",
  5682. "int": "\u222B",
  5683. there4: "\u2234",
  5684. sim: "\u223C",
  5685. cong: "\u2245",
  5686. asymp: "\u2248",
  5687. ne: "\u2260",
  5688. equiv: "\u2261",
  5689. le: "\u2264",
  5690. ge: "\u2265",
  5691. sub: "\u2282",
  5692. sup: "\u2283",
  5693. nsub: "\u2284",
  5694. sube: "\u2286",
  5695. supe: "\u2287",
  5696. oplus: "\u2295",
  5697. otimes: "\u2297",
  5698. perp: "\u22A5",
  5699. sdot: "\u22C5",
  5700. lceil: "\u2308",
  5701. rceil: "\u2309",
  5702. lfloor: "\u230A",
  5703. rfloor: "\u230B",
  5704. lang: "\u2329",
  5705. rang: "\u232A",
  5706. loz: "\u25CA",
  5707. spades: "\u2660",
  5708. clubs: "\u2663",
  5709. hearts: "\u2665",
  5710. diams: "\u2666"
  5711. };
  5712. var HEX_NUMBER = /^[\da-fA-F]+$/;
  5713. var DECIMAL_NUMBER = /^\d+$/;
  5714. types$1.j_oTag = new TokContext("<tag", false);
  5715. types$1.j_cTag = new TokContext("</tag", false);
  5716. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  5717. types.jsxName = new TokenType("jsxName");
  5718. types.jsxText = new TokenType("jsxText", { beforeExpr: true });
  5719. types.jsxTagStart = new TokenType("jsxTagStart", { startsExpr: true });
  5720. types.jsxTagEnd = new TokenType("jsxTagEnd");
  5721. types.jsxTagStart.updateContext = function () {
  5722. this.state.context.push(types$1.j_expr); // treat as beginning of JSX expression
  5723. this.state.context.push(types$1.j_oTag); // start opening tag context
  5724. this.state.exprAllowed = false;
  5725. };
  5726. types.jsxTagEnd.updateContext = function (prevType) {
  5727. var out = this.state.context.pop();
  5728. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  5729. this.state.context.pop();
  5730. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  5731. } else {
  5732. this.state.exprAllowed = true;
  5733. }
  5734. };
  5735. var pp$9 = Parser.prototype;
  5736. // Reads inline JSX contents token.
  5737. pp$9.jsxReadToken = function () {
  5738. var out = "";
  5739. var chunkStart = this.state.pos;
  5740. for (;;) {
  5741. if (this.state.pos >= this.input.length) {
  5742. this.raise(this.state.start, "Unterminated JSX contents");
  5743. }
  5744. var ch = this.input.charCodeAt(this.state.pos);
  5745. switch (ch) {
  5746. case 60: // "<"
  5747. case 123:
  5748. // "{"
  5749. if (this.state.pos === this.state.start) {
  5750. if (ch === 60 && this.state.exprAllowed) {
  5751. ++this.state.pos;
  5752. return this.finishToken(types.jsxTagStart);
  5753. }
  5754. return this.getTokenFromCode(ch);
  5755. }
  5756. out += this.input.slice(chunkStart, this.state.pos);
  5757. return this.finishToken(types.jsxText, out);
  5758. case 38:
  5759. // "&"
  5760. out += this.input.slice(chunkStart, this.state.pos);
  5761. out += this.jsxReadEntity();
  5762. chunkStart = this.state.pos;
  5763. break;
  5764. default:
  5765. if (isNewLine(ch)) {
  5766. out += this.input.slice(chunkStart, this.state.pos);
  5767. out += this.jsxReadNewLine(true);
  5768. chunkStart = this.state.pos;
  5769. } else {
  5770. ++this.state.pos;
  5771. }
  5772. }
  5773. }
  5774. };
  5775. pp$9.jsxReadNewLine = function (normalizeCRLF) {
  5776. var ch = this.input.charCodeAt(this.state.pos);
  5777. var out = void 0;
  5778. ++this.state.pos;
  5779. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  5780. ++this.state.pos;
  5781. out = normalizeCRLF ? "\n" : "\r\n";
  5782. } else {
  5783. out = String.fromCharCode(ch);
  5784. }
  5785. ++this.state.curLine;
  5786. this.state.lineStart = this.state.pos;
  5787. return out;
  5788. };
  5789. pp$9.jsxReadString = function (quote) {
  5790. var out = "";
  5791. var chunkStart = ++this.state.pos;
  5792. for (;;) {
  5793. if (this.state.pos >= this.input.length) {
  5794. this.raise(this.state.start, "Unterminated string constant");
  5795. }
  5796. var ch = this.input.charCodeAt(this.state.pos);
  5797. if (ch === quote) break;
  5798. if (ch === 38) {
  5799. // "&"
  5800. out += this.input.slice(chunkStart, this.state.pos);
  5801. out += this.jsxReadEntity();
  5802. chunkStart = this.state.pos;
  5803. } else if (isNewLine(ch)) {
  5804. out += this.input.slice(chunkStart, this.state.pos);
  5805. out += this.jsxReadNewLine(false);
  5806. chunkStart = this.state.pos;
  5807. } else {
  5808. ++this.state.pos;
  5809. }
  5810. }
  5811. out += this.input.slice(chunkStart, this.state.pos++);
  5812. return this.finishToken(types.string, out);
  5813. };
  5814. pp$9.jsxReadEntity = function () {
  5815. var str = "";
  5816. var count = 0;
  5817. var entity = void 0;
  5818. var ch = this.input[this.state.pos];
  5819. var startPos = ++this.state.pos;
  5820. while (this.state.pos < this.input.length && count++ < 10) {
  5821. ch = this.input[this.state.pos++];
  5822. if (ch === ";") {
  5823. if (str[0] === "#") {
  5824. if (str[1] === "x") {
  5825. str = str.substr(2);
  5826. if (HEX_NUMBER.test(str)) entity = fromCodePoint$1(parseInt(str, 16));
  5827. } else {
  5828. str = str.substr(1);
  5829. if (DECIMAL_NUMBER.test(str)) entity = fromCodePoint$1(parseInt(str, 10));
  5830. }
  5831. } else {
  5832. entity = XHTMLEntities[str];
  5833. }
  5834. break;
  5835. }
  5836. str += ch;
  5837. }
  5838. if (!entity) {
  5839. this.state.pos = startPos;
  5840. return "&";
  5841. }
  5842. return entity;
  5843. };
  5844. // Read a JSX identifier (valid tag or attribute name).
  5845. //
  5846. // Optimized version since JSX identifiers can"t contain
  5847. // escape characters and so can be read as single slice.
  5848. // Also assumes that first character was already checked
  5849. // by isIdentifierStart in readToken.
  5850. pp$9.jsxReadWord = function () {
  5851. var ch = void 0;
  5852. var start = this.state.pos;
  5853. do {
  5854. ch = this.input.charCodeAt(++this.state.pos);
  5855. } while (isIdentifierChar(ch) || ch === 45); // "-"
  5856. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  5857. };
  5858. // Transforms JSX element name to string.
  5859. function getQualifiedJSXName(object) {
  5860. if (object.type === "JSXIdentifier") {
  5861. return object.name;
  5862. }
  5863. if (object.type === "JSXNamespacedName") {
  5864. return object.namespace.name + ":" + object.name.name;
  5865. }
  5866. if (object.type === "JSXMemberExpression") {
  5867. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  5868. }
  5869. }
  5870. // Parse next token as JSX identifier
  5871. pp$9.jsxParseIdentifier = function () {
  5872. var node = this.startNode();
  5873. if (this.match(types.jsxName)) {
  5874. node.name = this.state.value;
  5875. } else if (this.state.type.keyword) {
  5876. node.name = this.state.type.keyword;
  5877. } else {
  5878. this.unexpected();
  5879. }
  5880. this.next();
  5881. return this.finishNode(node, "JSXIdentifier");
  5882. };
  5883. // Parse namespaced identifier.
  5884. pp$9.jsxParseNamespacedName = function () {
  5885. var startPos = this.state.start;
  5886. var startLoc = this.state.startLoc;
  5887. var name = this.jsxParseIdentifier();
  5888. if (!this.eat(types.colon)) return name;
  5889. var node = this.startNodeAt(startPos, startLoc);
  5890. node.namespace = name;
  5891. node.name = this.jsxParseIdentifier();
  5892. return this.finishNode(node, "JSXNamespacedName");
  5893. };
  5894. // Parses element name in any form - namespaced, member
  5895. // or single identifier.
  5896. pp$9.jsxParseElementName = function () {
  5897. var startPos = this.state.start;
  5898. var startLoc = this.state.startLoc;
  5899. var node = this.jsxParseNamespacedName();
  5900. while (this.eat(types.dot)) {
  5901. var newNode = this.startNodeAt(startPos, startLoc);
  5902. newNode.object = node;
  5903. newNode.property = this.jsxParseIdentifier();
  5904. node = this.finishNode(newNode, "JSXMemberExpression");
  5905. }
  5906. return node;
  5907. };
  5908. // Parses any type of JSX attribute value.
  5909. pp$9.jsxParseAttributeValue = function () {
  5910. var node = void 0;
  5911. switch (this.state.type) {
  5912. case types.braceL:
  5913. node = this.jsxParseExpressionContainer();
  5914. if (node.expression.type === "JSXEmptyExpression") {
  5915. this.raise(node.start, "JSX attributes must only be assigned a non-empty expression");
  5916. } else {
  5917. return node;
  5918. }
  5919. case types.jsxTagStart:
  5920. case types.string:
  5921. node = this.parseExprAtom();
  5922. node.extra = null;
  5923. return node;
  5924. default:
  5925. this.raise(this.state.start, "JSX value should be either an expression or a quoted JSX text");
  5926. }
  5927. };
  5928. // JSXEmptyExpression is unique type since it doesn't actually parse anything,
  5929. // and so it should start at the end of last read token (left brace) and finish
  5930. // at the beginning of the next one (right brace).
  5931. pp$9.jsxParseEmptyExpression = function () {
  5932. var node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  5933. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  5934. };
  5935. // Parse JSX spread child
  5936. pp$9.jsxParseSpreadChild = function () {
  5937. var node = this.startNode();
  5938. this.expect(types.braceL);
  5939. this.expect(types.ellipsis);
  5940. node.expression = this.parseExpression();
  5941. this.expect(types.braceR);
  5942. return this.finishNode(node, "JSXSpreadChild");
  5943. };
  5944. // Parses JSX expression enclosed into curly brackets.
  5945. pp$9.jsxParseExpressionContainer = function () {
  5946. var node = this.startNode();
  5947. this.next();
  5948. if (this.match(types.braceR)) {
  5949. node.expression = this.jsxParseEmptyExpression();
  5950. } else {
  5951. node.expression = this.parseExpression();
  5952. }
  5953. this.expect(types.braceR);
  5954. return this.finishNode(node, "JSXExpressionContainer");
  5955. };
  5956. // Parses following JSX attribute name-value pair.
  5957. pp$9.jsxParseAttribute = function () {
  5958. var node = this.startNode();
  5959. if (this.eat(types.braceL)) {
  5960. this.expect(types.ellipsis);
  5961. node.argument = this.parseMaybeAssign();
  5962. this.expect(types.braceR);
  5963. return this.finishNode(node, "JSXSpreadAttribute");
  5964. }
  5965. node.name = this.jsxParseNamespacedName();
  5966. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  5967. return this.finishNode(node, "JSXAttribute");
  5968. };
  5969. // Parses JSX opening tag starting after "<".
  5970. pp$9.jsxParseOpeningElementAt = function (startPos, startLoc) {
  5971. var node = this.startNodeAt(startPos, startLoc);
  5972. node.attributes = [];
  5973. node.name = this.jsxParseElementName();
  5974. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  5975. node.attributes.push(this.jsxParseAttribute());
  5976. }
  5977. node.selfClosing = this.eat(types.slash);
  5978. this.expect(types.jsxTagEnd);
  5979. return this.finishNode(node, "JSXOpeningElement");
  5980. };
  5981. // Parses JSX closing tag starting after "</".
  5982. pp$9.jsxParseClosingElementAt = function (startPos, startLoc) {
  5983. var node = this.startNodeAt(startPos, startLoc);
  5984. node.name = this.jsxParseElementName();
  5985. this.expect(types.jsxTagEnd);
  5986. return this.finishNode(node, "JSXClosingElement");
  5987. };
  5988. // Parses entire JSX element, including it"s opening tag
  5989. // (starting after "<"), attributes, contents and closing tag.
  5990. pp$9.jsxParseElementAt = function (startPos, startLoc) {
  5991. var node = this.startNodeAt(startPos, startLoc);
  5992. var children = [];
  5993. var openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  5994. var closingElement = null;
  5995. if (!openingElement.selfClosing) {
  5996. contents: for (;;) {
  5997. switch (this.state.type) {
  5998. case types.jsxTagStart:
  5999. startPos = this.state.start;startLoc = this.state.startLoc;
  6000. this.next();
  6001. if (this.eat(types.slash)) {
  6002. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  6003. break contents;
  6004. }
  6005. children.push(this.jsxParseElementAt(startPos, startLoc));
  6006. break;
  6007. case types.jsxText:
  6008. children.push(this.parseExprAtom());
  6009. break;
  6010. case types.braceL:
  6011. if (this.lookahead().type === types.ellipsis) {
  6012. children.push(this.jsxParseSpreadChild());
  6013. } else {
  6014. children.push(this.jsxParseExpressionContainer());
  6015. }
  6016. break;
  6017. // istanbul ignore next - should never happen
  6018. default:
  6019. this.unexpected();
  6020. }
  6021. }
  6022. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  6023. this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">");
  6024. }
  6025. }
  6026. node.openingElement = openingElement;
  6027. node.closingElement = closingElement;
  6028. node.children = children;
  6029. if (this.match(types.relational) && this.state.value === "<") {
  6030. this.raise(this.state.start, "Adjacent JSX elements must be wrapped in an enclosing tag");
  6031. }
  6032. return this.finishNode(node, "JSXElement");
  6033. };
  6034. // Parses entire JSX element from current position.
  6035. pp$9.jsxParseElement = function () {
  6036. var startPos = this.state.start;
  6037. var startLoc = this.state.startLoc;
  6038. this.next();
  6039. return this.jsxParseElementAt(startPos, startLoc);
  6040. };
  6041. var jsxPlugin = function (instance) {
  6042. instance.extend("parseExprAtom", function (inner) {
  6043. return function (refShortHandDefaultPos) {
  6044. if (this.match(types.jsxText)) {
  6045. var node = this.parseLiteral(this.state.value, "JSXText");
  6046. // https://github.com/babel/babel/issues/2078
  6047. node.extra = null;
  6048. return node;
  6049. } else if (this.match(types.jsxTagStart)) {
  6050. return this.jsxParseElement();
  6051. } else {
  6052. return inner.call(this, refShortHandDefaultPos);
  6053. }
  6054. };
  6055. });
  6056. instance.extend("readToken", function (inner) {
  6057. return function (code) {
  6058. if (this.state.inPropertyName) return inner.call(this, code);
  6059. var context = this.curContext();
  6060. if (context === types$1.j_expr) {
  6061. return this.jsxReadToken();
  6062. }
  6063. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  6064. if (isIdentifierStart(code)) {
  6065. return this.jsxReadWord();
  6066. }
  6067. if (code === 62) {
  6068. ++this.state.pos;
  6069. return this.finishToken(types.jsxTagEnd);
  6070. }
  6071. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  6072. return this.jsxReadString(code);
  6073. }
  6074. }
  6075. if (code === 60 && this.state.exprAllowed) {
  6076. ++this.state.pos;
  6077. return this.finishToken(types.jsxTagStart);
  6078. }
  6079. return inner.call(this, code);
  6080. };
  6081. });
  6082. instance.extend("updateContext", function (inner) {
  6083. return function (prevType) {
  6084. if (this.match(types.braceL)) {
  6085. var curContext = this.curContext();
  6086. if (curContext === types$1.j_oTag) {
  6087. this.state.context.push(types$1.braceExpression);
  6088. } else if (curContext === types$1.j_expr) {
  6089. this.state.context.push(types$1.templateQuasi);
  6090. } else {
  6091. inner.call(this, prevType);
  6092. }
  6093. this.state.exprAllowed = true;
  6094. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  6095. this.state.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore
  6096. this.state.context.push(types$1.j_cTag); // reconsider as closing tag context
  6097. this.state.exprAllowed = false;
  6098. } else {
  6099. return inner.call(this, prevType);
  6100. }
  6101. };
  6102. });
  6103. };
  6104. plugins.estree = estreePlugin;
  6105. plugins.flow = flowPlugin;
  6106. plugins.jsx = jsxPlugin;
  6107. function parse(input, options) {
  6108. return new Parser(options, input).parse();
  6109. }
  6110. function parseExpression(input, options) {
  6111. var parser = new Parser(options, input);
  6112. if (parser.options.strictMode) {
  6113. parser.state.strict = true;
  6114. }
  6115. return parser.getExpression();
  6116. }
  6117. exports.parse = parse;
  6118. exports.parseExpression = parseExpression;
  6119. exports.tokTypes = types;